gpt4 book ai didi

python - 如何在 python 中从 groupby pandas 中提取向量

转载 作者:太空狗 更新时间:2023-10-30 01:05:39 25 4
gpt4 key购买 nike

我有一个使用 pandas 的 DataFrame:

one    two  three

1 2 1
4 1 1
2 2 1
3 1 2
20 2 2

现在,我将通过对“三”进行分组来提取向量。基本上,我应该根据分组“三”从“二”列中获取向量:

groupby('three')
a=[2,1,2]
b=[1,2]

非常感谢

最佳答案

你可以使用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]

如果需要嵌套列表:

L = df.groupby('three')['two'].apply(list).tolist()
print (L)
[[2, 1, 2], [1, 2]]

另一种可能的解决方案:

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]]

关于python - 如何在 python 中从 groupby pandas 中提取向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43210427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com