【发布时间】:2019-12-11 04:41:20
【问题描述】:
我有一张像这样的桌子
Transaction_Date | Name | Birth_Date
1/01/15 | Tom | 16/11/89
1/01/15 | Kate | 8/03/65
....
1/01/15 | Ken | 14/05/64
Transaction_Date和Birth_Date的数据类型是str
我想按 (Transaction_Date - Birth_Date) 添加年龄列
我的代码是
tableA['Transaction_Date'] = pd.to_datetime(join_table['Transaction_Date'])
tableA['Birth_Date'] = pd.to_datetime(join_table['Birth_Date'])
tableA['Age'] = tableA['Transaction_Date'] - tableA['Birth_Date']).astype('<m8[Y]'
结果如下
Transaction_Date | Name | Birth_Date | Age
2015-01-01 | Tom | 1989-11-16 | 25.0
2015-01-01 | Kate | 2065-03-08 | -50.0
....
2015-01-01 | Ken | 2064-05-14 | -49.0
Tome 的 Birth_Date 是正确的,但 Kate 或 Ken 都是错误的。凯特应该是“1965-03-08”,肯应该是“1964-05-14”
问题:int类型如何计算Age?
当我使用时
int(tableA['Age'] = tableA['Transaction_Date'] - tableA['Birth_Date']).astype('<m8[Y]'
#TypeError: cannot convert the series to <class 'int'>)
提前致谢。
【问题讨论】:
-
你应该避免问几个问题。此外,您是否先搜索了stackoverflow?这些都是非常常见的问题。
-
是的,我按照搜索得到这个计算结果和日期转换结果。而且我对python有点陌生,所以结果可能会让我有点困惑
-
@LoneWanderer 通常是这样,但我实际上认为这是一个非常有序、独立的问题,显示了努力