繁体   English   中英

熊猫Lambda函数:属性错误“发生在索引0”

[英]Pandas Lambda Function : attribute error 'occurred at index 0'

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

我定义了一个函数,用于从datetime字段(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')

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 ,或者使用to_datetime进行转换:

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

或者更好的是告诉read_csv将该列解析为datetime:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM