我有一个使用pandas的DataFrame:
one two three
1 2 1
4 1 1
2 2 1
3 1 2
20 2 2
Run Code Online (Sandbox Code Playgroud)
现在,我将通过分组'三'来提取a向量.基本上,我应该根据"三个"分组从"两个"列中获取向量:
groupby('three')
a=[2,1,2]
b=[1,2]
Run Code Online (Sandbox Code Playgroud)
非常感谢
你可以使用groupby:
s = df.groupby('three')['two'].apply(list)
print (s)
three
1 [2, 1, 2]
2 [1, 2]
Name: two, dtype: object
a = s.loc[1]
b = s.loc[2]
print (a)
[2, 1, 2]
print (b)
[1, 2]
Run Code Online (Sandbox Code Playgroud)
如果需要嵌套列表:
L = df.groupby('three')['two'].apply(list).tolist()
print (L)
[[2, 1, 2], [1, 2]]
Run Code Online (Sandbox Code Playgroud)
另一种可能的解
L = [list(x) for i, x in df.groupby('three')['two']]
print (L)
[[2, 1, 2], [1, 2]]
L = [x.tolist() for i, x in tuple(df.groupby('three')['two'])]
print (L)
[[2, 1, 2], [1, 2]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1000 次 |
| 最近记录: |