Python 3.x 如何为基数较高的列的某个阈值以上的级别创建虚拟?

Python 3.x 如何为基数较高的列的某个阈值以上的级别创建虚拟?,python-3.x,pandas,multiple-columns,categorical-data,dummy-variable,Python 3.x,Pandas,Multiple Columns,Categorical Data,Dummy Variable,所以我有一个高基数的专栏: Df['Education_Degree'].value_counts(): Masters Degree in Mathematics 5550 Bachelors Degree in Physics 4420 Bacherlors Degree 3210 Masters Degre

所以我有一个高基数的专栏:

   Df['Education_Degree'].value_counts():

   Masters Degree in Mathematics                      5550
   Bachelors Degree in Physics                        4420
   Bacherlors Degree                                  3210
   Masters Degree in Mechanics                        2540
   Masters Degree                                     1200
   Masters Degree in Economics                        995
   .
   .
   .

   Name: Education_Degree, Length: 356, dtype: int64
我想做的是创建虚拟列,但仅限于995以上的级别,任何建议都将不胜感激,谢谢

s=Df['Education_Degree'].value_counts()
sdumm=pd.get_dummies(Df.loc[Df['Education_Degree'].isin(s.index[s>=995]),'Education_Degree'])
然后只需
concat

yourdf=pd.concat([Df,sdumm.reindex(Df.index).fillna(0)],axis=1)

值计数提供了足够的信息来实现这一点

c=Df['Education_Degree'].value_counts()
这将返回一个对象。我们可以用它来制作假人。或者我们可以使用不同的方法来获取值计数:

c=Df.groupby('Education_Degree', sort=False)['Education_Degree'].count().sort_values(ascending=False)
结果是一样的

一旦我们有了序列对象,我们就可以创建假人了。但还有另一个解决办法。而是获取我们希望保留的列:

c=c[c>995]
我们可以得到我们不喜欢保留的专栏

c=c[c<=995]
c_remove = c.index.tolist() # list of columns not to keep
最后,我们将删除这些列:

Df.drop(c_remove, axis=1)
Df.drop(c_remove, axis=1)