仅从 pandas 的混合数据类型列中选择整数

Cod*_*pra 1 python dataframe python-3.x pandas

我有一个数据框df,如下所示。该列col2具有空值、空白值、整数甚至浮点值。new_df我想从中派生一个新的数据帧,df其中该列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})
Run Code Online (Sandbox Code Playgroud)

看起来是这样的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
Run Code Online (Sandbox Code Playgroud)

以下是我想要的输出,new_df其中列col2值仅为整数:

  col1   col2  
2    c    200
6    g     35
Run Code Online (Sandbox Code Playgroud)

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

cs9*_*s95 5

str.isdigit

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

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

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

df2['col2'] = df2['col2'].astype(int)
Run Code Online (Sandbox Code Playgroud)

str.contains

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

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

  col1 col2
2    c  200
6    g   35
Run Code Online (Sandbox Code Playgroud)

pd.to_numeric

第三种解决方案有点hacky,但使用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
Run Code Online (Sandbox Code Playgroud)