[英]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
怎么實現那個..
我已經將打印列表作為表格數據鏈接。但沒有得到我想要的。
您需要透視數據。 這是一個例子。
pivot_df = df.pivot(index='from', columns='to', values='Amt')
對於事前進行小數計算,您可以使用groupby()
然后transform('sum')
。 它類似於SQL窗口函數和。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.