【问题标题】:Pandas calculating age from a date熊猫从日期计算年龄
【发布时间】:2014-11-12 21:39:17
【问题描述】:

我真的需要这方面的帮助。我之前的帖子非常糟糕且不清楚 - 对不起 - 我希望我可以删除,但希望这篇文章会更好。

我需要根据日期计算年龄(请参阅分析部分和最终结果部分)。

原始数据集

"JOLIE", 09091959,02051983
"PORTMAN",02111979,01272002
"MOORE", 01281975,01182009
"BEST", 04081973,07022008
"MONROE", 04161957,11231979

加载数据

from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd

columns = ['lname','dob','scd_csr_mdy']

raw_data = pd.read_csv(r'C:\Users\davidlopez\Desktop\Folders\Standard Reports\HR Reports\eeprofil  \eeprofil.txt',` 
                       names=columns, parse_dates = ['dob','scd_csr_mdy'})

df1 = raw_data

In [1]: df1
Out [1]:

         lname          dob          scd_csr_mdy
    0    JOLIE          09091959     02051983
    1    PORTMAN        02111979     01272002
    2    MOORE          01281975     01182009
    3    BEST           04081973     07022008
    4    MONROE         04161957     11231979

分析

我尝试执行以下操作但收到错误:

now = datetime.now()
df1['age'] = now - df1['dob']

但我收到了错误:

TypeError:  unsported operant type(S) for -: 'datetime.datetime' and 'str'

最终结果

     lname          dob          scd_csr_mdy    DOB_AGE     SCD_AGE
0    JOLIE          09091959     02051983       55          32
1    PORTMAN        02111979     01272002       36          13
2    MOORE          01281975     01182009       40          6
3    BEST           04081973     07022008       42          6
4    MONROE         04161957     11231979       58          35

有什么建议吗.....?

【问题讨论】:

  • type(df1['dob'])的输出是什么?
  • 我猜这是一个字符串,正如TypeError 的输出所示
  • dtype(['dob']) is 'o'

标签: python numpy pandas


【解决方案1】:

将 dob 列从字符串转换为日期时间对象

df1['dob'] = pd.to_datetime(df1['dob'])
now = datetime.now()    
df1['age'] = now - df1['dob']

【讨论】:

  • 这给了我同样的错误 TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'
  • 你能用这个检查熊猫版本吗:pd.__version__
  • pd.__version__ 0.13.1
  • 嗯,不知道发生了什么。该代码似乎确实在我的最后工作。似乎它必须对 csv 做一些事情。当我使用 pd.read_clipboard() 读取您的数据帧时,即先复制数据帧,然后运行命令;日期时间的东西对我有用
【解决方案2】:

使用格式将字符串转换为日期时间

df1['age'] = now - datetime.strptime(df1['dob'], "%m%d%Y")

【讨论】:

    【解决方案3】:

    如果没有太多条目,您可以执行以下操作:

    df['dob'] = df.dob.apply(lambda d: pd.to_datetime(d[-4:] + d[:4]))
    now - df.dob
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多