gpt4 book ai didi

python - 为多索引数据框的每个索引排序列

转载 作者:太空狗 更新时间:2023-10-30 02:51:39 25 4
gpt4 key购买 nike

我有一个具有多级索引的数据框。这是它的一个片段:

import pandas as pd

data = {'EVENT_ID': [112335580,112335580,112335580,112335580,112335580,112335580,112335580,112335580, 112335582,
112335582,112335582,112335582,112335582,112335582,112335582,112335582,112335582,112335582,
112335582,112335582,112335582],

'SELECTION_ID': [6356576,2554439,2503211,6297034,4233251,2522967,5284417,7660920,8112876,7546023,8175276,8145908,
8175274,7300754,8065540,8175275,8106158,8086265,2291406,8065533,8125015],

'BSP': [5.080818565,6.651493872,6.374683435,24.69510797,7.776082305,11.73219964,270.0383021,4,8.294425408,335.3223613,
14.06040142,2.423340019,126.7205863,70.53780982,21.3328554,225.2711962,92.25113066,193.0151362,3.775394142,
95.3786641,17.86333041],

'WIN_LOSE':[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]}

df = pd.DataFrame(data, columns=['EVENT_ID', 'SELECTION_ID', 'BSP','WIN_LOSE'])
df

df.set_index(['EVENT_ID', 'SELECTION_ID'], inplace=True)
df.sortlevel(level=0, ascending=True, sort_remaining=True)

我想分别对每个 EVENT_ID 索引的 BSP 列进行排序。

我尝试了以下方法:

data.assign(BSP=data.groupby(level=0).rank(ascending=False))

这是行不通的,因为它打乱了索引,而且似乎也没有对列进行排序。

我也尝试过只根据列进行排序,但这显然也只会弄乱索引。

最佳答案

这对每个事件 ID 按 BSP 升序排序:

df = pd.DataFrame(data, columns=['EVENT_ID', 'SELECTION_ID', 'BSP','WIN_LOSE'])
df = df.sort_values(["EVENT_ID","BSP"])
df.set_index(['EVENT_ID', 'SELECTION_ID'], inplace=True)

关于python - 为多索引数据框的每个索引排序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54906955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com