我有两个DataFrame df:
A B
5/4/2018 8/4/2018
24/5/15 26/5/15
21/7/16 22/7/16
3/7/2015 5/7/2015
1/7/2016 1/7/2016
我想计算每一行的天差。
例如:
A B C
5/4/2018 8/4/2018 3
24/5/15 26/5/15 2
我尝试使用pd.to_datetime将数据帧转换为datetime。但是,出现错误“ ValueError:仍存在未转换的数据:18”
尝试以下代码:
import datetime as dt
df['A'] = pd.to_datetime(df['A'], format = "%d/%m/%y").datetime.datetime.strftime("%Y-%m-%d")
df['B'] = pd.to_datetime(df['B'], format = "%d/%m/%y").datetime.datetime.strftime("%Y-%m-%d")
df['C'] = (df['B'] - df['A']).dt.days
注意:使用python 3.7
答案 0 :(得分:0)
尝试:
df['A'] = pd.to_datetime(df['A'], dayfirst=True)
df['B'] = pd.to_datetime(df['B'], dayfirst=True)
df['C'] = (df['B'] - df['A']).dt.days
输出:
A B C
0 2018-04-05 2018-04-08 3
1 2015-05-24 2015-05-26 2