根据条件从pandas DataFrame中删除行

时间:2017-08-03 16:27:25

标签: python pandas dataframe filter

我是熊猫的新手所以请原谅新手问题!

我有以下代码;

import pandas as pd

pet_names = ["Name","Species"
"Jack","Cat"
"Jill","Dog"
"Tom","Cat"
"Harry","Dog"
"Hannah","Dog"]

df = pd.DataFrame(pet_names)

df = df[df['Species']!='Cat']

print(df)

我想删除“Species”列中包含“Cat”的所有行,将所有狗留在后面。我该怎么做呢?不幸的是,此代码目前正在返回错误。

1 个答案:

答案 0 :(得分:16)

一般 boolean indexing

In [1093]: df[df.Species != 'Cat']
Out[1093]: 
  Index    Name Species
1     1    Jill     Dog
3     3   Harry     Dog
4     4  Hannah     Dog

df.ne(或~df.eq

In [1100]: df[df.Species.ne('Cat')]
Out[1100]: 
  Index    Name Species
1     1    Jill     Dog
3     3   Harry     Dog
4     4  Hannah     Dog

df.query

In [1096]: df.query("Species != 'Cat'")
Out[1096]: 
  Index    Name Species
1     1    Jill     Dog
3     3   Harry     Dog
4     4  Hannah     Dog

有关pd.eval()系列功能,其功能和用例的信息,请访问Dynamic Expression Evaluation in pandas using pd.eval()

df.isin

In [1089]: df[~df.Species.isin(['Cat'])]
Out[1089]: 
  Index    Name Species
1     1    Jill     Dog
3     3   Harry     Dog
4     4  Hannah     Dog