函数:属性错误“发生在索引0处”

时间:2021-08-19 19:07:58

I am using Pandas to create a new column in a data frame created from a csv.

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

I define a function to strip the time from the datetime fieldn (dCount) and then create a new column 'date'

我定义一个函数,从datetime fieldn (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')

There is some issue with the index_col. I previously used index_col = 1 but got the same error.

index_col有一些问题。我之前使用了index_col = 1,但是得到了相同的错误。

When I print 'dCount' I get

当我打印'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

The index column is causing the error. How do I ensure this isn't given to the function?

索引列导致错误。如何确保这个函数不被赋给函数?

1 个解决方案

#1


3  

Your error here is that your dates are str not datetime, either convert using to_datetime:

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

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

or better just tell read_csv to parse that column as datetime:

或者最好告诉read_csv将该列解析为datetime:

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

Afterwards you can then get just the date by calling the dt.date accessor

然后,您可以通过调用dt来获得日期。访问日期

#1


3  

Your error here is that your dates are str not datetime, either convert using to_datetime:

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

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

or better just tell read_csv to parse that column as datetime:

或者最好告诉read_csv将该列解析为datetime:

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

Afterwards you can then get just the date by calling the dt.date accessor

然后,您可以通过调用dt来获得日期。访问日期