【发布时间】:2016-05-02 23:34:33
【问题描述】:
从Reading CSV file in Pandas with historical dates 开始,我在表单中有一些 CSV 数据:
Object,Earliest Date
Object1,01/01/2000
Object2,01/01/1760
Object3,01/01/1520
...
我现在读到了 Pandas(使用 Period 来处理历史日期)并创建了一个系列。我试图将这个系列分成几十年,但在将 Period 值转换为 groupby 期望的形式时磕磕绊绊。到目前为止,我已经尝试过(其中 s 是从_csv 创建的系列):
def dt_parse(s):
try:
d,m,y = s.split('/')
return pd.Period(year=int(y), month=int(m), day=int(d), freq='D')
except:
return pd.NaT
s2 = s['Earliest Date'].apply(dt_parse) #Create Period values
pi = pd.PeriodIndex(s2)
decades = pi.groupby(pd.Grouper(freq="120M")).count()
失败:
TypeError: Argument 'labels' has incorrect type (expected numpy.ndarray, got TimeGrouper)
尝试将其作为一个系列进行分组:
decades = s2.groupby(pd.Grouper(freq="120M")).count()
失败:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
尝试将其作为 DataFrame 分组:
df = pd.DataFrame(s2)
decades = df.groupby(pd.Grouper(freq="120M", key='Earliest Date')).size()
失败:
AttributeError: 'Index' object has no attribute 'to_timestamp'
不知道还能怎么做?!
【问题讨论】:
-
dt_parse 是做什么的?我怀疑将
as_index=False传递给 df.groupby() 会做你想做的事。 -
dt_parse 将日期作为句点返回(参见第一个链接)。在 df.groupby 调用中添加了 as_index=False(没有键 arg as 似乎不适用),现在得到与系列相同的错误(TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但有一个实例'索引')