我有一个像熊猫一样的数据框:
a b
A 1
A 2
B 5
B 5
B 4
C 6
Run Code Online (Sandbox Code Playgroud)
我希望按第一列分组,并将第二列作为行中的列表:
A [1,2]
B [5,5,4]
C [6]
Run Code Online (Sandbox Code Playgroud)
使用pandas groupby可以做这样的事吗?
这是一个数据帧:
A B C
0 6 2 -5
1 2 5 2
2 10 3 1
3 -5 2 8
4 3 6 2
Run Code Online (Sandbox Code Playgroud)
我可以检索一个列,它基本上是原始列的元组df使用df.apply:
out = df.apply(tuple, 1)
print(out)
0 (6, 2, -5)
1 (2, 5, 2)
2 (10, 3, 1)
3 (-5, 2, 8)
4 (3, 6, 2)
dtype: object
Run Code Online (Sandbox Code Playgroud)
但是,如果我想要一个值列表而不是它们的元组,我不能这样做,因为它没有给我我期望的东西:
out = df.apply(list, 1)
print(out)
A B C
0 6 2 -5
1 2 5 2
2 10 3 1
3 -5 2 …Run Code Online (Sandbox Code Playgroud)