问题
I am trying to rename selected columns (say the two las columns) in my data frame using the iloc
and df.columns
functions but it does not seem to work for me and I can't figure out why. Here is a toy example of what I want to achieve:
import pandas as pd
d = {'one': list(range(5)),
'two': list(range(5)),
'three': list(range(5)),
'four': list(range(5)),
'five': ['a', 'b', 'c', 'd', 'e'],
'six': ['a', 'b', 'c', 'd', 'e']
}
df = pd.DataFrame(d)
df.iloc[:,-2:].columns = ['letter_1','letter_2']
df.columns
but I keep getting the original columns' names:
Index(['one', 'two', 'three', 'four', 'five', 'six'], dtype='object')
What am I missing?
回答1:
just use df.rename:
import pandas as pd
d = {'one': list(range(5)),
'two': list(range(5)),
'three': list(range(5)),
'four': list(range(5)),
'five': ['a', 'b', 'c', 'd', 'e'],
'six': ['a', 'b', 'c', 'd', 'e']
}
new_names = ['letter_1', 'letter_2']
df = pd.DataFrame(d).rename(index=str, columns=dict(zip(list(d.keys())[-len(new_names):], new_names)))
print(df.columns)
Output:
Index(['letter_1', 'four', 'one', 'letter_2', 'three', 'two'], dtype='object')
来源:https://stackoverflow.com/questions/56790037/renaming-selected-columns-in-pandas