1.pivot()

2024-10-06 14:31:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下数据帧:

import pandas as pd
import numpy as np
df = pd.DataFrame({"ort":["home","away","home","away"]*12, 
  "numbers":np.random.randint(0,3,48),"wins":np.random.randint(99,104,48)})

如何将df转换为ort成为列索引的形状,即结果数据帧的形状如下所示

| Ort   | Home          |   Away        |
|-------|---------------|---------------|
| Index | numbers wins  |  numbers wins |
| 0     |  0 102        |  2 99         |
| 1     |  2 103        |  1 99         |

等等

我尝试了df.pivot(columns = "ort"),但没有成功,因为它会导致home and away在数字之下并获胜。你知道吗

有人能告诉我怎么做吗?你知道吗

我见过How to spread a column in a Pandas data frame。不过,我的列“number”和“wins”只是占位符。在我的实际df中有100列(在上面的链接中只有一列)。所以我的问题是怎样才能做到。你知道吗

谢谢!你知道吗


Tags: 数据importpandasdfhomeasnprandom
1条回答
网友
1楼 · 发布于 2024-10-06 14:31:36

你需要为游戏id引入一个占位符以便传播。你知道吗

df['game_id'] = np.array(range(0, len(df.index)//2)).repeat(2)

这样就行了:

pd.pivot_table(df, index='game_id', columns='ort',values=['numbers','wins']
               ).swaplevel(0,1, axis=1).sort_index(axis=1)
#ort        away         home     
#        numbers wins numbers wins
#game_id                          
#0             2  101       2  101
#1             0  100       0   99
#2             1  101       2   99
#3             2  101       2  103
#4             0  103       1  101
#5             0   99       1  102
#...
#23            0  100       1  101

关于您的评论的后续解释:

  • 使用swaplevels(0,1, axis=1)交换列多索引的级别。

  • 使用sort_index(axis=1)按新的顶级索引(home和away)分组。

  • 如果您有100个度量,则需要用度量名称列表替换['numbers','wins']

相关问题 更多 >