【问题标题】:Aggregate pandas dataframe by value range of certain columns按某些列的值范围聚合熊猫数据框
【发布时间】:2017-09-26 21:30:42
【问题描述】:

数据如下:

time  value
1995  1
1995  2
1997  3
1998  5
2005  4
2004  7

如何将年份替换为年份范围:

time       value
1995-2000   1
1995-2000   2
1995-2000   3
1995-2000   5
2000-2005   4
2000-2005   7

谢谢

【问题讨论】:

  • aggregate 是什么意思?您只是想用范围替换 time 吗?
  • 是的,只需替换即可。

标签: python dataframe aggregation


【解决方案1】:

源 DF

In [222]: x
Out[222]:
   time  value
0  1995      1
1  1995      2
2  1997      3
3  1998      5
4  2005      4
5  2004      7

分箱time 列:

In [223]: x.time = pd.cut(x.time, bins=np.arange(1995, 2005+5, step=5), include_lowest=True)

In [224]: x
Out[224]:
           time  value
0  [1995, 2000]      1
1  [1995, 2000]      2
2  [1995, 2000]      3
3  [1995, 2000]      5
4  (2000, 2005]      4
5  (2000, 2005]      7

聚合:

In [221]: x.groupby(pd.cut(x.time, bins=np.arange(1995, 2005+5, step=5),
                           include_lowest=True))['value'] \
           .sum()
Out[221]:
time
[1995, 2000]    11
(2000, 2005]    11
Name: value, dtype: int64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2019-08-02
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多