To rename columns based on a condition in pandas, you can use the rename()
method along with a dictionary comprehension to map the old column names to new column names that satisfy the condition.
Here's an example:
main.py468 chars19 lines
In this example, we start by creating a sample DataFrame with three columns: name
, gender
, and age
. We then use the rename()
method to create a new DataFrame with the following changes:
gender
value of 'M' have '_male' added to the end of their namegistlibby LogSnag