我有一个 Pandas DataFrame()
,其中一些列是 Python 列表
,其中包含 字符串
。
我想将这些列转换为虚拟对象,将字符串“二值化”并计算它们的出现次数。
作为一个简单的例子,我们可以看下面的
import pandas
df = pd.DataFrame({"Hey":[['t1', 't2', 't1', 't3', 't1', 't3'], ['t2', 't2', 't1']]})
df
Out[54]:
Hey
0 [t1, t2, t1, t3, t1, t3]
1 [t2, t2, t1]
我已经设法做到了以下几点:
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
pd.DataFrame(mlb.fit_transform(df['Hey']), columns=list(map(lambda x: 'Hey_' + x, mlb.classes_)))
Out[55]:
Hey_t1 Hey_t2 Hey_t3
0 1 1 1
1 1 1 0
这不计算他们的出现次数,但只对出现次数产生 1,对不出现次数产生 0。我想要以下输出:
Hey_t1 Hey_t2 Hey_t3
0 3 1 2
1 1 2 0
这会计算他们的出现次数。
最佳答案
使用CountVectorizer
但必须加入 list
s:
from sklearn.feature_extraction.text import CountVectorizer
countvec = CountVectorizer()
counts = countvec.fit_transform(df['Hey'].str.join(' '))
df = pd.DataFrame(counts.toarray(), columns=countvec.get_feature_names())
print (df)
t1 t2 t3
0 3 1 2
1 1 2 0
另一种解决方案:
df1 = (pd.DataFrame(df['Hey'].values.tolist())
.stack()
.groupby(level=0)
.value_counts()
.unstack(fill_value=0))
print (df1)
t1 t2 t3
0 3 1 2
1 1 2 0
或者:
from collections import Counter
df1 = (pd.DataFrame([Counter(x) for i, x in df['Hey'].iteritems()], index=df.index)
.fillna(0).astype(int))
print (df1)
t1 t2 t3
0 3 1 2
1 1 2 0
关于python - Pandas - 从具有出现次数的可迭代对象中获取虚拟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51925083/