如何将2-D关系pandas数据帧转换为2D交叉矩阵?

时间:2018-06-06 18:53:12

标签: python pandas

我有一个数据:

import pandas as pd
import numpy as np
df = pd.DataFrame({'cust_id_1':['A','A','A','A','B','B','B','C','C','D']
              ,'cust_id_2':['B','C','D','E','C','D','E','D','E','E']
              ,'score':[4,2,4,2,1,3,2,4,5,3]})
df



cust_id_1 cust_id_2   score
0	A	B	4
1	A	C	2
2	A	D	4
3	A	E	2
4	B	C	1
5	B	D	3
6	B	E	2
7	C	D	4
8	C	E	5
9	D	E	3


And What I want to get below data:

cust	  A	B	C	D	E
A	  NaN 4.0	2.0	4.0	2.0
B	  4.0 NaN	1.0	3.0	2.0
C	  2.0 1.0	NaN	4.0	5.0
D	  4.0 3.0	4.0	NaN	3.0
E	  2.0 2.0	5.0	3.0	NaN



 有一个简单的方法吗?

我在pandas中使用了pivot_table函数,但得到了以下内容: Pivot_table Result

请注意左下角都是NaN。

0 个答案:

没有答案