简体   繁体   English

减去日期以获得熊猫天数

[英]Subtracting Dates to get Days in pandas

I have 2 columns date_1 ( dtype('O') ) and date_2( dtype(') 我有2列date_1(dtype( 'O') )和date_2(dtype (')

 date_1 date_2 2018-06-06 2018-04-01 

when i do subtraction to get days 当我做减法以获得日子

 df['date_1'] - df['date_2'] 

i get the error TypeError: incompatible type [object] for a datetime/timedelta operation 我收到错误TypeError:日期时间/时间增量操作的不兼容类型[object]

Need convert columns to datetime s: 需要将列转换为datetime

df['date_1'] = pd.to_datetime(df['date_1'])
df['date_2'] = pd.to_datetime(df['date_2'])

Or: 要么:

df = df.apply(pd.to_datetime)

And then: 接着:

df['days'] = (df['date_1'] - df['date_2']).dt.days

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM