根据条件从pandas DataFrame中删除行 [英] Remove rows from pandas DataFrame based on condition

查看:198
本文介绍了根据条件从pandas DataFrame中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a newbie to pandas so please forgive the newbie question!

我有以下代码;

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)的行,而将所有的狗都留在后面.我该怎么做呢?不幸的是,此代码当前返回错误.

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.

推荐答案

常规 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

有关pd.eval()功能家族,其功能和使用案例的信息,请访问

For information on the pd.eval() family of functions, their features and use cases, please visit Dynamic Expression Evaluation in pandas using pd.eval().

df[~df['Species'].isin(['Cat'])]

  Index    Name Species
1     1    Jill     Dog
3     3   Harry     Dog
4     4  Hannah     Dog

这篇关于根据条件从pandas DataFrame中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆