python - 分组行 python pandas

标签 python pandas dataframe

假设我有以下数据框,索引代表年龄,列名是某个类别,框架中的值是频率...

现在我想以各种方式对年龄进行分组(2 年分箱、5 年分箱和 10 年分箱)

>>> table_w
      1    2    3    4
20  1000   80   40  100
21  2000   40  100  100
22  3000   70   70  200
23  3000  100   90  100
24  2000   90   90  200
25  2000  100   80  200
26  2000   90   60  100
27  1000  100   30  200
28  1000  100   90  100
29  1000   60   70  100
30  1000   70  100  100
31   900   40  100   90
32   700  100   30  100
33   700   30   50   90
34   600   10   40  100

我想以这样的方式结束......

           1    2    3    4
20-21    3000  ...  ...  ...
22-23    6000  ...  ...  ...
24-25    4000  ...  ...  ...
26-27    3000  ...  ...  ...
28-29    2000  ...  ...  ...
30-31    1900  ...  ...  ...
32-33    1400  ...  ...  ...
34        600  ...  ...  ...

有没有一种简单有效的方法来做到这一点?

非常感谢任何帮助...

最佳答案

使用 pd.cut() 创建年龄分箱并将您的数据框与它们分组。

import io

import numpy as np
import pandas as pd

data = io.StringIO("""\
       1    2    3    4
20  1000   80   40  100
21  2000   40  100  100
22  3000   70   70  200
23  3000  100   90  100
24  2000   90   90  200
25  2000  100   80  200
26  2000   90   60  100
27  1000  100   30  200
28  1000  100   90  100
29  1000   60   70  100
30  1000   70  100  100
31   900   40  100   90
32   700  100   30  100
33   700   30   50   90
34   600   10   40  100
""")
df = pd.read_csv(data, delim_whitespace=True)

bins = np.arange(20, 37, 2)
df.groupby(pd.cut(df.index, bins, right=False)).sum()

输出:

             1    2    3    4
[20, 22)  3000  120  140  200
[22, 24)  6000  170  160  300
[24, 26)  4000  190  170  400
[26, 28)  3000  190   90  300
[28, 30)  2000  160  160  200
[30, 32)  1900  110  200  190
[32, 34)  1400  130   80  190
[34, 36)   600   10   40  100

关于python - 分组行 python pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38311120/

相关文章:

python - Chrome headless 忽略系统代理

python - 检测具有混合变量类型的几乎重复的行

Pandas .plot.hist() 与 .groupby()

Python pandas 通过检查值是否更改然后之前的值进行分组

python - 对于任何索引,返回前两个索引中的最小值

python - 使用 Python/Pandas 库从 JSON 响应中解析数据时遇到问题

pandas - 根据另一个数据框 python pandas 替换列值? (初学者)

python - 每个日期的聚合数据帧值

python - 使用 pandas 创建一个由 DataFrame 中的列表组成的新列

python - 在 Django 模板中获取代理用户对象