Victor
Victor

Reputation: 17107

How to rename multiple columns using a wildcard in pandas

I have a list of columns defined like this:

col_list=['Name_x','Num_x']

I have a df. Any column that matches the colname is col_list, I wish to remove the_x from the col_name.

How can I do this?

Upvotes: 3

Views: 382

Answers (1)

Hryhorii Pavlenko
Hryhorii Pavlenko

Reputation: 3910

# df.columns
# Index(['Name_x', 'Num_x', 'test_x'], dtype='object')

col_list=['Name_x','Num_x']

df.columns = np.where(
    df.columns.isin(col_list), df.columns.str.replace(r'_x$', ''), df.columns)

# df.columns
# Index(['Name', 'Num', 'test_x'], dtype='object')

Upvotes: 1

Related Questions