How to convert a matrix into column array with PANDAS / Python

风格不统一 提交于 2020-07-08 19:20:47

问题


I need to convert a matriz (below) into a 3 column list.

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

I've been trying to use pandas.pivot_table function, but I can't get the result needed.


回答1:


you can use DataFrame.stack() method:

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



回答2:


I was thinking about using pd.melt() :

pd.melt(df.reset_index(), id_vars=['index'], value_vars=['A', 'B', 'C'], var_name='Target', value_name='Weight')

It won't give you exactly what you want but it might be good to know :

      index Target  Weight
0     a      A     1.0
1     b      A     4.0
2     c      A     9.0
3     a      B     3.0
4     b      B     0.0
5     c      B     8.0
...


来源:https://stackoverflow.com/questions/41474284/how-to-convert-a-matrix-into-column-array-with-pandas-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!