假设我有以下数据帧:
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列(在上面的链接中只有一列)。所以我的问题是怎样才能做到。你知道吗
谢谢!你知道吗
你需要为游戏id引入一个占位符以便传播。你知道吗
这样就行了:
关于您的评论的后续解释:
使用
swaplevels(0,1, axis=1)
交换列多索引的级别。使用
sort_index(axis=1)
按新的顶级索引(home和away)分组。如果您有100个度量,则需要用度量名称列表替换
['numbers','wins']
。相关问题 更多 >
编程相关推荐