根据条件从 Pandas DataFrame 中删除行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45489846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove rows from pandas DataFrame based on condition
提问by James Geddes
I am a newbie to pandas so please forgive the newbie question!
我是Pandas的新手,所以请原谅新手问题!
I have the following code;
我有以下代码;
import pandas as pd
pet_names = ["Name","Species"
"Hyman","Cat"
"Jill","Dog"
"Tom","Cat"
"Harry","Dog"
"Hannah","Dog"]
df = pd.DataFrame(pet_names)
df = df[df['Species']!='Cat']
print(df)
I would like to remove all the rows that contain "Cat" in the "Species" column, leaving all the dogs behind. How do I do this? Unfortunately, this code is currently returning errors.
我想删除“物种”列中包含“猫”的所有行,留下所有的狗。我该怎么做呢?不幸的是,此代码目前正在返回错误。
回答by cs95
General boolean indexing
一般的 boolean indexing
df[df['Species'] != 'Cat']
# df[df['Species'].ne('Cat')]
Index Name Species
1 1 Jill Dog
3 3 Harry Dog
4 4 Hannah Dog
df.query
df.query
df.query("Species != 'Cat'")
Index Name Species
1 1 Jill Dog
3 3 Harry Dog
4 4 Hannah Dog
For information on the pd.eval()family of functions, their features and use cases, please visit Dynamic Expression Evaluation in pandas using pd.eval().
有关pd.eval()函数系列、它们的特性和用例的信息,请使用 pd.eval()访问Pandas 中的动态表达式评估。
df.isin
df.isin
df[~df['Species'].isin(['Cat'])]
Index Name Species
1 1 Jill Dog
3 3 Harry Dog
4 4 Hannah Dog

