Home > Mobile >  Remove column name suffix from DataFrame Python
Remove column name suffix from DataFrame Python

Time:10-04

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

CodePudding user response:

Use str.removesuffix:

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

Or replace:

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