python 中 pandas 数据帧的矩阵表示

matrix representation of pandas data-frame in python

我有一个像

这样的数据框
 from   to  Amt
 a      b   100
 a      c   200
 a      d   220
 b      a   250
 b      c   300
 b      d   330
 c      a   100
 c      b   120
 c      d   320
 d      a   211
 d      b   980
 d      c   430    

我想用

这样的矩阵格式来表示它
     a     b     c    d
a    0    100    200  220
b   250    0     300  330
c   100   120    0    320
d   211   980    430   0

如何实现..

我已经关注 Printing Lists as Tabular Data link.But 没有得到我想要的东西。

您需要旋转数据。这是一个例子。

pivot_df = df.pivot(index='from', columns='to', values='Amt')

要事先进行分数计算,您可以先使用 groupby(),然后再使用 transform('sum')。它类似于 SQL window 函数 sum.

df['sums'] =  df.groupby('from')['amt'].transform('sum')
df['frac'] = df['amt'] / df['sums']
df.pivot(index='from', columns='to', values='frac')

您需要旋转数据框。看 http://pandas.pydata.org/pandas-docs/stable/reshaping.html

df.pivot(index="from", columns="to",values="Amt" )

您也可以通过 pivot_table 实现:

df_pivoted = pd.pivot_table(df, index='from', columns='to', fill_value=0)
print(df_pivoted)

      Amt               
to      a    b    c    d
from                    
a       0  100  200  220
b     250    0  300  330
c     100  120    0  320
d     211  980  430    0