0

EDIT:

This is similar to stackoverflow.com/questions/36531675/rename-columns-in-pandas-based-on-dictionary but it is not the same.

Given that I already have defined a dictionary how do I map the column names? Besed on the above answer I try this but it gives me NaN values.

test = df.columns.to_series().map(columns)

----- End edit -----

I have a pandas dataframe something like this:

df = pd.DataFrame(
    {'id': [1, 2, 3, 4, 5],
     'oldname1': ['something'] *5,
     'old_name1': [1.10, 1.12, 1.23, 1.03, 1.22],
     'oldname_1': [1.10, 1.12, 1.23, 1.03, 1.22],
     'oldname1': ['ABC123'] * 5
     })

I want to rename the columns using df.columns = ['list of new columns']

The columns to be changed are stored in a dict:

columns = {
    'oldname1': 'new_nameA',
    'old_name1': 'new_nameB',
    'oldname_1': 'new_nameC',
    'oldname_2': 'new_nameD'
}

To rename I do the following:

new_column_names = []
for col in df:
    col = col.lower()
    if col in columns.keys():
        for key in columns.keys():
            new_col = col.lower().replace(key, columns[key])
            if new_col not in new_column_names:
                new_column_names.append(new_col)
    else:
        new_column_names.append(col)

At this point the new_column_names are: ['id', 'new_name1', 'oldname1', 'old_name1', 'oldname_1']

Once correct I can update the dataframe's columns

df.columns = new_column_names

Where am I going wrong? Can I code this better?

Spatial Digger
  • 1,883
  • 1
  • 19
  • 37
  • 3
    `df = df.rename(columns=columns)` – mozway Sep 30 '22 at 09:56
  • @mozway thank you for your comment, but I need to generate the correct column values, as stated above, before renaming the columns. – Spatial Digger Sep 30 '22 at 10:38
  • Can you provide the explicit expected output and clarify the logic? – mozway Sep 30 '22 at 10:55
  • @mozway I have a pandas dataframe. I want to replace column names if they are specified in the dictionary. If the dictionary matches the `oldname` then I want it to be replaced with the `newname` , as I explain in the OP. – Spatial Digger Sep 30 '22 at 11:04
  • 1
    What is unclear is how `df.rename(columns=columns)` doesn't work for you, please clarify with an explicit example – mozway Sep 30 '22 at 11:09
  • @mozway because `columns` is a dictionary, if it was a list `['id', 'new_nameA', 'new_nameB', 'new_nameC', 'new_nameD']` then that would work. – Spatial Digger Sep 30 '22 at 11:19
  • I copy-pasted the first two code blocks in your question, then applied mozway's solution, and that worked perfectly fine. You're doing something else in between to get an incorrect result. – 9769953 Sep 30 '22 at 11:20
  • Also read [the documentation for `pandas.DataFrame.rename`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html), in particular for the `columns` parameter. – 9769953 Sep 30 '22 at 11:21
  • 1
    Note that your example dataframe has two columns `'oldname1'`. – 9769953 Sep 30 '22 at 11:22
  • 1
    @SpatialDigger please try it, `rename` knows how to use a dictionary – mozway Sep 30 '22 at 11:25

0 Answers0