假设我有一个包含同名列的 DataFrame:
x x y
2 5 1
1 9 3
4 1 2
是否有内置的通用函数来重命名具有相同名称的列以彼此不同? 可能结果的示例:
x0 x1 y
2 5 1
1 9 3
4 1 2
当使用 pandas.read_csv 读取 csv 时会自动执行此操作(默认 mangle_dupe_cols=True),但我找不到对 Python 中已有的 DataFrame 对象执行此操作的简便方法。
最佳答案
but I could not find a handy way to do this to a DataFrame object already
对于现有的数据框,我们必须求助于一些代码,没有内置代码;
s = pd.Series(df.columns)
df.columns= df.columns+s.groupby(s).cumcount().replace(0,'').astype(str)
x x1 y
0 2 5 1
1 1 9 3
2 4 1 2
关于python - 是否有内置的 Python/pandas 函数来重命名 pandas.DataFrame 中的重复列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63618066/