Era*_*she 1 python pandas scikit-learn
我有一个Pandas DataFrame()
并且在其中,一些列Pythons' lists
包含strings
.我想将这些列转换为"二值化"字符串并计算其外观的假人.
作为一个简单的例子,我们可以看看以下内容
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]
Run Code Online (Sandbox Code Playgroud)
我设法做了以下事情:
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
Run Code Online (Sandbox Code Playgroud)
这不包括他们的外表,但只有1次出现,0次缺席.我想要以下输出:
Hey_t1 Hey_t2 Hey_t3
0 3 1 2
1 1 2 0
Run Code Online (Sandbox Code Playgroud)
这取决于他们的外表.
使用CountVectorizer
但必要的连接list
:
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
Run Code Online (Sandbox Code Playgroud)
另一种方案:
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
Run Code Online (Sandbox Code Playgroud)
要么:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
95 次 |
最近记录: |