how to rename columns based on a conditon pandas in python

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.py
import pandas as pd

df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie'],
    'gender': ['F', 'M', 'M'],
    'age': [25, 30, 35]
})

# rename columns where gender is 'M'
df = df.rename(columns={col: col+'_male' for col in df.columns if df.loc[df.gender == 'M', col].any()})

# output
print(df)

#   name name_male gender_male  age_male
#0  Alice     Alice          F        25
#1    Bob       Bob          M        30
#2   Charlie  Charlie         M        35
468 chars
19 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:

  • all columns with a gender value of 'M' have '_male' added to the end of their name
  • all other columns remain unchanged

related categories

gistlibby LogSnag