在 pandas 中获取 get dummies 中分类值的频率

Getting the frequency of categorical values in get dummies in pandas

我正在对数据实施一种热编码

Version  Cluster_Size     Hardware_type  
1.0.4     3              Aplha,Alpha,Aplha
1.0.2     3              Aplha,Beta,Aplha 
1.0.9     3              Aplha,Beta,Gama  

在 df['hardware_type'].str.get_dummies(sep=', ') 之后,我能够得到这样的数据框

Version  Cluster_Size     Hardware_type      Alpha   Beta   Gama
1.0.4     3              Alpha,Alpha,Alpha     1       0      0
1.0.2     3              Alpha,Beta,Alpha      1       1      0
1.0.9     3              Alpha,Beta,Gama       1       1      1

这正是 one-hot 编码应该做的,但我正在尝试实现这样的事情,其中​​我可以获得出现在各自单元格中的分类值的计数的列。

Version  Cluster_Size     Hardware_type      Alpha   Beta   Gama
1.0.4     3              Alpha,Alpha,Alpha     3       0      0
1.0.2     3              Alpha,Beta,Alpha      2       1      0
1.0.9     3              Alpha,Beta,Gama       1       1      1

有没有办法做这样的事情? 谢谢你的时间。

如果使用 Series.str.get_dummies,则没有关于计数的信息。

所以需要另一个解决方案 - 这里使用 CounterDataFrame 构造函数:

from collections import Counter
L = [Counter(x.split(',')) for x in df['Hardware_type']]
df = df.join(pd.DataFrame(L, index=df.index).fillna(0).astype(int))
print (df)
  Version  Cluster_Size      Hardware_type  Alpha  Beta  Gama
0   1.0.4             3  Alpha,Alpha,Alpha      3     0     0
1   1.0.2             3   Alpha,Beta,Alpha      2     1     0
2   1.0.9             3    Alpha,Beta,Gama      1     1     1

或者Series.str.split, DataFrame.stack and SeriesGroupBy.value_counts的解决方案是可能的,但应该更慢(取决于数据,最好测试它):

s = df['Hardware_type'].str.split(',', expand=True).stack()
df = df.join(s.groupby(level=0).value_counts().unstack(fill_value=0))
print (df)
  Version  Cluster_Size      Hardware_type  Alpha  Beta  Gama
0   1.0.4             3  Alpha,Alpha,Alpha      3     0     0
1   1.0.2             3   Alpha,Beta,Alpha      2     1     0
2   1.0.9             3    Alpha,Beta,Gama      1     1     1