[英]matrix representation of pandas data-frame in python
i have a data-frame like 我有一个像数据框架
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
i want to represent it in matrix format like 我想以矩阵格式表示它
a b c d
a 0 100 200 220
b 250 0 300 330
c 100 120 0 320
d 211 980 430 0
How to achieve that.. 怎么实现那个..
i have followed Printing Lists as Tabular Data link.But not getting what i was looking for. 我已经将打印列表作为表格数据链接。但没有得到我想要的。
You need to pivot your data. 您需要透视数据。 Here is an example.
这是一个例子。
pivot_df = df.pivot(index='from', columns='to', values='Amt')
For doing fractional calculations before hand, you might use groupby()
then transform('sum')
. 对于事前进行小数计算,您可以使用
groupby()
然后transform('sum')
。 It is similar to a SQL window function sum. 它类似于SQL窗口函数和。
df['sums'] = df.groupby('from')['amt'].transform('sum')
df['frac'] = df['amt'] / df['sums']
df.pivot(index='from', columns='to', values='frac')
You need to pivot the data frame. 您需要透视数据框。 See http://pandas.pydata.org/pandas-docs/stable/reshaping.html
请参见http://pandas.pydata.org/pandas-docs/stable/reshaping.html
df.pivot(index="from", columns="to",values="Amt" )
You could also achieve that with pivot_table
: 您也可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.