在 Pandas 中按顺序重命名重复的列名

Lyn*_*ynn 6 python numpy pandas

我有一个数据框 df,我想在其中按连续顺序重命名两个重复的列:

数据

DD  Nice Nice Hello
0   1    1    2
Run Code Online (Sandbox Code Playgroud)

期望的

DD  Nice1 Nice2 Hello
0   1     1     2
Run Code Online (Sandbox Code Playgroud)

正在做

df.rename(columns={"Name": "Name1", "Name": "Name2"})
Run Code Online (Sandbox Code Playgroud)

然而,我正在运行该rename函数,因为两个列名相同,所以结果并不理想。

sj9*_*126 1

您可以使用itertools.count()计数器和列表表达式来创建新的列标题,然后将它们分配给数据框。

例如:

>>> import itertools
>>> df = pd.DataFrame([[1, 2, 3]], columns=["Nice", "Nice", "Hello"])
>>> df
   Nice  Nice  Hello
0     1     2      3
>>> count = itertools.count(1)
>>> new_cols = [f"Nice{next(count)}" if col == "Nice" else col for col in df.columns]
>>> df.columns = new_cols
>>> df
   Nice1  Nice2  Hello
0      1      2      3
Run Code Online (Sandbox Code Playgroud)

(f 字符串需要 Python 3.6+)

编辑:或者,根据下面的注释,列表表达式可以替换可能包含的任何标签,"Nice"以防出现意外的空格或其他字符:

new_cols = [f"Nice{next(count)}" if "Nice" in col else col for col in df.columns]
Run Code Online (Sandbox Code Playgroud)