我有一个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,2,第四组中的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'值的和。 请在这部分给我建议和指导
也许对这些结果分组进行编号是一个更好的主意。 在这种情况下,您可以检查序列中的值是否小于或等于移位版本,并获取布尔结果的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
请尝试以下操作:
df['G'] = df.E.eq('1').cumsum()