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.
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
Asked: 2022-04-22 11:00:00 +0000
Seen: 14 times
Last updated: Jun 07 '21
How can popen() be used to direct streaming data to TAR?
In Python, can a string be utilized to retrieve a dataframe that has the same name as the string?
What is the method for merging field value and text into a singular line for display?
What is the method for programmatic access to a time series?