Python 在熊猫数据框中的多个条件下删除行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52456874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Drop rows on multiple conditions in pandas dataframe
提问by Dsh M
My df has 3 columns
我的 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")})
I want to drop rows where df.col_1 is 1.0 and df.col_2 is 0.0. So, I would get:
我想删除 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")})
I tried:
我试过:
df_new = df.drop[df[(df['col_1'] == 1.0) & (df['col_2'] == 0.0)].index]
It gives me the error:
它给了我错误:
'method' object is not subscriptable
Any idea how to solve the above problem?
知道如何解决上述问题吗?
回答by Dani Mesejo
dropis a method, you are calling it using []
, that is why it gives you:
drop是一种方法,您使用的是调用它[]
,这就是它为您提供的原因:
'method' object is not subscriptable
change to ()
(a normal method call) an it should work:
更改为()
(普通方法调用)它应该可以工作:
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)
Output
输出
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
回答by Charles R
Try to filter your df with loc. It's so powerfull. The "~" means you want the opposit of your condition. The ":" means you want to keep all the columns
尝试使用 loc 过滤您的 df。太强大了 “~”表示您想要与您的条件相反的内容。“:”表示您要保留所有列
df = df.loc[~((df['col_1'] == 1.0) & (df['col_2'] == 0.0)),:]
回答by Saurabh
You can use or (|) operator for this , Refer this link for it pandas: multiple conditions while indexing data frame - unexpected behavior
您可以为此使用或 (|) 运算符,请参阅此链接熊猫:索引数据框时的多个条件 - 意外行为
i.e dropping rows where both conditions are met
即删除满足两个条件的行
df = df.loc[~((df['col_1']==1) | (df['col_2']==0))]
回答by aliasgar paloda
Put the location of row which you want remove at "location".
将要删除的行的位置放在“位置”。
df = df.drop(['location' axix=1, inplace=True]