kbk
kbk

Reputation: 61

Pandas: renaming columns that have the same name

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"})

Upvotes: 6

Views: 14189

Answers (6)

Weston A. Greene
Weston A. Greene

Reputation: 127

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)]

Upvotes: 0

aze45sq6d
aze45sq6d

Reputation: 925

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)]

Upvotes: 2

Karn Kumar
Karn Kumar

Reputation: 8816

try:

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

>>> df
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

Upvotes: 10

jpp
jpp

Reputation: 164623

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')

Upvotes: 0

naman
naman

Reputation: 490

You can simply do:

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

Upvotes: -1

Batman
Batman

Reputation: 8917

You can always just manually rename all the columns.

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

Upvotes: 1

Related Questions