你可以使用
df.columns.str.contains
:
df = pd.DataFrame({'oldName1': [1,1], 'zzzoldName2': [2,2], 'someoldName3': [3,3]})
converters = {'oldName1': 'newName1','oldName2': 'newName2','oldName3': 'newName3'}
conversion_map = {df.columns[df.columns.str.contains(old)][0]: new for old, new in converters.items()}
df.rename(columns=conversion_map)
>> newName1 newName3 newName2
0 1 3 2
1 1 3 2
请注意
[0]
将返回第一个匹配项,因此您可能需要检查
conversion_map
查看名称是如何更改的。如果这样找不到名称,它将引发
IndexError