本文介绍了根据相邻列名重命名 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 中的列
发布评论