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.
set_axis method is used to change the index or column names. This method can also be used to rename the multiple columns at once in pandas by passing a list or tuple of new column names and setting the value of the axis parameter to 1.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With