Carola
Carola

Reputation: 366

Remove column name suffix from DataFrame Python

I have the following pandas DataFrame in python:

attr_x header example_x other
3232 322 abv ideo
342 123213 ffee iie
232 873213 ffue iie
333 4534 ffpo iieu

I want to remove the suffixes '_x' from all columns containing it. The original DataFrame is much longer. Example result:

attr header example other
3232 322 abv ideo
342 123213 ffee iie
232 873213 ffue iie
333 4534 ffpo iieu

Upvotes: 3

Views: 546

Answers (1)

jezrael
jezrael

Reputation: 863741

Use str.removesuffix:

df.columns = df.columns.str.removesuffix("_x")

Or replace:

df.columns = df.columns.str.replace(r'_x$', '')

Upvotes: 3

Related Questions