英文:
pairwise reshaping of a dataframe
问题
我有一个数据框架 df,想要将其重塑成如下的成对矩阵(如果在上面的数据框架中没有col1和col2的行组合,则条目应为0,否则为NaN。如下所示:
     a    b    c
a   12   NaN  17.0
b   2    4.0  NaN
c   45   6.0  20.0
英文:
I have a dataframe
df = pd.DataFrame({'col1':['a', 'a', 'a', 'b', 'b', 'c', 'c'], 
                   'col2':['a', 'b', 'c', 'b', 'c', 'a', 'c'], 
                   'count':[12, 2, 45, 4, 6, 17, 20]})
  col1 col2 count
0	a	a	12
1	a	b	2
2	a	c	45
3	b	b	4
4	b	c	6
5	c	a	17
6	c	c	20
and I would like to reshape it so I have a pairwise matrix as below (if there is no row combination of col1, col2 in the dataframe above the entry should be 0 or else nan. So it would look like that
     a	 b	 c			
a	12	NaN	 17.0
b	2	4.0	 NaN
c	45	6.0	 20.0
答案1
得分: 1
您正在寻找pivot()函数:
df = pd.DataFrame({'col1':['a', 'a', 'a', 'b', 'b', 'c', 'c'], 
                   'col2':['a', 'b', 'c', 'b', 'c', 'a', 'c'], 
                   'count':[12, 2, 45, 4, 6, 17, 20]})
df.pivot(index='col1', columns='col2')
df
     count           
col2     a    b     c
col1                 
a     12.0  2.0  45.0
b      NaN  4.0   6.0
c     17.0  NaN  20.0
这是代码示例和其输出的翻译。
英文:
You are looking for the pivot() function:
df = pd.DataFrame({'col1':['a', 'a', 'a', 'b', 'b', 'c', 'c'], 
                   'col2':['a', 'b', 'c', 'b', 'c', 'a', 'c'], 
                   'count':[12, 2, 45, 4, 6, 17, 20]})
df.pivot(index='col1', columns='col2)
df
     count           
col2     a    b     c
col1                 
a     12.0  2.0  45.0
b      NaN  4.0   6.0
c     17.0  NaN  20.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论