根据最频繁值删除列

2024-06-12 04:30:44 发布

您现在位置:Python中文网/ 问答频道 /正文

你可以先说wtf,但我想说,如果有可能根据以下条件删除一列:

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

有什么想法吗?你知道吗


Tags: oftheifthatcolumn条件dropunique
1条回答
网友
1楼 · 发布于 2024-06-12 04:30:44

是的,那是可能的。你知道吗

考虑以下数据帧:

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%出现率的唯一值。您可以按每列的最大值检查,并将其作为布尔数组传递:

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
...

相关问题 更多 >