Lud*_*udo 3 python rename dataframe python-3.x pandas
我有一个数据框列表,我遍历它们,使用一个 Pandasdf.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)
Run Code Online (Sandbox Code Playgroud)
它似乎适用于某些表,部分适用于其他表,然后完全不适用于某些表。为什么?例如,即使列 'vol' 正确映射到同一个 df 中的 'Volume Sales','aic' 索引没有在其中包含 'aic' 的 df 中正确重命名。
根据关于重命名参数的Pandas 文档mapper, index, columns
,它是这样写的:
使用任一 映射器和轴线以指定的轴目标与映射器,或索引和列
在你举的例子中,
{
'vol': 'Volume Sales',
'val': 'Value Sales',
}
Run Code Online (Sandbox Code Playgroud)
函数将其理解为 asmapper =
然后您给出index
和columns
。在无法重现的情况下,该函数可能rename
有一些“麻烦”来理解您提供的参数(我想查看后面的代码会给出原因)
这也解释了为什么该列'vol'
被重命名'Volume Sales'
而不是'Volume Sales (L)'
像中定义的那样column=