Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change all column names in chained operation

Tags:

python

pandas

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.

like image 971
Allen Avatar asked Feb 11 '18 21:02

Allen


People also ask

How do I change the column name in machine learning?

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.


1 Answers

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
like image 184
Allen Avatar answered Sep 25 '22 02:09

Allen