rename a column if it contains certain character in python

To rename a column in a pandas dataframe based on a certain character, you can use the .rename() method and pass a dictionary to it. The dictionary should map the old column name (key) to the new column name (value).

For example, let's say you have a dataframe df with a column 'col_name' and you want to rename it to 'new_name' if it contains the character 'x'.

main.py
import pandas as pd

# example dataframe
df = pd.DataFrame({'col_name': ['abc', 'xyz', 'def'], 'col2': [1,2,3]})

# rename column if it contains 'x'
df = df.rename(columns={col: 'new_name' if 'x' in col else col for col in df.columns})

print(df)
247 chars
10 lines

This would output:

main.py
  new_name  col2
0      abc     1
1      xyz     2
2      def     3
68 chars
5 lines

In this example, the dictionary passed to .rename() uses a dictionary comprehension to iterate over all column names in df.columns, checking if 'x' exists in the name. If it does, the old name is mapped to 'new_name'; otherwise, the old name is left as is.

related categories

gistlibby LogSnag