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

编程入门 行业动态 更新时间:2024-10-27 02:24:16
本文介绍了根据相邻列名重命名 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 中的列

本文发布于:2023-10-25 03:18:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525766.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重命名   pd   DataFrame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!