pandas 删除行与过滤器 [英] Pandas drop rows vs filter

查看:40
本文介绍了 pandas 删除行与过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pandas数据框,想摆脱"A"列为负的行.我知道两种方法可以做到这一点:

I have a pandas dataframe and want to get rid of rows in which the column 'A' is negative. I know 2 ways to do this:

df = df[df['A'] >= 0]

selRows = df[df['A'] < 0].index
df = df.drop(selRows, axis=0)

推荐的解决方案是什么?为什么?

What is the recommended solution? Why?

推荐答案

推荐的解决方案是最有效的,在这种情况下,这是第一个解决方案.

The recommended solution is the most eficient, which in this case, is the first one.

df = df[df['A'] >= 0]

关于第二种解决方案

selRows = df[df['A'] < 0].index
df = df.drop(selRows, axis=0)

您正在重复切片过程.但是,让我们把它弄成碎片以了解原因.

you are repeating the slicing process. But lets break it to pieces to understand why.

写作时

df['A'] >= 0

您正在创建一个掩码,这是一个布尔系列,其中每个df索引都有一个条目,根据条件(在给定索引下,如果列'A'的值是这样的话),则该值的值为True或False大于或等于0).

you are creating a mask, a Boolean Series with an entry for each index of df, whose value is either True or False according to a condition (on this case, if such the value of column 'A' at a given index is greater than or equal to 0).

写作时

df[df['A'] >= 0]

您访问的掩码(df ['A']> = 0)为True的行.这是Pandas支持的切片方法,可让您通过传递布尔系列来选择某些行,并将返回原始DataFrame的视图,其中仅包含该系列为True的条目.

you accessing the rows for which your mask (df['A'] >= 0) is True. This is a slicing method supported by Pandas that lets you select certain rows by passing a Boolean Series and will return a view of the original DataFrame with only the entries for which the Series was True.

最后,当您编写此内容

selRows = df[df['A'] < 0].index
df = df.drop(selRows, axis=0)

您之所以要重复此过程,是因为

you are repeating the proccess because

df[df['A'] < 0]

已经对您的DataFrame进行切片(在这种情况下,是您要删除的行).然后,您将获得这些索引,返回到原始DataFrame并显式删除它们.不需要这个,您已经在第一步中对DataFrame进行了切片.

is already slicing your DataFrame (in this case for the rows you want to drop). You are then getting those indices, going back to the original DataFrame and explicitly dropping them. No need for this, you already sliced the DataFrame in the first step.

这篇关于 pandas 删除行与过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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