如果特定列中的值不是pandas数据框中的整数,则删除行 [英] Drop rows if value in a specific column is not an integer in pandas dataframe

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

问题描述

如果我有一个数据框,并且想删除一行中的值不是整数的行,我该怎么做?

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?

另一种选择是,如果value不在0-2范围内,则删除行,但是由于我不确定该怎么做,所以我希望有人这样做.

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.

这是我尝试过的方法,但不确定为什么不起作用:

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)

推荐答案

我建议使用2种方法:

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

如果值的范围受到您的限制,则使用isin将是最快的方法:

If the range of values is as restricted as you say then using isin will be the fastest method:

In [216]:

df[df['entrytype'].isin([0,1,2])]
Out[216]:
  entrytype
0         0
1         1
4         2

否则我们可以强制转换为str,然后调用.isdigit()

Otherwise we could cast to a str and then call .isdigit()

In [215]:

df[df['entrytype'].apply(lambda x: str(x).isdigit())]
Out[215]:
  entrytype
0         0
1         1
4         2

这篇关于如果特定列中的值不是pandas数据框中的整数,则删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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