2 回答

TA貢獻1872條經驗 獲得超4個贊
嘗試使用正則表達式。
前任:
import re
def p_time(val):
try:
t = 0
h = re.search(r"(\d+) hour(s)?", val)
if h:
t += int(h.group(1)) * 60
m = re.search(r"(\d+) minute(s)?", val)
if m:
t += int(m.group(1))
return t
except:
pass
return 0
s = pd.Series(['1 hour and 59 minutes','2 hours', np.nan, '38 minutes', '4 hours and 31 minute'])
print(s.apply(p_time).astype(int))
輸出:
0 119
1 120
2 0
3 38
4 271
dtype: int32

TA貢獻1744條經驗 獲得超4個贊
另一種方法可能只是用于numexpr評估數值方程:
import numexpr
foo = pd.Series(['1 hour and 59 minutes','2 hours', np.nan, '38 minutes', '4 hours and 31 minutes'])
(foo.str.replace(r' hours?','*60').str.replace(' minutes','').str.replace(' and ', '+')
.fillna('0').apply(numexpr.evaluate))
輸出:
0 119
1 120
2 0
3 38
4 271
添加回答
舉報