Pandas从数据框中选择仅数字或整数字段

21 投票
4 回答
51661 浏览
提问于 2025-04-18 14:14

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

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

其中A这一列的类型是对象。

我想选择A列中值是整数或数字的记录,得到:

     A    B
0    1    green
1    2    red
3    3    yellow

谢谢

4 个回答

0

我个人觉得,直接使用内置的 map 比用 .apply() 要简单明了很多。

In [13]: df[map(pred, df['B'])]
5

请注意,convert_objects这个功能已经不再推荐使用了。

>>> df[['A']].convert_objects(convert_numeric=True)
__main__:1: FutureWarning: convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

从版本0.17.0开始,建议使用pd.to_numeric,并设置errors='coerce',这样如果解析出错就会返回NaN(表示缺失值)。可以使用notnull来返回一个布尔值的掩码,这样你就可以在原始数据表上使用它:

>>> df[pd.to_numeric(df.A, errors='coerce').notnull()]
   A       B
0  1   green
1  2     red
3  3  yellow
11

你可以使用 convert_objects 这个功能,当你设置 convert_numeric=True 时,它会强制把所有非数字的内容变成 nan(也就是“不是一个数字”的意思)。然后你可以把这些 nan 去掉,最后就能得到你想要的结果。

这样做的速度会比在一个比较大的数据框上使用 apply 快很多,因为这个功能是用 cython 实现的,效率更高。

In [30]: df[['A']].convert_objects(convert_numeric=True)
Out[30]: 
    A
0   1
1   2
2 NaN
3   3
4 NaN

In [31]: df[['A']].convert_objects(convert_numeric=True).dropna()
Out[31]: 
   A
0  1
1  2
3  3

In [32]: df[['A']].convert_objects(convert_numeric=True).dropna().index
Out[32]: Int64Index([0, 1, 3], dtype='int64')

In [33]: df.iloc[df[['A']].convert_objects(convert_numeric=True).dropna().index]
Out[33]: 
   A       B
0  1   green
1  2     red
3  3  yellow
26

在数据框上调用 apply 方法时,要注意使用双重方括号 df[['A']],而不是 df['A']。接着,我们调用字符串方法 isdigit(),并设置参数 axis=1,这样就可以按行应用这个函数。这里发生的事情是,索引用来创建一个布尔掩码。

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 或更新的版本,那么下面的方法也可以使用:

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

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

在这里,我们使用 astype 将序列转换为 str 类型,然后调用向量化的 str.isdigit 方法。

另外要注意的是,convert_objects 已经不推荐使用,最新版本 0.17.0 或更高版本应该使用 to_numeric

撰写回答