我这里在数据上实现了一个热编码。
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
这正是一键编码应该做的,但我试图实现这样的东西,其中列我可以得到的分类值出现在各自的单元格中的计数。
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
没有关于计数的信息。
所以需要另一种解决方案--这里使用的是 Counter
与 DataFrame
构造函数。
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
和 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