Pandas: renaming columns that have the same name
Asked Answered
G

6

5

I have a dataframe that has duplicated column names a, b and b. I would like to rename the second b into c.

df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "b1": [7, 8, 9]})
df.rename(index=str, columns={'b1' : 'b'})

Trying this with no success..

df.rename(index=str, columns={2 : "c"})
Gorgonzola answered 8/10, 2018 at 12:24 Comment(1)
accept the answer which suits you best in order to clear from the Queue.Define
D
9

try:

>>> df.columns = ['a', 'b', 'c']

>>> df
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9
Define answered 8/10, 2018 at 12:32 Comment(0)
K
2

These solutions don't take into account the problem with having many cols. Here is a solution where, independent on the amount of columns, you can rename the columns with the same name to a unique name

 df.columns = ['name'+str(col[0]) if col[1] == 'name' else col[1] for col in enumerate(df.columns)]
Ketti answered 14/9, 2022 at 16:12 Comment(0)
B
1

You can always just manually rename all the columns.

df.columns = ['a', 'b', 'c']
Berryberryhill answered 8/10, 2018 at 12:34 Comment(0)
C
0

If your columns are ordered and you want lettered columns, don't type names out manually. This is prone to error.

You can use string.ascii_lowercase, assuming you have a maximum of 26 columns:

from string import ascii_lowercase

df = pd.DataFrame(columns=['a', 'b', 'b1'])

df.columns = list(ascii_lowercase[:len(df.columns)])

print(df.columns)

Index(['a', 'b', 'c'], dtype='object')
Colunga answered 8/10, 2018 at 12:38 Comment(0)
C
0

To piggy back off of the answer from @aze45sq6d, here's another solution that allows you to change the name of a column by its order (like index, but not technically):

column_indices_to_change = {5: 'New name'}
df.columns = [column_indices_to_change.get(enum, col) for enum, col in enumerate(df.columns)]
Concubinage answered 22/5 at 14:32 Comment(0)
S
-1

You can simply do:

df.columns = ['a','b','c']
Shovel answered 8/10, 2018 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.