如果特定列中的值不是 Pandas 数据框中的整数,则删除行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28499973/
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 if value in a specific column is not an integer in pandas dataframe
提问by azuric
If I have a dataframe and want to drop any rows where the value in one column is not an integer how would I do this?
如果我有一个数据框并想删除其中一列中的值不是整数的任何行,我该怎么做?
The alternative is to drop rows if value is not within a range 0-2 but since I am not sure how to do either of them I was hoping someonelse might.
如果值不在 0-2 范围内,另一种方法是删除行,但由于我不确定如何执行其中任何一个,我希望有人可以这样做。
Here is what I tried but it didn't work not sure why:
这是我尝试过的,但不知道为什么:
df = df[(df['entrytype'] != 0) | (df['entrytype'] !=1) | (df['entrytype'] != 2)].all(1)
回答by EdChum
There are 2 approaches I propose:
我提出了两种方法:
In [212]:
df = pd.DataFrame({'entrytype':[0,1,np.NaN, 'asdas',2]})
df
Out[212]:
entrytype
0 0
1 1
2 NaN
3 asdas
4 2
If the range of values is as restricted as you say then using isinwill be the fastest method:
如果值的范围如您所说的那样受限制,那么使用isin将是最快的方法:
In [216]:
df[df['entrytype'].isin([0,1,2])]
Out[216]:
entrytype
0 0
1 1
4 2
Otherwise we could cast to a str and then call .isdigit()
否则我们可以转换为 str 然后调用 .isdigit()
In [215]:
df[df['entrytype'].apply(lambda x: str(x).isdigit())]
Out[215]:
entrytype
0 0
1 1
4 2

