Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于最频繁值删除列_Python_Pandas_Numpy_Dataframe - Fatal编程技术网

Python 基于最频繁值删除列

Python 基于最频繁值删除列,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,你可以先说wtf,但我想知道是否有可能根据以下条件删除一列: drop column if 1 of the unique values of that column represent 70% of the samples. 有什么想法吗?是的,有可能 考虑以下数据帧: prng = np.random.RandomState(0) df = pd.DataFrame(prng.choice([1, 2, 3], p=[0.7, 0.15, 0.15], size=(100, 5)))

你可以先说wtf,但我想知道是否有可能根据以下条件删除一列:

 drop column if 1 of the unique values of that column represent 70% of the samples.
有什么想法吗?

是的,有可能

考虑以下数据帧:

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

现在,如果您只想选择那些使用了
apply()
(我们不经常这么说!)的应用程序,请点击这里。@JohnZwinck谢谢。据我所知,除了在列上循环之外,没有向量化的方法来计算每列中的值,所以我使用apply。
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
...