<p>其思想是将具有相同前缀的列分组,并为它们建立一个cumcount。你知道吗</p>
<p>由于我们需要分别处理不带前缀的列,因此需要使用<code>GroupBy.cumcount</code>和<code>np.where</code>分两步进行:</p>
<pre><code>cols = df.columns.str.split('_').str[0].to_series()
df.columns = np.where(
cols.groupby(level=0).transform('count') > 1,
cols.groupby(level=0).cumcount().add(1).astype(str).radd(df.columns),
cols
)
</code></pre>
<p/>
<pre><code>df
A B Data_mean1 Data_std2 Data_corr3 Text_one1 Text_two2 Text_three3
0 a e 1 5 9 foo bar bar
1 b f 2 6 10 bar foo bar
2 c g 3 7 11 foobar barfoo barbar
3 d h 4 8 12 barfoo foobar foofoo
</code></pre>
<hr/>
<p>一个更简单的解决方案是将不想添加后缀的列设置为索引。那么你可以简单地</p>
<pre><code>df.set_index(['A', 'B'], inplace=True)
df.columns = (
df.columns.str.split('_')
.str[0]
.to_series()
.groupby(level=0)
.cumcount()
.add(1)
.astype(str)
.radd(df.columns))
df
Data_mean1 Data_std2 Data_corr3 Text_one1 Text_two2 Text_three3
A B
a e 1 5 9 foo bar bar
b f 2 6 10 bar foo bar
c g 3 7 11 foobar barfoo barbar
d h 4 8 12 barfoo foobar foofoo
</code></pre>