Search code examples
pythonpandasdataframemultiple-columns

How to rename pandas column names by splitting with space


I have a dataframe like this:

index   col A   col B   col C
index1    3       1       2
index2    1       4       9
index3    5       1       2
index4    8       2       2
index5    2       1       6

I want to rename columns by splitting them with space. I dont want to do it manually since I have hundreds of columns. My ouutput looks like this:

index     A       B       C
index1    3       1       2
index2    1       4       9
index3    5       1       2
index4    8       2       2
index5    2       1       6

Can anyone help me with this


Solution

  • Use:

    df.columns = df.columns.str.split().str[1]