python pandas extract year from datetime --- df ['year'] = df ['date']。year is not working [英] python pandas extract year from datetime --- df['year'] = df['date'].year is not working

查看:1772
本文介绍了python pandas extract year from datetime --- df ['year'] = df ['date']。year is not working的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,这个问题似乎重复 - 我希望答案会让我感觉像一个骨头...但我没有运气使用相似的问题的答案SO。

Sorry for this question that seems repetitive - I expect the answer will make me feel like a bonehead... but I have not had any luck using answers to the similar questions on SO.

我通过 read_csv 导入数据,但由于某些原因我无法确定,我无法从数据框中提取年份或月份系列 df ['date']

I am importing data in through read_csv, but for some reason which I cannot figure out, I am not able to extract the year or month from the dataframe series df['date'].

date    Count
6/30/2010   525
7/30/2010   136
8/31/2010   125
9/30/2010   84
10/29/2010  4469

df = pd.read_csv('sample_data.csv',parse_dates=True)

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

df['year'] = df['date'].year
df['month'] = df['date'].month

但是这返回:


AttributeError:'Series'没有属性'年'

AttributeError: 'Series' object has no attribute 'year'

提前感谢。

更新:

df = pd.read_csv('sample_data.csv',parse_dates=True)

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

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month

这会产生相同的AttributeError:'Series'对象没有属性'dt'

this generates the same "AttributeError: 'Series' object has no attribute 'dt' "

FOLLOW UP:

FOLLOW UP:

我使用Spyder 2.3.1与Python 3.4.1 64bit,但不能将大熊猫更新到较新的版本(目前在0.14.1)。以下每个都会生成无效的语法错误:

I am using Spyder 2.3.1 with Python 3.4.1 64bit, but cannot update pandas to a newer release (currently on 0.14.1). Each of the following generates an invalid syntax error:

conda update pandas

conda install pandas==0.15.2

conda install -f pandas

任何想法?

推荐答案

如果你正在运行一个近期版本的大熊猫,那么你可以使用datetime属性 dt 访问日期时间组件: p>

If you're running a recent-ish version of pandas then you can use the datetime attribute dt to access the datetime components:

In [6]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df
Out[6]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

编辑

看起来你正在运行一个较旧版本的大熊猫,在这种情况下下列工作:



It looks like you're running an older version of pandas in which case the following would work:

In [18]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)
df
Out[18]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

为什么它没有将它解析成 read_csv 中的日期时间,您需要传递列的顺序位置( [0] ),因为当 True 它尝试解析列 [1,2,3] 请参阅文档

Regarding why it didn't parse this into a datetime in read_csv you need to pass the ordinal position of your column ([0]) because when True it tries to parse columns [1,2,3] see the docs

In [20]:

t="""date   Count
6/30/2010   525
7/30/2010   136
8/31/2010   125
9/30/2010   84
10/29/2010  4469"""
df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
date     5 non-null datetime64[ns]
Count    5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes

所以如果您将param parse_dates = [0] 传递给 read_csv ,则不需要调用 to_datetime 在加载后的'日期'列。

So if you pass param parse_dates=[0] to read_csv there shouldn't be any need to call to_datetime on the 'date' column after loading.

这篇关于python pandas extract year from datetime --- df ['year'] = df ['date']。year is not working的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆