Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PYTHON:如何从列中出现的单词创建列?_Python_Pandas_Dataframe - Fatal编程技术网

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

PYTHON:如何从列中出现的单词创建列?,python,pandas,dataframe,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

例如,我有一个数据帧,如下所示:

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

我的dataframe比这个示例要大得多,有更多的单词。每列可以有多个单词。

让我们使用
get\u dummies
pd.concat

pd.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
你需要+:

编辑-有必要:

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

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

下面是一个针对大型数据集的节省内存解决方案,它使用稀疏矩阵和稀疏帧:

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
注意:这仅适用于熊猫版本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)
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)