Home > Net >  Pandas swap substrings in column names
Pandas swap substrings in column names

Time:03-02

I try to swap substrings in the column names of a DataFrame

K_1[0,0] K_1[0,1] K_1[1,20]
12 34 77
99 42 23

where the result should look like this

K_1[0,0] K_1[1,0] K_1[20,1]
12 34 77
99 42 23

So inside the parenthesis, the values before and after the comma should simply be interchanged.

Thanks in advance!

CodePudding user response:

You can use DataFrame.rename with a callable that employs a regular expression.

import re
df = df.rename(lambda c: re.sub('(.*)(\d ),(\d )(.*)', r'\1\3,\2\4', c), axis=1)

CodePudding user response:

Use str.replace:

df = pd.DataFrame(columns=['K_1[0,0]','K_1[0,1]','K_1[1,20]'])

df.columns = df.columns.str.replace(r'^(.*)(\d ),(\d )(.*)$', r'\1\3,\2\4')
print (df)      
Empty DataFrame
Columns: [K_1[0,0], K_1[1,0], K_1[20,1]]
Index: []
  • Related