如何检查pandas数据框是否仅包含数字列?

时间:2019-01-29 17:47:38

标签: python pandas dataframe series

我想检查数据框中的每一列是否仅包含数字。我怎么找到它。

5 个答案:

答案 0 :(得分:4)

您可以使用to_numeric并检查是否存在错误:

pd.to_numeric(df['column'], errors='coerce').notnull().all()

对于所有列,您可以遍历各列或仅使用apply

df.apply(lambda s: pd.to_numeric(s, errors='coerce').notnull().all())

例如

df = pd.DataFrame({'col' : [1,2, 10, np.nan, 'a'], 
                   'col2': ['a', 10, 30, 40 ,50],
                   'col3': [1,2,3,4,5.0]})

输出

col     False
col2    False
col3     True
dtype: bool

答案 1 :(得分:2)

您可以使用isnumeric()

进行对/错比较

示例:

 >>> df
       A      B
0      1      1
1    NaN      6
2    NaN    NaN
3      2      2
4    NaN    NaN
5      4      4
6   some   some
7  value  other

结果:

>>> df.A.str.isnumeric()
0     True
1      NaN
2      NaN
3     True
4      NaN
5     True
6    False
7    False
Name: A, dtype: object

# df.B.str.isnumeric()

使用apply()方法似乎更可靠,以防您需要进行逐角比较:

DataFrame具有两个不同的列,一个是混合类型,另一个是仅用于测试的数字:

>>> df
       A   B
0      1   1
1    NaN   6
2    NaN  33
3      2   2
4    NaN  22
5      4   4
6   some  66
7  value  11

结果:

>>> df.apply(lambda x: x.str.isnumeric())
       A     B
0   True  True
1    NaN  True
2    NaN  True
3   True  True
4    NaN  True
5   True  True
6  False  True
7  False  True

答案 2 :(得分:1)

如果所有列均为数字,则返回True,否则返回False。

df.shape[1] == df.select_dtypes(include=np.number).shape[1]

要选择数字列:

new_df = df.select_dtypes(include=np.number)

答案 3 :(得分:0)

假设您有一个名为df的数据框,

df.select_dtypes(include=["float", 'int'])

这将返回所有数字列,您可以检查是否与原始df相同。

否则,您也可以使用exclude参数:

df.select_dtypes(exclude=["float", 'int'])

,然后检查是否为您提供一个空白的数据框。

答案 4 :(得分:0)

接受的答案似乎有点矫枉过正,因为它们对整个数据框进行了子选择。

要检查类型,只应使用元数据,这可以通过 pd.api.types.is_numeric_dtype

import pandas as pd
df = pd.DataFrame(data=[[1,'a']],columns=['numeruc_col','string_col'])

print(df.columns[list(map(pd.api.types.is_numeric_dtype,df.dtypes))]) # one way
print(df.dtypes.map(pd.api.types.is_numeric_dtype)) # another way
相关问题