python - 从 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})
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_df
列col2
值仅为整数的我想要的输出:
col1 col2
2 c 200
6 g 35
我尝试过使用 pd.to_numeric() 甚至是 isdigit() 函数,但他们期望一个系列作为输入。有没有一种简单的方法来获得所需的输出?
解决方案
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
推荐阅读
- python - 基于python中现有的数据框列创建多个新数据框
- javascript - 如何更改 pdf 页面上的图标?
- ios - 按 tabbar 并在 prefersLargeTitles = true iOS 中调用 Scroll to top
- deep-learning - 为什么 CNN 中使用的图像大小通常是特定数字?
- dart - 如何通过手势传递到下面的对象?
- javascript - Vuejs SSR、Laravel 和 PHP V8Js 问题“窗口未定义”
- python - 重命名目录中的文件时的 If-Else
- javascript - 为什么fillText没有出现在画布中?
- javascript - 即使在使用 window.location 重定向后,Chrome 也会继续加载资源
- regex - 如何为我的词法分析器使用正则表达式转义字符串文字?