如何计算每列的99%和1%百分位数作为上限和下限,如果值>=99%百分位数则重新定义该值作为99%百分位数的值;类似地,如果 value <= 1% percentile 则将 value 重新定义为 1% percentile 的值
np.random.seed(2)
df = pd.DataFrame({'value1': np.random.randn(100), 'value2': np.random.randn(100)})
df['lrnval'] = np.where(np.random.random(df.shape[0])>=0.7, 'learning', 'validation')
如果我们有数百列,我们可以使用 apply 函数而不是 do 循环吗?
请您参考如下方法:
根据 Abdou 的回答,以下内容可能会为您节省一些时间:
for col in df.columns:
percentiles = df[col].quantile([0.01, 0.99]).values
df[col][df[col] <= percentiles[0]] = percentiles[0]
df[col][df[col] >= percentiles[1]] = percentiles[1]
或使用 numpy.clip :
import numpy as np
for col in df.columns:
percentiles = df[col].quantile([0.01, 0.99]).values
df[col] = np.clip(df[col], percentiles[0], percentiles[1])
