【问题标题】:Python manipulate timeseries data in aggregationPython 在聚合中操作时间序列数据
【发布时间】:2019-09-16 15:46:32
【问题描述】:

我有一个时间序列数据框,其中包含如下所示的列:

    perf_date  pull_date  clicks  conv      rev 
    2019-01-21 2019-01-28   56     9        44.12
    2019-01-22 2019-01-28   56     10       44.70
               2019-01-29   56     10       44.70
    2019-01-23 2019-01-28   59     13       89.31
               2019-01-29   59     13       89.31
               2019-01-30   59     14       95.31

我想做的是: 1) 根据每个 perf_date 保留第一行的所有行值。 2) 将最大 pull_date 的收入值附加到每个 perf_date。 所以在操作之后,上面的数据框应该是这样的:

    perf_date  pull_date  clicks  conv      rev 
    2019-01-21 2019-01-28   56     9        44.12
    2019-01-22 2019-01-28   56     10       44.70
    2019-01-23 2019-01-28   59     13       95.31

【问题讨论】:

  • print (df.index) 是什么?
  • 我之前使用了groupby方法,然后reset index。

标签: python pandas time-series aggregation


【解决方案1】:

GroupBy.agg 与具有聚合函数的列字典一起使用 - 您可以手动或动态传递它 - 所有没有perf_daterev 的列都由firstrevlast 聚合:

#if necessary
df['perf_date'] = df['perf_date'].ffill()
df = df.sort_values(['perf_date','pull_date'])

d = dict.fromkeys(df.columns.difference(['perf_date','rev']), 'first')
d['rev'] = 'last'
print (d)
{'clicks': 'first', 'conv': 'first', 'pull_date': 'first', 'rev': 'last'}

df = df.groupby('perf_date', as_index=False).agg(d).reindex(df.columns, axis=1)
print (df)
    perf_date   pull_date  clicks  conv    rev
0  2019-01-21  2019-01-28      56     9  44.12
1  2019-01-22  2019-01-28      56    10  44.70
2  2019-01-23  2019-01-28      59    13  95.31

编辑:

d = dict.fromkeys(df.columns.difference(['perf_date','rev']), 'first')
df1 = df.groupby('perf_date', as_index=False).agg(d)
s = df.groupby('perf_date')['rev'].nth(2)
df = df1.join(s, on='perf_date')
print (df)
    perf_date  clicks  conv   pull_date    rev
0  2019-01-21      56     9  2019-01-28    NaN
1  2019-01-22      56    10  2019-01-28    NaN
2  2019-01-23      59    13  2019-01-28  95.31

【讨论】:

  • 优秀的解决方案。如果我想为除收入之外的所有列保留第三行怎么办?这很容易吗?
  • @Nofy - 然后可以使用GroupBy.nth,检查编辑的答案。
  • 实际上你选择了第三个收入值,我想保留所有其他列的第三行和最后一个收入值
猜你喜欢
  • 2015-05-28
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 2021-04-02
  • 2011-04-28
  • 2017-03-07
  • 2016-06-14
  • 2017-06-21
相关资源
最近更新 更多