我計算了資料框中的持續時間,但我想以秒為單位獲取持續時間,而不是它給出的持續時間(0 天、00:10:25 等):
df['duration'] = df['end_date'] - df['start_date']
df.head(2)
started_at ended_at start_date end_date duration
0 2021-01-23 16:14:19 2021-01-23 16:24:44 2021-01-23 16:14:19 2021-01-23 16:24:44 0 days 00:10:25
1 2021-01-27 18:43:08 2021-01-27 18:47:12 2021-01-27 18:43:08 2021-01-27 18:47:12 0 days 00:04:04
我從這里嘗試了一些解決方案,但我不確定如何正確地做,沒有任何效果;例如我試過這個:
df['duration'] = datetime.timedelta.total_seconds(df['duration'])
但它說
TypeError: descriptor 'total_seconds' for 'datetime.timedelta' objects doesn't apply to a 'Series' object
uj5u.com熱心網友回復:
您應該能夠使用 total_seconds 方法。但是,您需要通過 datetime 訪問器訪問該方法dt。
>>> df['duration'].dt.total_seconds()
但是,如果系列Duration是字串/物件-您應該使用 pd.to_timedelta
>>> pd.to_timedelta(df['duration']).dt.total_seconds()
uj5u.com熱心網友回復:
我會嘗試在您的系列上運行應用
df['duration'] = df['duration'].apply(datetime.timedelta.total_seconds)
從你的錯誤。它表明您正在嘗試在系列上運行它
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438542.html
上一篇:從字串中獲取一些單詞,直到pandas中有一個巨大的模式
下一篇:如何使用行索引值作為資料框的列?
