且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据相邻列名重命名 pd.DataFrame 中的列

更新时间:2023-11-22 22:05:16

如果我有这样的示例数据:

If I have sample data like this:

df = pd.DataFrame(
    {
        'Contour': range(5),
        'X': range(5, 10),
        'slice-0010-EDSR_x2': range(10, 15),
        'X_': range(5, 10),
        'slice-0011-EDSR_x2': range(10, 15),        
    }
)

那么我可以用下面的代码实现你的目标.

then I can achieve your goal with the following code.

col_names = df.columns.tolist()
new_col_names = []

for i_col, col in enumerate(col_names):
    if i_col == 0:
        new_col = col
    elif col.startswith('X'):
        new_col = col_names[i_col + 1] + '_X'
    else:
        new_col = col + '_Y'
    
    new_col_names.append(new_col)
    
df.columns = new_col_names
print(df)

结果如下:

   Contour  slice-0010-EDSR_x2_X  slice-0010-EDSR_x2_Y  slice-0011-EDSR_x2_X  \
0        0                     5                    10                     5   
1        1                     6                    11                     6   
2        2                     7                    12                     7   
3        3                     8                    13                     8   
4        4                     9                    14                     9   

   slice-0011-EDSR_x2_Y  
0                    10  
1                    11  
2                    12  
3                    13  
4                    14