如何在python中对1,123,12,12......等有序数字进行分组。

问题描述 投票:0回答:2

我有一个数据有3303行。我在python中使用pandas

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'有'C'和'D'值的总和由'G'分组。

python pandas pandas-groupby
2个回答
3
投票

试试这个。

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

如果每一个新的组都是以 "1 "开头的,就可以用这个方法。如果不是,你需要使用 雅图的解决方案.

回答你的整个问题。

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

1
投票

可能吧 编号 这些结果组是一个更好的想法。在这种情况下,你可以检查系列中的值是否比移位的版本小或相等,并取下 cumsum 的布尔结果。

df['G'] = df.E.le(df.E.shift()).cumsum()

print(df)

     A      B         C         D  E  G
0  foo    one -1.495356  3.699348  1  0
1  bar    one -1.852039  0.569688  1  1
2  foo    two  0.875101  0.736014  2  1
3  bar  three -0.690525  0.132817  3  1
4  foo    two -0.742679  0.138903  1  2
5  bar    two -0.435063  1.525082  2  2
6  foo    one -0.985005  1.013949  1  3
7  foo  three  0.934254  1.157935  2  3
© www.soinside.com 2019 - 2024. All rights reserved.