Reputation: 19947
I have a data frame:
df = pd.DataFrame(data=[[1,2]], columns=['a', 'b'])
I'm aware I can do the following to change all column names in a dataframe:
df.columns = ['d', 'e']
How can I change all column names in a chained operation? For example, I would like to do something like:
df=(
df.rename all column names
.reset_index()
)
The only way I can find is to use df.rename
and build a dictionary with the old and new column pairs but that looks very ugly. Are there any more elegant solutions?
Thanks.
Upvotes: 5
Views: 1149
Reputation: 19947
Thanks to @unutbu for pointing to a git hub issue, it turns out this can be done via set_axis from one of the comments there:
df = pd.DataFrame(data=[[1,2]], columns=['a', 'b'])
df
Out[21]:
a b
0 1 2
df2 = (
df.set_axis(['d','e'], axis=1, inplace=False)
.reset_index()
)
df2
Out[18]:
index d e
0 0 1 2
Upvotes: 9