Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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_Python 3.x_Pandas - Fatal编程技术网

Python 在文档词矩阵中转换文档词列表

Python 在文档词矩阵中转换文档词列表,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有这样一个数据集: Brand AssociatedWord Weight 0 pepsi red 10 1 pepsi yellow 3 2 coke red 5 3 coke grey 5 4 coke pink 2 我需要将其转换为以下矩阵: Brand red yellow grey pink 0

我有这样一个数据集:

  Brand AssociatedWord  Weight
0  pepsi           red      10
1  pepsi        yellow       3
2  coke            red       5
3  coke           grey       5
4  coke           pink       2
我需要将其转换为以下矩阵:

  Brand   red   yellow   grey   pink
0  pepsi   10        3      0      0
1  coke     5        0      5      2
现在,每一行都是一个品牌,每个关联词都有一列,其中报告了关联的权重。零值表示缺少关联。 列的顺序并不重要。你能帮我吗?

使用:



注意:AssociatedWord是列的名称,您可以使用以下方法更改它:

new_df.columns.name=None

也可以使用+:


太好了,谢谢你!我可以删除“AssociatedWord”列而不是重命名吗?使用
new_-df.columns.name=''
I love help:)或
new_-df.columns.name=None
AssociatedWord  Brand  grey  pink  red  yellow
0                coke     5     2    5       0
1               pepsi     0     0   10       3
new_df.columns.name=None
   Brand  grey  pink  red  yellow
0   coke     5     2    5       0
1  pepsi     0     0   10       3
new_df=df.set_index(['Brand','AssociatedWord']).unstack(fill_value=0).reset_index()
print(new_df)


new_name        Brand Weight                
AssociatedWord          grey pink red yellow
0                coke      5    2   5      0
1               pepsi      0    0  10      3