通过不同的dtype过滤数据框列元素(因为包含INT和STR以构成整个列和对象)

问题描述 投票:0回答:1

我有一列当前具有Object的dtype。这是因为该列中0.2%的元素是字符串,而其余99.8%是整数。如何按dtype过滤数据框列?

((我发现df.select_dtypes(include ='bool')会返回df中具有布尔值的任何列,但我的问题是用dtype = Object标识了单个列,因为它是由INT和STR。)

df = pd.DataFrame([[1], [2], ['three']], columns=['A'])
python-3.x pandas dataframe series
1个回答
0
投票

如果数字和字符串混合,则可以测试type-通过isinstance

m = df['A'].apply(lambda x: isinstance(x, int))
print (m)
0     True
1     True
2    False
Name: A, dtype: bool

或按type

m = df['A'].apply(type) == int
print (m)
0     True
1     True
2    False
Name: A, dtype: bool

如果有所有字符串-如果可能,也使用数字to_numeric并转换为数字,否则缺少值,因此可以通过to_numeric进行测试:

Series.notna

以及最后一个由Series.notna过滤的内容:

df['A'] = pd.to_numeric(df['A'], errors='coerce')
m = df['A'].notna()
© www.soinside.com 2019 - 2024. All rights reserved.