【问题标题】:Pandas Lambda Function : attribute error 'occurred at index 0'Pandas Lambda 函数:属性错误“发生在索引 0”
【发布时间】:2016-01-12 06:48:19
【问题描述】:

我正在使用 Pandas 在从 csv 创建的数据框中创建一个新列。

[in] DfT_raw = pd.read_csv('./file.csv', index_col = False)
[in] print(DfT_raw)

[out]            Region Name dCount ONS    CP  S Ref E  S Ref N   Road  \
0        East Midlands  E06000015      14/04/00 00:00  37288   434400   336000   A516   
1        East Midlands  E06000015       14/04/00 00:00  37288   434400   336000   A516   
2        East Midlands  E06000015       14/04/00 00:00  37288   434400   336000   A516   
3        East Midlands  E06000015       14/04/00 00:00  37288   434400   336000   A516   

我定义了一个函数从日期时间字段 (dCount) 中去除时间,然后创建一个新列“日期”

[in] def date_convert(dCount):
         return dCount.date()

     DfT_raw['date'] = DfT_raw.apply(lambda row: date_convert(row['dCount']), axis=1)

[out] AttributeError: ("'str' object has no attribute 'date'", u'occurred at index 0')

index_col 存在一些问题。我之前使用过 index_col = 1 但得到了同样的错误。

当我打印“dCount”时,我得到了

0          14/04/00 00:00
1          14/04/00 00:00
2          14/04/00 00:00
3          14/04/00 00:00
4          14/04/00 00:00

索引列导致错误。如何确保不会将其赋予函数?

【问题讨论】:

  • 这是一个 str 不是 datetime 对象,您需要先转换 df['dCount'] = pd.to_datetime(df['dCount']) 然后获取日期 df['dCount'].dt.date,您可以通过将 parse_dates=['dCount'] 传递给 @ 来读取这些 datetime 字符串作为 datetime 987654327@
  • DfT_raw = pd.read_csv('./file.csv', parse_dates=['dCount'],index_col = False) 完美,非常感谢!如果您愿意,请随时发布作为答案

标签: python pandas lambda


【解决方案1】:

您的错误是您的日期是str 而不是datetime,要么使用to_datetime 进行转换:

df['dCount'] = pd.to_datetime(df['dCount'])

或者更好的是告诉read_csv 将该列解析为日期时间:

DfT_raw = pd.read_csv('./file.csv', parse_dates=['dCount'],index_col = False)

之后,您可以通过调用 dt.date 访问器获取日期

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 2020-04-08
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多