首页 > 解决方案 > 如何在python中按有序数字1、123、12、12 ..等进行分组

问题描述

我有一个有 3303 行的数据。我在 python 中使用熊猫

df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'],'B': ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'], 'C': np.random.randn(8),'D': np.random.randn(8), 'E':['1','1','2','3','1','2','1','2',]})

OUTPUT:
     A   B          C            D      E
0   foo one     -1.607303   1.343192    1
1   bar one      2.064340   1.000130    1
2   foo two     -0.362983   1.113389    2
3   bar three    0.486864   -0.804323   3
4   foo two      0.111030   -0.322696   1
5   bar two     -0.729870   0.912012    2
6   foo one      1.111405   0.076317    1
7   foo three    0.378172   0.298974    2

您知道如何按数字顺序对“E”列进行分组吗?意义; 关于如何按迭代进行分组的任何想法,例如第一组中的 1,2,3,第二组中的 1,2,第三组中的 1,第四组中的 1,2……等等,这样就会像

     A   B          C            D      E  G
0   foo one     -1.607303   1.343192    1  a
1   bar one      2.064340   1.000130    1  b
2   foo two     -0.362983   1.113389    2  b
3   bar three    0.486864   -0.804323   3  b
4   foo two      0.111030   -0.322696   1  c
5   bar two     -0.729870   0.912012    2  c
6   foo one      1.111405   0.076317    1  d
7   foo three    0.378172   0.298974    2  d

这样它就像新列“H”、“I”具有按“G”分组的“C”和“D”值之和。请在这部分建议和指导我

标签: pythonpandaspandas-groupby

解决方案


尝试这个:

df['G'] = df.E.eq('1').cumsum()

如果每个新组都以“1”开头,则此方法有效。如果不是,您需要求助于yatu 的解决方案

要回答您的整个问题:

df[['H','I']] = df.groupby(df.E.eq('1').cumsum())[['C','D']].transform(sum)

推荐阅读