Niam45
Niam45

Reputation: 578

Add prefix to dataframe columns that match those names in a list

Consider that I have a list called columns_to_prefix.

The list looks like this:

columns_to_prefix = ['fruit', 'colour', 'country']

Then consider that I had a dataframe as follows:

fruit    colour    popularity    country   cost
Apple    Green     High          UK        2
Berry    Red       High          Spain     4

I want to put the prefix of 'the_' in front of the columns in this list.

data = data['columns_to_prefix'].add_prefix('the_')

This is an example dataframe, my actual dataframe has hundreds of columns so a method that uses the specific column names will not work.

Upvotes: 0

Views: 199

Answers (1)

Corralien
Corralien

Reputation: 120509

Use a comprehension:

columns_to_prefix = set(['fruit', 'colour', 'country'])
df.columns = [f"the_{c}" if c in columns_to_prefix else c for c in df.columns]
print(df)

# Output
  the_fruit the_colour popularity the_country  cost
0     Apple      Green       High          UK     2
1     Berry        Red       High       Spain     4

Upvotes: 2

Related Questions