您可以先说 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/