[英]Subtract two columns in pandas dataframe
我在pandas數據框中有兩列,以24小時格式表示一天中的小時,即18:00:00
。 它們都是對象數據類型,我想找出兩列在小時數上的差異。 例如。 18:00:00
和17:00:00
之間的17:00:00
應為1。我嘗試使用to_timedelta
函數,但即使將單位指定為“ h”,它to_timedelta
返回“未指定單位”錯誤。
d = {'col1': ['18:00:00', '19:00:00'], 'col2': ['17:00:00', '17:00:00']}
df = pd.DataFrame(data=d)
df
df['col1']-df['col2']
有人可以協助嗎? 提前致謝。
您必須to_datetime
轉換to_datetime
:
df.col1 = pd.to_datetime(df.col1)
df.col2 = pd.to_datetime(df.col2)
df.col1.sub(df.col2)
0 01:00:00
1 02:00:00
dtype: timedelta64[ns]
如果您只想要小時數的結果,請除以另一個Timedelta
:
df.col1.sub(df.col2).div(pd.Timedelta('1h'))
0 1.0
1 2.0
dtype: float64
使用
df=df.apply(pd.to_datetime)
(df.col1-df.col2).dt.seconds/3600
Out[524]:
0 1.0
1 2.0
dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.