Pandas 中的分组期间系列值

Grouping Period series values in Pandas

开始,我有一些 CSV 数据,格式如下:

Object,Earliest Date
Object1,01/01/2000
Object2,01/01/1760
Object3,01/01/1520
...

我现在已经阅读了 Pandas(使用 Period 来处理历史日期)并创建了一个系列。我正在尝试将系列分为几十年,但在将 Period 值设置为 groupby 期望的形式时遇到了麻烦。到目前为止,我已经尝试过(其中 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'

不知道还能怎么做?!

错误消息和 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())