Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- Renaming duplicated values based on another variable

Is there anyway to rename the values based on another variable? Over here I have two columns, one of which is ID and another is fruits. However, I was thinking would it be possible to uniquely identify them based on the ID

ID  Fruits
1    Apple
1   Banana
1   Orange
1   Banana
2    Apple
2   Orange
2   Orange
3    Apple
3    Apple
3   Orange

Was hoping to achieve something like that

ID  Fruits
1    Apple
1   Banana
1   Orange
1  Banana1
2    Apple
2   Orange
2  Orange1
3    Apple
3   Apple1
3   Orange
like image 624
Denova Avatar asked Jun 13 '18 04:06

Denova


1 Answers

Setup

df = pd.DataFrame({
    'id': [1,1,1,1,2,2,2,3,3,3],
    'fruit': ['Apple', 'Banana', 'Orange', 'Banana', 'Apple', 'Orange', 'Orange', 'Apple', 'Apple', 'Orange']
})

Option 1
cumcount with replace and string concatenation (I use a regex pattern that only matches a single zero so this answer can also support more than 9 duplicates per group):

df['fruit'] = df.fruit + df.groupby(
    ['id', 'fruit']).cumcount().astype(str).replace(
    r'^0$', '', regex=True
)

Option 2
Store the groupby and use boolean indexing with fillna (I personally prefer this approach)

s = df.groupby(['id', 'fruit']).cumcount()
df['fruit'] = (df.fruit + s[s>0].astype(str)).fillna(df.fruit)

Both result in:

   id    fruit
0   1    Apple
1   1   Banana
2   1   Orange
3   1  Banana1
4   2    Apple
5   2   Orange
6   2  Orange1
7   3    Apple
8   3   Apple1
9   3   Orange
like image 100
user3483203 Avatar answered Nov 15 '22 13:11

user3483203