Ask Your Question
1

How can a list in a data frame be renamed based on a dictionary in Python?

asked 2022-04-22 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-06-07 20:00:00 +0000

lakamha gravatar image

You can use the rename() function in pandas to rename columns in a data frame based on a dictionary. Here's an example:

import pandas as pd

# Create a sample data frame with columns to be renamed
df = pd.DataFrame({'old_col_1': [1, 2, 3],
                   'old_col_2': [4, 5, 6]})

# Define a dictionary to map old column names to new names
col_dict = {'old_col_1': 'new_col_1',
            'old_col_2': 'new_col_2'}

# Use the rename function to apply the dictionary mapping to column names
df = df.rename(columns=col_dict)

# Print the resulting data frame with renamed columns
print(df)

This code will output:

   new_col_1  new_col_2
0          1          4
1          2          5
2          3          6

As you can see, the columns have been renamed based on the dictionary mapping.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-22 11:00:00 +0000

Seen: 14 times

Last updated: Jun 07 '21