将特定功能应用于列表中的熊猫多索引级别的唯一值,从而创建新的多索引

问题描述

我想使用需要列表作为输入的函数来转换多索引的值,使用起来很昂贵。

def example_function(*,alist):
    import time

    for i in alist:
        print(i)
        time.sleep(0.1)
    return [
        str(s).upper() + "_" + str(np.random.randint(0,100_000,1)[0]) for s in alist
    ]

示例索引:

idx = pd.MultiIndex.from_tuples(
    [
        ("first","one"),("first","two"),("second","three"),"five"),]
)

使用上面的多索引,计算需要0.5 * (2 + 4) = 3秒。

最初,我认为可以使用set_levels,但这似乎不起作用。

尝试:

idx_new = idx.copy()
processed_levels = []
for i in range(idx.nlevels):
    current_level = idx_new.get_level_values(level=i)
    remap = dict(
        zip(current_level.unique(),example_function(alist=current_level.unique()))
    )
    processed_levels.append(current_level.unique().map(remap))

给予

# processed_levels
[Index(['FIRST_38195','SECOND_65065'],dtype='object'),Index(['ONE_18944','TWO_29545','THREE_80217','FIVE_4730'],dtype='object')]

之后

idx_new.set_levels(processed_levels)

没有映射正确的值,它给出:

MultiIndex([( 'FIRST_38195','TWO_29545'),( 'FIRST_38195','FIVE_4730'),('SECOND_65065','THREE_80217'),'ONE_18944')],)

第一个索引是正确的(必需的是相同的输入值具有相同的后缀),但是第二个索引是错误的,引用原始数据:

MultiIndex([( 'first','one'),( 'first','two'),('second','three'),'five')],)

要清楚,后缀号在这里并不重要-重要的是相同的输入值接收相同的输出值。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)