【问题标题】:Panda convert str to Date and calculate age [duplicate]熊猫将字符串转换为日期并计算年龄[重复]
【发布时间】: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 通常是这样,但我实际上认为这是一个非常有序、独立的问题,显示了努力

标签: python pandas


【解决方案1】:

试试这个,必须工作。

df['birth_date'] = pd.to_datetime(df['Birth_Date'].str[:-2] + '19' + df['Birth_Date'].str[-2:])

要计算 AGE,您必须执行以下操作:

df['transaction_date'] = pd.to_datetime(df['Transaction_Date'])

df['age'] = df['transaction_date'].dt.year - df['birth_date'].dt.year

【讨论】:

  • 非常感谢@Nodar,这解决了我的问题
猜你喜欢
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 2018-05-26
  • 2019-07-25
  • 2017-09-17
  • 1970-01-01
  • 2020-08-26
  • 2017-05-20
相关资源
最近更新 更多