我有一个数据框架,df,有以下列:
df['ArrivalDate'] =
...
936 2012-12-31
938 2012-12-29
965 2012-12-31
966 2012-12-31
967 2012-12-31
968 2012-12-31
969 2012-12-31
970 2012-12-29
971 2012-12-31
972 2012-12-29
973 2012-12-29
...
列的元素是pandas. tslip . timestamp。
我想只包括年份和月份。我以为会有简单的方法,但我想不出来。
以下是我的尝试:
df['ArrivalDate'].resample('M', how = 'mean')
我得到了以下错误:
Only valid with DatetimeIndex or PeriodIndex
然后我试着:
df['ArrivalDate'].apply(lambda(x):x[:-2])
我得到了以下错误:
'Timestamp' object has no attribute '__getitem__'
有什么建议吗?
编辑:我有点明白了。
df.index = df['ArrivalDate']
然后,我可以使用索引重新采样另一列。
但是我仍然想要一个重新配置整个列的方法。什么好主意吗?
@KieranPC的解决方案是Pandas的正确方法,但不容易扩展到任意属性。为此,你可以在生成器理解中使用getattr,并使用pd.concat进行组合:
# input data
list_of_dates = ['2012-12-31', '2012-12-29', '2012-12-30']
df = pd.DataFrame({'ArrivalDate': pd.to_datetime(list_of_dates)})
# define list of attributes required
L = ['year', 'month', 'day', 'dayofweek', 'dayofyear', 'weekofyear', 'quarter']
# define generator expression of series, one for each attribute
date_gen = (getattr(df['ArrivalDate'].dt, i).rename(i) for i in L)
# concatenate results and join to original dataframe
df = df.join(pd.concat(date_gen, axis=1))
print(df)
ArrivalDate year month day dayofweek dayofyear weekofyear quarter
0 2012-12-31 2012 12 31 0 366 1 4
1 2012-12-29 2012 12 29 5 364 52 4
2 2012-12-30 2012 12 30 6 365 52 4