pandas 只从数据框中选择数字或整数字段 [英] Pandas select only numeric or integer field from dataframe

查看:63
本文介绍了 pandas 只从数据框中选择数字或整数字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Pandas数据框(df):

I have this Pandas dataframe (df):

     A    B
0    1    green
1    2    red
2    s    blue
3    3    yellow
4    b    black

类型是对象.

我将选择其中A值为整数或数字的记录:

I'd select the record where A value are integer or numeric to have:

     A    B
0    1    green
1    2    red
3    3    yellow

谢谢

推荐答案

在数据框上调用apply(请注意使用双方括号df[['A']]而不是df['A'])并调用字符串方法isdigit(),然后设置参数axis=1以逐行应用lambda函数.这里发生的是该索引用于创建布尔掩码.

Call apply on the dataframe (note the double square brackets df[['A']] rather than df['A']) and call the string method isdigit(), we then set param axis=1 to apply the lambda function row-wise. What happens here is that the index is used to create a boolean mask.

In [66]:
df[df[['A']].apply(lambda x: x[0].isdigit(), axis=1)]
Out[66]:
       A       B
Index           
0      1   green
1      2     red
3      3  yellow

更新

如果您使用的版本是 0.16 .0 或更高版本,则以下内容也将起作用:

If you're using a version 0.16.0 or newer then the following will also work:

In [6]:
df[df['A'].astype(str).str.isdigit()]

Out[6]:
   A       B
0  1   green
1  2     red
3  3  yellow

在这里,我们使用astype将系列转换为str,然后调用矢量化的

Here we cast the Series to str using astype and then call the vectorised str.isdigit

还请注意,不建议使用convert_objects,对于最新版本0.17.0或更高版本,应使用to_numeric

Also note that convert_objects is deprecated and one should use to_numeric for the latest versions 0.17.0 or newer

这篇关于 pandas 只从数据框中选择数字或整数字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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