数据框的成对重塑。

huangapple go评论55阅读模式
英文:

pairwise reshaping of a dataframe

问题

我有一个数据框架 df,想要将其重塑成如下的成对矩阵(如果在上面的数据框架中没有col1col2的行组合,则条目应为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

huangapple
  • 本文由 发表于 2023年6月6日 00:57:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定