python - Pandas Lambda 函数 : attribute error 'occurred at index 0'

标签 python pandas lambda

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

我定义了一个函数来从日期时间字段 n (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

索引列导致错误。我如何确保 this 不提供给函数?

最佳答案

你的错误是你的日期是 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 来获取日期。访问器(accessor)

关于python - Pandas Lambda 函数 : attribute error 'occurred at index 0' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33120959/

相关文章:

python - pdfkit 没有在网页中获取嵌入图像

python - 使用 Pandas 对值(value)和时间指数的下采样或平均数据

python - Pandas:对于排序系列 B 的所有元素,查找排序系列 A 中最接近元素的索引

c++ - 使用 C++11 占位符作为 lambdas?

python - 在python中解析xml文件的数据

python - C++ 中基本 Boost 使用的段错误

python - Pants python - 为每个目录构建文件

python - 如何重新索引 Pandas Dataframe 的 MultiIndex 列?

c++ - < : and :> mean when declaring a lambda? 做什么

java - 使用 Java 8 流运算符将两级映射列表减少为单个两级映射