Remove column name suffix from DataFrame Python

Question:

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
Asked By: Carola

||

Answers:

Use str.removesuffix:

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

Or replace:

df.columns = df.columns.str.replace(r'_x$', '')
Answered By: jezrael
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.