Python 如何检查pandas数据帧字段是否为数字且不为';你没有空吗?

Python 如何检查pandas数据帧字段是否为数字且不为';你没有空吗?,python,pandas,Python,Pandas,我有以下数据帧df: col1 col2 col3 50 dd 3 2 r NaN 5 d 4 a e 5 我需要计算所选列的平均值cols。然后我应该检查所选行中的任何值是否偏离中值超过20% 我不知道如何处理一行中的混合值来进行这些计算 def test_row(x, threshold): if x.dtype == int or x.dtype == float: return

我有以下数据帧
df

col1   col2   col3
50     dd     3
2      r      NaN
5      d      4
a      e      5
我需要计算所选列的平均值
cols
。然后我应该检查所选行中的任何值是否偏离中值超过20%

我不知道如何处理一行中的混合值来进行这些计算

def test_row(x, threshold):
    if x.dtype == int or x.dtype == float:
        return x > threshold

columns = ["col1", "col3"]
for col in columns:
    threshold = df[col].median()*(20/100)
    check = df.apply(lambda x: test_row(x[col], threshold), axis=1)
    print(check.any())

但是,如果x.dtype==int或x.dtype==float不起作用,它显然会失败。

您的函数可能是:

def test_row(x, threshold):
    if isinstance(x,(int,float)) and x:
        return x > threshold

函数中的第二个逻辑仅用于检查x是否包含某些内容,如果为空,则返回False。

您的代码在此处引发一个值错误:
threshold=df[col].media()*(20/100)
甚至在函数运行之前谢谢@Chris。你知道怎么修吗?我不想将NaN替换为0。只是跳过它们。@Chris指出的问题是在col1中有“a”。您可以使用
pd.to_numeric(df['col1',errors='concurve')
@Terry修复类型列的更改。这段代码只返回所有数值吗?他将转换为数值,他不能转换的将返回为NaN