python - 根据最频繁的值删除列

标签 python pandas numpy dataframe

您可以先说 wtf,但我想是否可以根据以下条件删除列:

 drop column if 1 of the unique values of that column represent 70% of the samples.

有什么想法吗?

最佳答案

是的,这是可能的。

考虑以下 DataFrame:

prng = np.random.RandomState(0)
df = pd.DataFrame(prng.choice([1, 2, 3], p=[0.7, 0.15, 0.15], size=(100, 5)))

您可以通过以下方式获取每列的每个唯一值的百分比:

df.apply(pd.Series.value_counts, normalize=True)
Out: 
      0     1     2     3     4
1  0.77  0.73  0.78  0.62  0.70
2  0.09  0.14  0.07  0.18  0.12
3  0.14  0.13  0.15  0.20  0.18

请注意,前三列的唯一值出现率高于 70%。您可以通过每列的最大值进行检查并将其作为 bool 数组传递:

df.apply(pd.Series.value_counts, normalize=True).max() > 0.7
Out: 
0     True
1     True
2     True
3    False
4    False
dtype: bool

现在,如果您只想选择具有 <70% 唯一值的值,请使用:

df.loc[:, ~(df.apply(pd.Series.value_counts, normalize=True).max() > 0.7)]
Out: 
    3  4
0   1  1
1   3  1
2   3  1
3   2  3
4   2  1
...

关于python - 根据最频繁的值删除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44342409/

相关文章:

python - 如何将一个添加到矩阵?

python - OpenCV 车辆检测

python - 非阻塞键盘输入

pandas - 计算每个股价随时间的滚动指数加权移动平均值

python-3.x - 如何根据条件对 pandas 数据框的行值进行排序?

python - 向量化 numpy 一维重新分类

python - Successfactors API 限制每个请求返回的记录数

python - `subprocess.call` 与直接在 shell 中运行命令的操作不同

python - 在数据框 Pandas 中选择日期范围

Python/Numpy - 加速放射性衰变的蒙特卡罗方法