Home > Software engineering >  Dataframe column like groupby but not how to do it?
Dataframe column like groupby but not how to do it?

Time:06-24

Here is a sample dataframe.

import pandas as pd
d = {'id': ['101', '101', '101', '105', '105'], 
     'qty': [10, 15, 20, 50, 55],
    }
df31 = pd.DataFrame(data=d)
df31

    id  qty
0   101 10
1   101 15
2   101 20
3   105 50
4   105 55

How to get results like this?

enter image description here

CodePudding user response:

Looks like your desired output consist of empty strings.

You can use shift to check equality of a value with it's previous value and assign back '' if condition is met:

df31['id'] = np.where(df31['id'].shift() == df31['id'],'',df31['id'])

>>> print(df31)

    id  qty
0   101 10
1       15
2       20
3   105 50
4       55

>>> print(df31.to_dict('records'))

 [{'id': '101', 'qty': 10},
 {'id': '', 'qty': 15},
 {'id': '', 'qty': 20},
 {'id': '105', 'qty': 50},
 {'id': '', 'qty': 55}]

CodePudding user response:

Assuming the id-column is sorted:

df['id'] = df['id'].drop_duplicates().reindex(df.index, fill_value='')
  • Related