pandas 尝试从日期列中提取年份时,“AttributeError: Can only use .dt accessor with datetimelike values”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46271332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"AttributeError: Can only use .dt accessor with datetimelike values" when trying to extract year from a date column
提问by Lucy
I got a dateframe which there is one column 'brth_dt' and its type is datetime64[ns].I want to extract the age of persons,however when input:
all_df['brth_dt'].dt.year or
all_df['age'] = (pd.datetime.today().year - all_df['brth_dt'].dt.year)
我有一个日期框,其中有一列“brth_dt”,它的类型是 datetime64[ns]。我想提取人的年龄,但是当输入时:all_df['brth_dt'].dt.year 或
all_df['age' ] = (pd.datetime.today().year - all_df['brth_dt'].dt.year)
coming up an error:can only use .dt accessor with datetimelike values
出现错误:只能使用具有类似日期时间的值的 .dt 访问器
brth_dt columns are like this:
brth_dt 列是这样的:
brth_date
1 14Oct1978
2 21Aug1970
3 06Jan1980
4 09Mar1992
any advice?thanks!
有什么建议吗?谢谢!
回答by Vaishali
You need to convert the column to datetime first using
您需要首先使用将列转换为日期时间
df['brth_date'] = pd.to_datetime(df['brth_date'], format = '%d%b%Y')
The you can use the dt accessor
您可以使用 dt 访问器
df['brth_date'].dt.year
You get
你得到
1 1978
2 1970
3 1980
4 1992