【问题标题】:Generate series from long-format data从长格式数据生成系列
【发布时间】:2023-03-22 07:19:01
【问题描述】:
df
      date      fruit    type   count   mean      comment
0   2010-01-05   apple   fruit    3    0.280949   apple is best
1   2010-01-05   banana  yellow   3    0.480949   banana not in stock
2   2010-01-05   apple    green   3    0.587949   apple is best
3   2010-01-05   bana     fruit   4    0.80949    banana not in stock
...

有没有办法为每种水果和类型组合获取时间序列序列(x = 年份,y = 平均值)。 (然后我可以计算滚动平均值;需要通用代码,因为有很多类型)。例如对于苹果,我需要两个生成时间序列:apple_fruit 和 apple_green:

date         mean
2010-01-05   0.280949
...
date         mean
2010-01-05   0.587949   
...

【问题讨论】:

  • 为什么你们的日期都一样?
  • 我刚刚为上下文添加了一个注释变量。
  • 我不明白你为什么要生成一个时间序列,如果你的日期都是一样的......
  • 有几年的每一天的日期。我只是提供了一天价值样本的快照。
  • 因此,如果您为每种水果/类型组合获得多个不同的日期,您希望保留哪个日期?

标签: python python-3.x pandas dataframe


【解决方案1】:

您可以使用基于fruittype 列拆分数据框

l = list(df.groupby(['fruit', 'type']))

其中l[i][0] 将是fruittype 组合,l[i][1] 将是与组合匹配的数据帧的子集

样本

df = pd.DataFrame({
                   'date': pd.date_range(start='2016-01-01 09:30:00', periods=40, freq='d'),
                   'fruit': ['apple', 'banana', 'apple', 'banana']*10,
                   'type' : ['fruit', 'yellow', 'green', 'fruit']*10,
                   'count' : [3]*40,
                   'mean'  : np.random.randn(40),
})

for g in  list(df.groupby(['fruit', 'type'])):
    print ("{0} {1}".format(*g[0]))
    print (g[1][['date', 'mean']])

如果您打算基于fruittype 组合采用滚动平均值,您可以使用

df.sort_values('date').groupby(['fruit', 'type'])['mean'].rolling(1).mean()

不需要显式拆分。

你也可以使用

for g in list(df.sort_values('date').groupby(['fruit', 'type'])):
  print ("{0} {1}".format(*g[0]))
  print (g[1]['mean'].rolling(1).mean())

【讨论】:

  • 由于结尾行是打印语句,它会生成系列吗?
猜你喜欢
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 2018-11-18
  • 1970-01-01
  • 2013-03-26
  • 2016-05-23
相关资源
最近更新 更多