【问题标题】:Grouping Period series values in Pandas在 Pandas 中对周期序列值进行分组
【发布时间】: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 有效,但有一个实例'索引')

标签: python pandas period


【解决方案1】:

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

【讨论】:

  • 太好了,现在正在工作,谢谢。对第一个项目进行了相当深入的研究,一定要回到文档中!
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 2013-01-16
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 2013-12-06
相关资源
最近更新 更多