How to calculate count and first occurrence of list data?

Viewed 29

I have a list which has types of cars,

a = ['Car_1','Car_1','Car_1','Car_2','Car_3','Car_3']

I should be able to create an output of 2 lists from the above list,

result_count = [1,0,0,1,1,0] #Whenever new car type is present in list, make it 1
result_count = [1,2,3,1,1,2] #Count each car type

How can I easily achieve this without using for loops? Thanks.

1 Answers

IIUC, using a pandas dataframe

for #1 we can use .drop_duplicates

for #2 we can use groupby and cumcount

df = pd.DataFrame({'cars' : a})

one = (~df['cars'].duplicated()).astype(int).tolist() # Thanks to Erfan
two = (df.groupby('cars').cumcount() + 1).tolist()

print(one)

[1 0 0 1 1 0]

print(two)

[1, 2, 3, 1, 1, 2]
Related