简体   繁体   English

python pandas-总结两个具有不同格式的变量

[英]python pandas - summing up two variables with different formats

I'm trying to sum up two variables using following code. 我正在尝试使用以下代码总结两个变量。

data['C'] = data['A'] + data['B']

My data has two variables A and B. A is in datetime format and B is object. 我的数据有两个变量A和B。A为日期时间格式,B为对象。 I tried to convert B to datetime format using to_datetime but it's giving me error. 我试图使用to_datetime将B转换为datetime格式,但这给了我错误。

PS: B variable doesn't have consistent data. PS:B变量没有一致的数据。

PFB sample data attached as image. PFB样本数据作为图像附加。

How can I sum up A and B. 如何总结A和B。

Appreciate your help. 感谢您的帮助。 Thanks. 谢谢。

Sample data: 样本数据:

在此处输入图片说明

You can use to_timedelta for convert column B if integer values are days : 如果整数值为days则可以使用to_timedelta转换B列:

data = pd.DataFrame({'A':['2012-03-04','2012-11-30','2014-01-25'], 
                     'B':[7,7,'111 days 00:00:00']})
data.A = pd.to_datetime(data.A)
print (data))
           A                  B
0 2012-03-04                  7
1 2012-11-30                  7
2 2014-01-25  111 days 00:00:00

data.B = pd.to_timedelta(data.B, unit='D')
data['C'] = data.A + data.B
print (data)
           A        B          C
0 2012-03-04   7 days 2012-03-11
1 2012-11-30   7 days 2012-12-07
2 2014-01-25 111 days 2014-05-16

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

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