Python - 计算一列对于多个其他列的每个唯一值(交叉表、透视表)

问题描述 投票:0回答:1

我已经到处研究过这个问题,但没有任何东西能满足我的需要。 我有一个包含 3 列的数据框。我想计算一列的所有值以获取其他两列的唯一值。交叉表仅适用于两列,并且我尝试过的数据透视表没有为我提供计数列中所有唯一值的列。

df=pd.DataFrame({'player':['A','A','B','B','C','D'],
                 'team':['tmX','tmX','tmX','tmX','tmY','tmY'],
                 'result':['hit','hit','hit','miss','miss','hit']})
print(df)

  player team result
0    A    tmX   hit 
1    A    tmX   hit
2    B    tmX   hit
3    B    tmX   miss
4    C    tmY   miss
5    D    tmY   hit

# code here to pivot/crosstab
# print(new_df)    

#this is the result I want
  player team hit miss
0     A   tmX  2    0
1     B   tmX  1    1
2     C   tmY  0    1
3     D   tmY  1    0
    

如果我使用 groupby(),我会得到以下结果:

   new_df=xyz.groupby(['player','team'])['result'].count().reset_index()

   print(new_df)

   #this is what I get - counts result, but not by unqiue value
     player team result
   0    A    tmX   2
   1    B    tmX   2
   2    C    tmY   1 
   3    D    tmY   1
python pandas dataframe pivot
1个回答
0
投票

您可以按所有三列计算大小,然后取消堆叠

result
索引:

(
  df.groupby(['player', 'team', 'result'])
    .size()
    .unstack(level=2, fill_value=0)
    .reset_index()
)

result player team  hit  miss
0           A  tmX    2     0
1           B  tmX    1     1
2           C  tmY    0     1
3           D  tmY    1     0
© www.soinside.com 2019 - 2024. All rights reserved.