如果单元格位于顶部或底部 x%,则转换为 NaN

Convert to NaN if cell is in the top or bottom x%

我正在寻找 trim 我的数据框,方法是从特定列中删除顶部和底部 5% 左右的数据。有错误的异常值阻止我有效地使用数据。

数据框有一个 "name" 列和一些其他非数字列,所以我希望能够 select 特定列到 trim df。

我认为如果单元格的值是最大或最小 x%,则将其转换为 NaN 将是一种有效的方法,但如果其他方法也有效,我也愿意接受。

这是我正在尝试做的一个例子:

for column in df.columns:
    top = column.quantile(0.95)
    bottom = column.quantile(0.05)
    for cell in column:
        if (cell >= top)|(cell <= bottom):
            cell = np.NaN

我想你想要 between。此外,您可以将数组传递给 quantile():

for column in [your_list_of_columns]:
    bottom, top = df[column].quantile([0.05,0.95])

    df[column] = df[column].where(df[column].between(bottom, top))

您可以使用如下所示的 np.argpartation 方法来 select 每列中顶部和底部 5% 的数据。这将更有效,因为它使用矢量化并且也不需要对所有行进行排序

bottom_ind = np.argpartition(df.values, trim_len, axis=0)[:trim_len]
top_ind = np.argpartition(df.values, -trim_len, axis=0)[-trim_len:]
trim_ind = np.r_[bottom_ind, top_ind]

## you can use loop here if you have more columns
df.iloc[trim_ind[0],0] = np.nan
df.iloc[trim_ind[1],1] = np.nan
df