pandasdataframerenameprefix

Insert prefix to all pandas dataframe columns names


I have created the following pandas dataframe:

import pandas as pd

ds = {"col1":[1,2,3,4,5], "col2":[6,7,8,9,10]}
df = pd.DataFrame(data=ds)
print(df)

Which looks like this:

   col1  col2
0     1     6
1     2     7
2     3     8
3     4     9
4     5    10

I need to add a prefix (Milan_) to all columns anmes. Bear in mind that in a real dataframe I have 2,000+ columns, so I won't be able to do it manually.

The resulting dataframe would look like this:

   Milan_col1  Milan_col2
0           1           6
1           2           7
2           3           8
3           4           9
4           5          10

Is there an automatica way to do it in Python for dataframes with 2,000+ fields?


Solution

  • There certainly is a way to do that

    df_new = df.add_prefix("Milan_")