<p>我希望在Pandas中找到一个解决方案,而不是一般的Python解决方案。
如果列的get_loc()函数找到指向找到重复项的位置的值为“True”的重复项,则返回一个屏蔽数组。然后我使用掩码将新值分配到这些位置。在我的例子中,我提前知道要得到多少个dup,以及要分配给它们什么,但是看起来df.columns.get_duplicates()将返回所有dup的列表,如果需要更通用的dup消除操作,则可以将该列表与get_loc()结合使用</p>
<pre><code>cols=pd.Series(df.columns)
for dup in df.columns.get_duplicates():
cols[df.columns.get_loc(dup)] = ([dup + '.' + str(d_idx)
if d_idx != 0
else dup
for d_idx in range(df.columns.get_loc(dup).sum())]
)
df.columns=cols
blah blah2 blah3 blah.1 blah.2
0 0 1 2 3 4
1 5 6 7 8 9
</code></pre>
<p><strong>新的更好的方法(更新日期:2019年12月3日)</strong></p>
<p>下面的代码比上面的代码好。从下面的另一个答案(@SatishSK)复制:</p>
<pre><code>#sample df with duplicate blah column
df=pd.DataFrame(np.arange(2*5).reshape(2,5))
df.columns=['blah','blah2','blah3','blah','blah']
df
# you just need the following 4 lines to rename duplicates
# df is the dataframe that you want to rename duplicated columns
cols=pd.Series(df.columns)
for dup in cols[cols.duplicated()].unique():
cols[cols[cols == dup].index.values.tolist()] = [dup + '.' + str(i) if i != 0 else dup for i in range(sum(cols == dup))]
# rename the columns with the cols list.
df.columns=cols
df
</code></pre>
<p>输出:</p>
<pre><code> blah blah2 blah3 blah.1 blah.2
0 0 1 2 3 4
1 5 6 7 8 9
</code></pre>