gpt4 book ai didi

python Pandas : removing rows not matching multiple conditions from dataframe

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:35 27 4
gpt4 key购买 nike

假设我有一个像这样使用 pandas.dataframe 的列:

index  fruits    origin      attribute
1 apple USA tasty
2 apple France yummy
3 apple USA juicy
4 apple England juicy
5 apple Japan normal
6 banana Canada nice
7 banana Italy good
.....

我想选择 yummy apple from France(2) 并从表中删除不匹配的 apples,如下所示:

index  fruits    origin      attribute
1 apple France yummy
2 banana Canada nice
3 banana Italy good
.....

我认为以下应该可行。但事实并非如此:

df.drop(df[(df.fruits == "apple") & (df.origin != "France") | (df.fruits == "apple") & (df.attribute != "yummy")].index)

然后我尝试了以下也不起作用:

df = df[~df[(df.fruits == "apple") & (df.origin != "France") & (df.attribute != "yummy")]

有什么帮助吗,小伙子们?

最佳答案

如果按条件选择:

df[(df.fruits != 'apple') | ((df.fruits == 'apple') & (df.origin == 'France') & (df.attribute == 'yummy'))]

#index fruits origin attribute
#1 2 apple France yummy
#5 6 banana Canada nice
#6 7 banana Italy good

如果按不匹配条件移除:需要移除的是fruits为apple但origin不匹配France的行或者 attributeyummy 不匹配:

df[~((df.fruits == 'apple') & ((df.origin != 'France') | (df.attribute != 'yummy')))]

# index fruits origin attribute
#1 2 apple France yummy
#5 6 banana Canada nice
#6 7 banana Italy good

关于 python Pandas : removing rows not matching multiple conditions from dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45558673/

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