0

我有以下 DataFrame 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())

但是它显然失败了,因为if x.dtype == int or x.dtype == float它不起作用。

4

1 回答 1

1

您的功能可能是:

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

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

于 2019-03-27T18:59:25.187 回答