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
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 1cumcount
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With