繁体   English   中英

在 pandas dataframe 中的多个条件下删除行

[英]Drop rows on multiple conditions in pandas dataframe

我的 df 有 3 列

df = pd.DataFrame({"col_1": (0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0), 
                   "col_2": (0.0, 0.24, 1.0, 0.0, 0.22, 3.11, 0.0),
                    "col_3": ("Mon", "Tue", "Thu", "Fri", "Mon", "Tue", "Thu")}) 

我想删除 df.col_1 为 1.0 且 df.col_2 为 0.0 的行。 所以,我会得到:

df = pd.DataFrame({"col_1": (0.0, 0.0, 1.0, 0.0, 1.0), 
                   "col_2": (0.0, 0.24, 1.0, 0.22, 3.11),
                    "col_3": ("Mon", "Tue", "Thu", "Mon", "Tue")})

我试过了:

df_new = df.drop[df[(df['col_1'] == 1.0) & (df['col_2'] == 0.0)].index]

它给了我错误:

'method' object is not subscriptable

知道如何解决上述问题吗?

drop是一种方法,您使用[]调用它,这就是它为您提供的原因:

'method' object is not subscriptable

更改为() (一个正常的方法调用),它应该可以工作:

import pandas as pd

df = pd.DataFrame({"col_1": (0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0),
                   "col_2": (0.0, 0.24, 1.0, 0.0, 0.22, 3.11, 0.0),
                   "col_3": ("Mon", "Tue", "Thu", "Fri", "Mon", "Tue", "Thu")})

df_new = df.drop(df[(df['col_1'] == 1.0) & (df['col_2'] == 0.0)].index)
print(df_new)

输出

   col_1  col_2 col_3
0    0.0   0.00   Mon
1    0.0   0.24   Tue
2    1.0   1.00   Thu
4    0.0   0.22   Mon
5    1.0   3.11   Tue

尝试使用 loc 过滤您的 df。 太强大了! “~”表示你想保留那些与你的情况相反的人。 “:”表示您要保留所有列

df = df.loc[~((df['col_1'] == 1.0) & (df['col_2'] == 0.0)),:]

您可以为此使用或 (|) 运算符,请参阅此链接pandas: multiple conditions while indexing data frame - unexpected behavior

即删除同时满足两个条件的行

 df = df.loc[~((df['col_1']==1) | (df['col_2']==0))]
mask = df['Product_Code'].isin(['filter1', 'filter2', 'filter3'])
df = df[~mask]
df.head()

.isin()允许您根据系列中的多个值过滤整个数据框。 与我所知道的其他解决方案相比,这是要编写的最少代码量。

在按列过滤器中添加~会反转isin()的逻辑。

将要删除的行的位置放在“位置”。

df = df.drop(['location' axix=1, inplace=True]

您也可以在此处使用query

In [4]: df.query('~(col_1 == 1 & col_2 == 0)')
Out[4]: 
   col_1  col_2 col_3
0    0.0   0.00   Mon
1    0.0   0.24   Tue
2    1.0   1.00   Thu
4    0.0   0.22   Mon
5    1.0   3.11   Tue

使用~查询被否定,返回条件col_1 == 1 & col_2 == 0不成立的那些观察结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM