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