在这种情况下,如何使用正则表达式更改熊猫列名称?

Mil*_*001 4 python pandas

我有一个pandas数据框,其中有很多带有[0][1]字符串的列名,我想知道如何将它们更改为_01等等。

这是我的示例代码:

import numpy as np
import pandas as pd

df = pd.DataFrame({'id':[10,20],'flux[0][0]':[1.1,1.2],
                   'flux[1][0]':[1.3,1.4],'ellip[2][0]':[1.5,1.6]})

print(df)
   flux[0][0]  flux[1][0]  ellip[2][0]  id
0         1.1         1.3         1.5  10
1         1.2         1.4         1.6  20
Run Code Online (Sandbox Code Playgroud)

我的尝试:

df.columns = ['flux_00', 'flux_10', 'ellip_20', 'id']
print(df)
   flux_00  flux_10  ellip_20  id
0      1.1      1.3      1.5  10
1      1.2      1.4      1.6  20
Run Code Online (Sandbox Code Playgroud)

但是,对于许多列来说,它花费的时间太长。还有其他更简单的方法吗?

我对熊猫很陌生,所以请耐心和善良。

Bre*_*dan 5

df = pd.DataFrame({'id':[10,20],'flux[0][0]':[1.1,1.2],
                   'flux[1][0]':[1.3,1.4],'flux[2][0]':[1.5,1.6]})

# Per comment, if you have column names other than 'flux...':
df.columns = df.columns.str.replace(pat='\[', repl='_', n=1).str.replace(pat='\[|\]', repl='')

Run Code Online (Sandbox Code Playgroud)

产量

   id  flux_00  flux_10  flux_20
0  10      1.1      1.3      1.5
1  20      1.2      1.4      1.6
Run Code Online (Sandbox Code Playgroud)