我的 df 與時間列是這樣的:
time
12:30
12:15
12:00
我需要像這樣的浮點型別:
time
12.5
12.25
12.00
我努力了:
df.time = df.time.replace(":", ".", regex=True).astype(float)
但我的結果并不令人滿意,如下所示:
time
12.3
12.15
12.00
請問有什么想法嗎?
uj5u.com熱心網友回復:
一種解決方案是pandas.to_timedelta在輸入字串的修改版本上使用(以匹配預期格式),然后轉換為total_seconds并除以 60:
df['time_float'] = pd.to_timedelta('00:' df['time']).dt.total_seconds()/60
輸出:
time time_float
0 12:30 12.50
1 12:15 12.25
2 12:00 12.00
替代使用str.replace您最初的意圖:
df['time'] = (df['time']
.str.replace('(:)(\d )',
lambda x: f'.{100*int(x.group(2))//60}',
regex=True)
.astype(float)
)
uj5u.com熱心網友回復:
to_timedelta與 append :00by一起使用Series.add,然后轉換為 seconds bySeries.dt.total_seconds和 last 除以60:
df['time'] = pd.to_timedelta(df['time'].add(':00')).dt.total_seconds().div(3600)
print (df)
0 12.50
1 12.25
2 12.00
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/444909.html
