PYTHON:如何从列中出现的单词创建列?

时间:2017-05-09 16:47:31

标签: python pandas dataframe

我有一个数据框,例如:

import pandas as pd

my_df = pd.DataFrame({'col1':['A', 'B', 'C', 'A', 'A', 'B'], 
                      'col2':['foo bar', 'bar', 'something foo', 'foo', 'bar', 'foo']})

我想为其中一列中出现的每个单词生成列,例如col2,并计算该行中出现的次数。

  col1   col2          foo bar something 
0    A  foo bar         1   1    0
1    B  bar             0   1    0
2    C  something foo   1   0    1
3    A  foo             1   0    0
4    A  bar             0   1    0
5    B  foo             1   0    0

我的数据框比这个例子要大得多。每列可以有多个单词。

3 个答案:

答案 0 :(得分:5)

您需要join + get_dummies

df = my_df.join(pd.get_dummies(my_df['col2']))
print (df)
  col1       col2  bar  foo  something
0    A        foo    0    1          0
1    B        bar    1    0          0
2    C  something    0    0          1
3    A        foo    0    1          0
4    A        bar    1    0          0
5    B        foo    0    1          0

编辑 - 是必要的str.get_dummies

df = my_df.join(my_df['col2'].str.get_dummies(' '))
print (df)
  col1           col2  bar  foo  something
0    A        foo bar    1    1          0
1    B            bar    1    0          0
2    C  something foo    0    1          1
3    A            foo    0    1          0
4    A            bar    1    0          0
5    B            foo    0    1          0

但如果一行中有多个相同的单词并需要计算它们:

my_df = pd.DataFrame({'col1':['A', 'B', 'C', 'A', 'A', 'B'], 
                      'col2':['foo bar foo', 'bar', 'something foo', 'foo', 'bar', 'foo']})
print (my_df)
  col1           col2
0    A    foo bar foo
1    B            bar
2    C  something foo
3    A            foo
4    A            bar
5    B            foo

df = my_df.join(my_df['col2'].str.split(expand=True)
                             .apply(pd.value_counts,1)
                             .fillna(0)
                             .astype(int))
print (df)
  col1           col2  bar  foo  something
0    A    foo bar foo    1    2          0
1    B            bar    1    0          0
2    C  something foo    0    1          1
3    A            foo    0    1          0
4    A            bar    1    0          0
5    B            foo    0    1          0

答案 1 :(得分:3)

让我们使用pd.concatpd.concat([my_df,my_df.col2.str.get_dummies(' ')],axis=1)

  col1           col2  bar  foo  something
0    A        foo bar    1    1          0
1    B            bar    1    0          0
2    C  something foo    0    1          1
3    A            foo    0    1          0
4    A            bar    1    0          0
5    B            foo    0    1          0

输出:

{{1}}

答案 2 :(得分:2)

这是一个大数据集的内存保存解决方案,它使用稀疏矩阵和SparseDataFrame:

In [33]: from sklearn.feature_extraction.text import CountVectorizer

In [34]: vect = CountVectorizer()

In [35]: X = vect.fit_transform(my_df['col2'])

In [36]: r = pd.SparseDataFrame(X, columns=vect.get_feature_names(),
                                index=my_df.index, default_fill_value=0)

In [37]: r['col1'] = my_df.col1

In [38]: r
Out[38]:
   bar  foo  something col1
0    1    1          0    A
1    1    0          0    B
2    0    1          1    C
3    0    1          0    A
4    1    0          0    A
5    0    1          0    B

注意内存使用情况:

In [39]: r.memory_usage()
Out[39]:
Index        80
bar          24  # 3 * 8 byte (np.int64)
foo          32  # 4 * 8 byte (np.int64)
something     8  # 1 * 8 byte (np.int64)
col1         48
dtype: int64

注意:这仅适用于Pandas版本0.20.1+。对于早期版本,我们可以使用以下技巧:

for i, col in enumerate(vect.get_feature_names()):
    my_df[col] = pd.SparseSeries(X[:, i].A.ravel(), fill_value=0)

而不是:

r = pd.SparseDataFrame(X, columns=vect.get_feature_names(),
                       index=my_df.index, default_fill_value=0)
相关问题