For循环一个函数一个DataFrame Python

For loop through a function an DataFrame Python

我编写了一个函数来从 table 中的每一列中删除异常值:(我附上了 table 的照片)

enter image description here

去除异常值的函数为:

def remove_outliers(df_in, col):

    q1 = df_in[col].quantile(0.25)
    q3 = df_in[col].quantile(0.75)
    iqr = q3-q1
    lower_bound = q1-1.5*iqr
    upper_bound = q3+1.5*iqr
    df_out = df_in.loc[(df_in[col] > lower_bound) & (df_in[col] < upper_bound)]
    return df_out

现在我想做一个 "for loop" 或任何其他循环,代码 运行 遍历 table 的每一列并执行删除异常值的功能并得到没有异常值的新 table。

有人可以帮我吗?

谢谢

穆赫雷斯

如果需要,您确实可以使用 for 循环,遍历数据框中的列。

如果您的数据框名为 df,您可以这样做:

for column in df.columns:
    df = remove_outliers(df, column)

尽管如此,请注意,执行此操作时,您将删除具有标记为离群值的任何列的任何行,并覆盖您的原始数据框:)