[英]apply() to every column of every dataframe of an ExcelFile, Pandas
[英]Access atribute of every object in pandas dataframe column
考虑以下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])
我可以通过以下方式访问单个日期的month
属性:
df.Date[0].month
Out[22]: 10
但是, df.Date.month
不会返回包含所有月份的向量,正如我所期望的那样。 相反,它会抛出一个错误:
AttributeError:'Series'对象没有属性'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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.