考虑以下 mwe:
import pandas as pd
from decimal import *
from datetime import date
d1={'Date':date(2016,10,24),'Value':Decimal(20)}
d2={'Date':date(2016,10,25),'Value':Decimal(10)}
d3={'Date':date(2016,9,25),'Value':Decimal(50)}
d4={'Date':date(2016,9,24),'Value':Decimal(5)}
df=pd.DataFrame([d1,d2,d3,d4])
我可以通过以下方式访问单个日期的月
属性:
df.Date[0].month
Out[22]: 10
但是df.Date.month
不会返回包含我所期望的所有月份的向量。相反,它会抛出一个错误:
AttributeError: 'Series' object has no attribute 'month'
有没有一种好的方法可以完成此任务,而无需迭代数据帧?
最佳答案
您需要先转换 to_datetime
然后使用 dt.month
:
print (pd.to_datetime(df.Date).dt.month)
0 10
1 10
2 9
3 9
Name: Date, dtype: int64
使用 apply
的另一个较慢的解决方案:
print (df.Date.apply(lambda x: x.month))
0 10
1 10
2 9
3 9
Name: Date, dtype: int64
时间:
#[40000 rows x 2 columns]
df = pd.concat([df]*10000).reset_index(drop=True)
In [292]: %timeit (df.Date.apply(lambda x: x.month))
100 loops, best of 3: 15.8 ms per loop
In [293]: %timeit (pd.to_datetime(df.Date).dt.month)
100 loops, best of 3: 5.44 ms per loop
关于python - pandas dataframe 列中每个对象的访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40218017/