Pandas Lambda函数:索引0处发生属性错误

2024-06-15 12:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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   

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

[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')

索引列有问题。我以前使用索引列=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

索引列导致错误。如何确保这不是给函数的?


Tags: csv函数inrefconvertdateindexraw
1条回答
网友
1楼 · 发布于 2024-06-15 12:34:07

这里的错误是您的日期是str而不是datetime,请使用^{}转换:

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

或者最好告诉^{}将该列解析为datetime:

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

然后,您可以通过调用^{}访问器来获取日期

相关问题 更多 >