Home > Mobile >  rename a duplicated IDs pandas
rename a duplicated IDs pandas

Time:02-24

I think it is stupid question but couldn't think of the answer d:

I have a family ID which is duplicated for all family members, it looks like:

Fam_ID member_no
12121 1
12121 2
12121 3
12121 4
12121 5
12121 6
12121 7
12121 8
12124 1
12124 2
12125 1
12125 2
12125 3

what i want is renameing the family ID, whether by numbering or labeling with family1,family2 .... and results will be:

Fam_ID member_no fmily_label
12121 1 family1
12121 2 family1
12121 3 family1
12121 4 family1
12121 5 family1
12121 6 family1
12121 7 family1
12121 8 family1
12124 1 family2
12124 2 family2
12125 1 family3
12125 2 family3
12125 3 family3

CodePudding user response:

Easy:

for ix, fam in enumerate(df.Fam_ID.unique()):
    df.loc[df.Fam_ID==fam, 'fmily_label'] = f'family{ix 1}'
  • Related