python - 索引和列上的 pandas df.rename 并不总是有效

标签 python python-3.x pandas dataframe rename

我有一个数据框列表并遍历它们,使用一个 pandas df.rename 重命名所有列/索引方法调用。

df.rename(
    {
        'vol': 'Volume Sales',
        'val': 'Value Sales',
    },
    index={
        't1': info['literal_periods'][0],
        't2': info['literal_periods'][1],
        'acv': '% ACV Distribution',
        'aic': 'Average Items Carried',
        'tdp': 'Total Distribution Points',
        'vol': 'Volume Sales',
        'psl': 'Promo Sales',
        'Share of AIC': '{} share of {} AIC'.format(
            info['name'], info['p1']),
        'Share of TDP': '{} share of {} TDP'.format(
            info['name'], info['p1']),
        'Target Product': info['name'],
        'target product': info['name'],
    },
    columns={
        't1':
        info['literal_periods'][0],
        't2':
        info['literal_periods'][1],
        'promo change':
        '% change from ya',
        'non promo change':
        '% change from ya',
        'sales change':
        '% change from ya',
        'val':
        'Value Sales (£)',
        'vol':
        'Volume Sales (L)',
        'volsu':
        'Volume Sales (units)',
        'litres per unit':
        'litres/unit',
        't2 Promo Sales':
        '{} Promo Sales'.format(info['literal_periods'][1]),
        't2 Non-Promo Sales':
        '{} Non Promo Sales'.format(info['literal_periods'][1]),
        't2 Total Sales':
        '{} Total Sales'.format(info['literal_periods'][1])
    },
    inplace=True)

它似乎对某些表非常有效,对其他表部分有效,对某些表则完全无效。为什么? 例如,即使列“vol”在同一个 df 中正确映射到“Volume Sales”,但在其中包含“aic”的 df 中,“aic”索引未正确重命名。

最佳答案

根据 Pandas documentation on rename其中参数mapper, index, columns有解释,是这样写的:

使用 mapper 和axis 来指定映射器的目标轴,或者index 和columns

以你举的例子为例,

{
    'vol': 'Volume Sales',
    'val': 'Value Sales',
}

函数将其理解为 mapper =,然后您提供 indexcolumns。如果无法重现,函数 rename 可能有一些“麻烦”来理解您提供的参数(我想查看后面的代码会给出原因)

这也解释了为什么列 'vol' 重命名为 'Volume Sales' 而不是 'Volume Sales (L)' 定义在 column=

关于python - 索引和列上的 pandas df.rename 并不总是有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50218179/

相关文章:

python - 从文本文件读取行后python代码中的IndexError

python-3.x - 比较和排序 DataFrame 两列中的值并在 python 中的同一行中排序

pandas - 对具有多索引列的数据帧的行之间的比较操作进行向量化

python - Django DB 表名,复数 double s

python - 停止 python 将 json 文件写入一行

Python:递归方法回滚变化?

python - 在Python中,对于POST请求,是否可以从POST请求对象中获取该请求所使用的ip地址?

python - 求和 pandas 数据框中字符串的出现次数

python - Pygraphviz/networkx 设置节点级别或层

未使用 pip 在 vi​​rtualenv 中安装 Python 包