Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add Suffix to Dataframe with Specific Repeating Column Name

i have data in a dataframe such as the following columns: week, SITE, LAL, SITE, LAL. I need to assign a suffix to the col name == ‘SITE’ such that the final df will look like: week, SITE_1, LAL, SITE_2, LAL.

Thank you,

dataframe example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    week    SITE        LAL SITE        LAL
0   1   BARTON CHAPEL   1.1 PENASCAL I  1.0
1   2   BARTON CHAPEL   1.1 PENASCAL I  1.0
2   3   BARTON CHAPEL   1.1 PENASCAL I  1.0
3   4   BARTON CHAPEL   1.1 PENASCAL I  1.0
4   5   BARTON CHAPEL   1.1 PENASCAL I  1.0
5   6   BARTON CHAPEL   1.4 PENASCAL I  1.0

>Solution :

You can try to use itertools.count:

from itertools import count

cnt = count(1)
df.columns = [f'{c}_{next(cnt)}' if c == 'SITE' else c for c in df.columns]

print(df)

Prints:

   week         SITE_1  LAL      SITE_2  LAL
0     1  BARTON CHAPEL  1.1  PENASCAL I  1.0
1     2  BARTON CHAPEL  1.1  PENASCAL I  1.0
2     3  BARTON CHAPEL  1.1  PENASCAL I  1.0
3     4  BARTON CHAPEL  1.1  PENASCAL I  1.0
4     5  BARTON CHAPEL  1.1  PENASCAL I  1.0
5     6  BARTON CHAPEL  1.4  PENASCAL I  1.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading