根据相邻列名重命名 pd.DataFrame 中的列 [英] Renaming the columns in pd.DataFrame based on the adjacent column name

查看:81
本文介绍了根据相邻列名重命名 pd.DataFrame 中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 csv 文件如下图所示.

My csv file looks like below image.

所以我想使用相邻的列 slice-0010-EDSR_x2 重命名列 X.所以新的 X 列名称应该是 slice-0010-EDSR_x2_X而此列 slice-0010-EDSR_x2 名称应为 slice-0010-EDSR_x2_Y.并对应所有其他列

So I want to rename the column X using the adjacent column slice-0010-EDSR_x2. So the new column X name should be slice-0010-EDSR_x2_X And this column slice-0010-EDSR_x2 name should be slice-0010-EDSR_x2_Y . And cooresponding to all other columns

这有可能吗?

推荐答案

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

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  

这篇关于根据相邻列名重命名 pd.DataFrame 中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆