jeudi 12 octobre 2023

Creating a pattern in a sequence for groupby in pandas

I am having A dataset of Three columns ID , 'sort_seqandlevel. basically i want to identify id wise level sequence sort by sort_seq. please suggest any optimal code other then for loop` because it is taking longer time with dictionary and appending in list.

Input Dataset

    import pandas as pd
import numpy as np
data = {'id': [1, 1, 1, 1,2, 2, 3, 3, 3, 3, 4, 5, 5, 6],
        'sort_seq': [89, 24, 56,  8,  5, 64, 93, 88, 61, 31, 50, 75,  1, 81],
        'level':['a', 'a',  'b', 'c', 'x', 'x', 'g', 'a', 'b', 'b', 'b', 'c', 'c','b']}
df = pd.DataFrame(data)

Expected Output

enter image description here

Tried Code

collect = []
for ij in df.id.unique():
  idict = {}
  x =  df[df['id'] == ij]
  x = x.sort_values(by='sort_seq',ascending=True)
  x = x.reset_index()
  idict[ij] =  x['level'].tolist()
  collect.append(idict)
collect

Aucun commentaire:

Enregistrer un commentaire