如何使用PANDAS / Python将矩阵转换为列数组 [英] How to convert a matrix into column array with PANDAS / Python
本文介绍了如何使用PANDAS / Python将矩阵转换为列数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将Matriz(如下)转换为3列列表。
I need to convert a matriz (below) into a 3 column list.
我目前有一个这样的DataFrame:
I currently have a DataFrame as this:
A B C ...
a 1 3 4 ...
b 4 0 6 ...
c 9 8 0 ...
,我需要得到这样的结果:
and I need to get a results as this:
Source Target Weight
a A 1
a B 3
a C 4
b A 4
b C 6
c A 9
c B 8
我一直在尝试使用pandas.pivot_table函数,但无法获得所需的结果。
I've been trying to use pandas.pivot_table function, but I can't get the result needed.
推荐答案
您可以使用 DataFrame.stack()方法:
In [335]: df.stack().reset_index().rename(columns={'level_0':'Source','level_1':'Target', 0:'Weight'})
Out[335]:
Source Target Weight
0 a A 1
1 a B 3
2 a C 4
3 b A 4
4 b B 0
5 b C 6
6 c A 9
7 c B 8
8 c C 0
这篇关于如何使用PANDAS / Python将矩阵转换为列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文