python df.rename并不总是有效

时间:2018-05-07 15:58:22

标签: 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索引...

2 个答案:

答案 0 :(得分:2)

根据解释参数mapper, index, columns的{​​{3}},写成:

使用 映射器和轴指定要使用映射器定位的轴,或索引和列

在你举例中,

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

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

这也解释了为'vol'

中定义的'Volume Sales'列重命名为'Volume Sales (L)'而非column=的原因

答案 1 :(得分:1)

问题出在前几行:

df.rename(
    {
        'vol': 'Volume Sales',
        'val': 'Value Sales',
    },

我不知道为什么,但是一旦我删除了前两个映射,它就开始工作了。我的猜测是df.rename的工作方式是,如果你传递一个通用映射,并且它在你的df中找到一个匹配其中一个键的术语,那么它只会查找那些并且不关心你的特定索引和列映射。 / p>