gpt4 book ai didi

python-3.x - 如果其中一个列值与另一个数组匹配,则返回唯一 ID 的数据框及其所有行

转载 作者:行者123 更新时间:2023-12-01 03:03:45 25 4
gpt4 key购买 nike

 df=
id - val1
1 - 50
2 - 40
1 - 60
2 - 41

a = [50]

output = id - val1
1 - 50
1 - 60

假设我有一个像 df 这样的 Pandas 数据框和一个像 'a' 这样的数组。现在,如果 df 列的 val1 列的任何值与此数组匹配,我想返回唯一 ID 的所有条目(如输出)。我该怎么做?

最佳答案

您可以使用 groupby.transformisinany :

df[df.groupby('id')['val1'].transform(lambda x: x.isin(a).any())]

或者,嵌套的 isin:

df.loc[df['id'].isin(df.loc[df['val1'].isin(a), 'id'])]

[输出]

   id  val1
0 1 50
2 1 60

关于python-3.x - 如果其中一个列值与另一个数组匹配,则返回唯一 ID 的数据框及其所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60614265/

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