替换列和多索引上的Pandas数据帧值

2024-09-25 00:20:47 发布

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

我有一个带有层次索引的Pandas数据帧。它完全由整数(可能还有nan)组成。对于索引中的每个级别和某些列,我有一个字典,它将每个整数映射到不同的字符串,我希望用字符串而不是列来表示数据帧。我正在测试如下所示的代码:

import pandas as pd
import numpy as np
mappings = {'ace': {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'},
            'algo': {0:'x', 1:'y', 2:'z', 3:'w', 4:'v'},
            'lucky': {0:'str0', 1:'str1', 2:'str2', 3:'str3', 4:'str4'}}
df = pd.DataFrame( np.random.randint(0, 5, (100, 5)), 
                   columns=('ace', 'spade', 'lucky', 'algo', 'boo') )
_a = df.set_index(['ace', 'algo'])
_b = df.groupby(['ace', 'algo']).size()
groups_small = _b[_b <= _b.quantile(0.7)].index
df_out = _a.drop(groups_small)

例如,如果df_out是:

^{pr2}$

我想把它变成:

          spade  lucky  boo
ace algo
a   y         3   str0    0
    v         0   str0    1
b   v         0   str4    3
d   w         1   str4    4
    w         2   str1    1
c   x         0   str3    1
a   v         2   str2    1
    y         0   str4    2
    y         3   str3    3

通过mappings。我要做哪些手术?在


Tags: 数据字符串importdfasnp整数mappings