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'). It is similar to a SQL window function sum.
df['sums'] = df.groupby('from')['amt'].transform('sum')
df['frac'] = df['amt'] / df['sums']
df.pivot(index='from', columns='to', values='frac')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With