python - Pandas - 从具有出现次数的可迭代对象中获取虚拟对象

标签 python pandas scikit-learn

我有一个 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但必须加入 lists:

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/

相关文章:

python Bokeh : update scatter plot colors on callback

python - 无法使用 pip 安装 coinbase API

python - 如何对 pandas 数据框进行非规范化

python - conda 创建-n 测试 pandas=0.12.0 (?)

python - Scikit-learn 的 Pipeline : Error with multilabel classification. 传递了一个稀疏矩阵

python - 将字符串字符串转换为数据框中的列表

python - Pyspark 过滤来自 RDD 的空行不起作用

Python 脚本失败并下降 0 CPU 使用率

python - ValidateError 验证字段 arch 时发生错误 : Invalid XML for View Architecture

python - 如何在gridsearchcv中使用log_loss记分器?