我有一个数据框列表并遍历它们,使用一个 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 =
,然后您提供 index
和 columns
。如果无法重现,函数 rename
可能有一些“麻烦”来理解您提供的参数(我想查看后面的代码会给出原因)
这也解释了为什么列 'vol'
重命名为 'Volume Sales'
而不是 'Volume Sales (L)'
定义在 column=
关于python - 索引和列上的 pandas df.rename 并不总是有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50218179/