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

查看:42
本文介绍了根据条件从 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)

我想删除物种"列中包含猫"的所有行,留下所有的狗.我该怎么做呢?不幸的是,此代码目前正在返回错误.

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.

推荐答案

General 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("Species != 'Cat'")

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

有关 pd.eval() 函数系列、它们的特性和用例的信息,请访问 使用 pd.eval() 在 Pandas 中进行动态表达式评估.

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天全站免登陆