在Pandas中对Period系列值进行分组

时间:2016-05-02 23:34:33

标签: python pandas period

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处理历史日期)并创建了一个系列。我试图把这个系列分成几十年,但是期望将期间值加入到表格组中的绊脚石。到目前为止,我已经尝试过(其中s是从from_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'

不知道怎么做?!

1 个答案:

答案 0 :(得分:0)

错误消息和pandas文档将成为您的朋友。

我不知道您的日期列是否包含严格的唯一日期。如果它们是,它是微不足道的,只需将它用作索引,您就可以使用pd.Grouper。否则,请定义您自己的分组功能:

def grouper(ind):
    y = df.loc[ind]['Earliest Date'].year 
    return y - (y % 10)

# I'm assuming that df is the dataframe from pd.read_csv("/path/to/csv")
# and that there's a column named "earliest date" 
# that is a Period or Datetime or something with a year attribute
gb = df.groupby(by=grouper)
print(gb.size())