首页 > 解决方案 > 从 pandas 的混合数据类型列中仅选择整数

问题描述

我有一个df如下所示的数据框。该列col2具有空值、空白值、整数甚至浮点值。我想new_dfdf该列col2只有整数值的地方派生一个新的数据框。

import pandas as pd
import numpy as np

col1 = ["a", "b", "c", "d", "e", "f", "g", "h"]
col2 = ["25.45", "", "200", np.nan, "N/A", "null", "35", "5,300"]

df = pd.DataFrame({"col1": col1, "col2": col2})

df看起来是这样的:

  col1   col2
0    a  25.45
1    b       
2    c    200
3    d    NaN
4    e    N/A
5    f   null
6    g     35
7    h  5,300

以下是new_dfcol2值仅为整数的我想要的输出:

  col1   col2  
2    c    200
6    g     35

我尝试过使用 pd.to_numeric() 甚至是 isdigit() 函数,但他们期望一个系列作为输入。有没有一种简单的方法来获得所需的输出?

标签: pythonpython-3.xpandasdataframe

解决方案


str.isdigit

过滤掉数字并通过布尔索引选择:

df2 = df[df.col2.astype(str).str.isdigit()]    
print(df2)
  col1 col2
2    c  200
6    g   35

PS,要将“col2”转换为整数,请使用

df2['col2'] = df2['col2'].astype(int)

str.contains

您也可以使用str.contains,尽管速度较慢,因为它使用正则表达式。

df[df.col2.astype(str).str.contains(r'^\d+$')]

  col1 col2
2    c  200
6    g   35

pd.to_numeric

第三种解决方案有点老套,但使用pd.to_numeric. 我们需要一个预替换步骤来过滤掉浮动。

v = df.col2.astype(str).str.replace('.', '|', regex=False)
df[pd.to_numeric(v, errors='coerce').notna()]

  col1 col2
2    c  200
6    g   35

推荐阅读