pandas :如何根据列表从数据框中删除行? [英] Pandas: How to remove rows from a dataframe based on a list?

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

问题描述

我有一个数据框客户,其中包含一些不良"行,该数据框中的键是CustomerID.我知道我应该删除这些行.我有一个名为 badcu 的列表,其中列出了[23770, 24572, 28773, ...]每个值都对应于一个不同的不良"客户.

然后我有了另一个数据框,我们将其称为 sales (销售额),因此我想删除 badcu 列表中那些不良客户的所有记录.

如果我执行以下操作

sales[sales.CustomerID.isin(badcu)]

我得到了一个数据框,其中包含我要删除的记录,但是如果我做了

sales.drop(sales.CustomerID.isin(badcu))

它返回一个数据帧,其中第一行被删除(这是合法顺序),其余行保持不变(它不会删除坏行),我想我知道为什么会发生这种情况,但是我仍然不知道不知道如何删除不正确的客户ID行.

解决方案

您需要

new_df = sales[~sales.CustomerID.isin(badcu)]

I have a dataframe customers with some "bad" rows, the key in this dataframe is CustomerID. I know I should drop these rows. I have a list called badcu that says [23770, 24572, 28773, ...] each value corresponds to a different "bad" customer.

Then I have another dataframe, lets call it sales, so I want to drop all the records for the bad customers, the ones in the badcu list.

If I do the following

sales[sales.CustomerID.isin(badcu)]

I got a dataframe with precisely the records I want to drop, but if I do a

sales.drop(sales.CustomerID.isin(badcu))

It returns a dataframe with the first row dropped (which is a legitimate order), and the rest of the rows intact (it doesn't delete the bad ones), I think I know why this happens, but I still don't know how to drop the incorrect customer id rows.

解决方案

You need

new_df = sales[~sales.CustomerID.isin(badcu)]

这篇关于 pandas :如何根据列表从数据框中删除行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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