Fix Python – How to add a suffix (or prefix) to each column name?

Question

Asked By – Klausos Klausos

I want to add _x suffix to each column name like so:

featuresA = myPandasDataFrame.columns.values + '_x'

How do I do this? Additionally, if I wanted to add x_ as a suffix, how would the solution change?

Now we will see solution for issue: How to add a suffix (or prefix) to each column name?


Answer

You can use a list comprehension:

df.columns = [str(col) + '_x' for col in df.columns]

There are also built-in methods like .add_suffix() and .add_prefix() as mentioned in another answer.

This question is answered By – Stefan

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0