gpt4 book ai didi

python - PANDAS:通过在其他列上应用条件从列中提取值

转载 作者:行者123 更新时间:2023-11-28 21:53:44 25 4
gpt4 key购买 nike

我有下表

 Label   B   C
1 5 91
1 5 65
1 5 93
-1 5 54
-1 5 48
1 10 66
1 10 54
-1 10 15

对于 B 中的每组值,我只想要 C 中标记为“1”的那些值。我想从 C 中提取这些值,如下所示:[[91 65 93],[66 54]]在 python 中实现类似的事情很容易,但我想用 pandas 做同样的事情。

最佳答案

您可以将 df 过滤为 Label 为 1 的那些值,然后在剩余的列上按 B 分组并获取 C 的唯一值:

In [26]:

gp = df[df['Label']==1][['B','C']].groupby('B')
gp['C'].unique()
Out[26]:
B
5 [91, 65, 93]
10 [66, 54]
Name: C, dtype: object

您也可以将其转换为数组列表:

In [36]:

list(gp['C'].unique().values)
Out[36]:
[array([91, 65, 93], dtype=int64), array([66, 54], dtype=int64)]

关于python - PANDAS:通过在其他列上应用条件从列中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25651163/

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