这是测向样本,
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)
})
A B C D
0 foo one 1.215172 -0.861875
1 bar one -0.318147 0.384239
2 foo two 1.729844 -0.173781
3 bar three 0.331456 0.914334
4 foo two 2.038198 -0.354784
5 bar two 0.258204 -1.476305
6 foo one -0.338992 0.856365
7 foo three -0.311692. -0.159846
按A和B类分组
for name, group in df.groupby(['A', 'B']):
print(name)
print(group)
('bar', 'one')
A B C D
1 bar one -0.318147 0.384239
('bar', 'three')
A B C D
3 bar three 0.331456 0.914334
('bar', 'two')
A B C D
5 bar two 0.258204 -1.476305
('foo', 'one')
A B C D
0 foo one 1.215172 -0.861875
6 foo one -0.338992 0.856365
('foo', 'three')
A B C D
7 foo three -0.311692 -0.159846
('foo', 'two')
A B C D
2 foo two 1.729844 -0.173781
4 foo two 2.038198 -0.354784
所以我们现在有6个小组。
问题:如何添加名为G的新列,并让其值为组名(如G1、G2…G6),由行所属的组决定。
下面是df最后的样子:
A B C D G
0 foo one 1.215172 -0.861875 G4
1 bar one -0.318147 0.384239 G1
2 foo two 1.729844 -0.173781 G6
3 bar three 0.331456 0.914334 G2
4 foo two 2.038198 -0.354784 G6
5 bar two 0.258204 -1.476305 G3
6 foo one -0.338992 0.856365 G4
7 foo three -0.311692. -0.159846 G5
谢谢你的帮助。
最佳答案
有一个悬而未决的公关,我需要重新平衡-这个问题刚刚激励我绕过它:-)---这将最终给我们一个干净的方式来获取这些信息。同时,组码实际上在groupby对象中,只是隐藏了一点:
In [97]: df["GN"] = df.groupby(["A","B"]).grouper.group_info[0]
In [98]: df["G"] = "G" + (df["GN"] + 1).astype(str)
In [99]: df
Out[99]:
A B C D GN G
0 foo one -1.245506 0.307395 3 G4
1 bar one 0.072989 -0.402182 0 G1
2 foo two 0.399269 0.794413 5 G6
3 bar three 0.475859 -0.685398 1 G2
4 foo two -0.463065 -0.222632 5 G6
5 bar two 0.696606 -0.999691 2 G3
6 foo one -1.211876 -0.368574 3 G4
7 foo three -0.936385 -1.067160 4 G5
关于python - 如何为数据帧的每一行分配组名?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44229397/