有条件地重命名多个列名

2024-09-30 04:28:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用相同的名称重命名多个列,方法是为每个重复项添加数字1

这就是我尝试过的

select_cols = np.asarray([i for i, col in enumerate(fully_merged.columns) if 'stance' in col])
fully_merged.rename(columns={cols:'stance'+str(i) for cols in fully_merged.columns[select_cols] for i in range(1,7)})
# df.rename(columns={col: '' for col in df.columns[idx_filter]}, inplace=True)

但对于每个带有stance一词的列,它都返回'stance6'

以下是我的列名示例:

x1,stance,y1,x2,stance,y2,x3,stance,y3,x4,stance,y4,x5,stance,y5,x6,stance,y6

预期输出:

x1,stance1,y1,x2,stance2,y2,x3,stance3,y3,x4,stance4,y4,x5,stance5,y5,x6,stance6,y6

Tags: columnsindfforcolmergedselectx1
1条回答
网友
1楼 · 发布于 2024-09-30 04:28:09

将列转换为序列并按^{}创建计数器用于将具有1值的列重命名为N值的列:

a = 'x1,stance,y1,x2,stance,y2,x3,stance,y3,x4,stance,y4,x5,stance,y5,x6,stance,y6'
df = pd.DataFrame(columns=a.split(','))

select_cols = df.columns.to_series()
count = select_cols.groupby(level=0).cumcount().add(1).astype(str)

df.columns = np.where(select_cols == 'stance', 'stance' + count, select_cols)
print (df)
Empty DataFrame
Columns: [x1, stance1, y1, x2, stance2, y2, x3, stance3, y3, 
          x4, stance4, y4, x5, stance5, y5, x6, stance6, y6]
Index: []

相关问题 更多 >

    热门问题