Python 删除不是 .isin('X') 的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14057007/
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
Remove rows not .isin('X')
提问by DrewH
Sorry just getting into Pandas, this seems like it should be a very straight forward question. How can I use the isin('X')to remove rows that are inthe list X? In R I would write !which(a %in% b).
抱歉刚刚进入 Pandas,这似乎应该是一个非常直接的问题。我如何使用isin('X')删除的行是在列表中X?在 RI 中会写!which(a %in% b).
回答by Andy Hayden
You can use the DataFrame.selectmethod:
您可以使用以下DataFrame.select方法:
In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])
In [2]: df
Out[2]:
0 1
A 1 2
B 3 4
In [3]: L = ['A']
In [4]: df.select(lambda x: x in L)
Out[4]:
0 1
A 1 2
回答by bmu
You can use numpy.logical_notto invert the boolean array returned by isin:
您可以使用numpy.logical_not来反转由 返回的布尔数组isin:
In [63]: s = pd.Series(np.arange(10.0))
In [64]: x = range(4, 8)
In [65]: mask = np.logical_not(s.isin(x))
In [66]: s[mask]
Out[66]:
0 0
1 1
2 2
3 3
8 8
9 9
As given in the comment by Wes McKinney you can also use
正如 Wes McKinney 在评论中给出的,您也可以使用
s[~s.isin(x)]
回答by atm
All you have to do is create a subset of your dataframe where the isin method evaluates to False:
您所要做的就是创建数据帧的一个子集,其中 isin 方法的计算结果为 False:
df = df[df['Column Name'].isin(['Value']) == False]
回答by Jonny Brooks
You have many options. Collating some of the answers above and the accepted answer from this postyou can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]
你有很多选择。整理上面的一些答案和这篇文章中接受的答案,你可以这样做:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4.df[np.logical_not(df["column"].isin(["value"]))]
Note: for option 4 for you'll need to import numpy as np
注意:对于选项 4,您需要 import numpy as np
Update:You can also use the .querymethod for this too. This allows for method chaining:
5. df.query("column not in @values").
where valuesis a list of the values that you don't want to include.
更新:您也可以.query为此使用该方法。这允许方法链接:
5. df.query("column not in @values").
wherevalues是您不想包含的值的列表。

