Filter by unique values in column and apply function seperately

Viewed 18

I have a dataframe df where df.head() which looks like

category value time
A 4 10:15
B 5 10:20
B 5 12:30
Z 6 12:45
S 5 13:45

I have a pre-existing function def op(df): which has a different calculation for each category which I want to apply separately when the category is filled with for example only A, then it is filled with on B and so on.

Basically, the function should be applied to each filtered dataframe containing each category value.

I tried applying the function separately for each category but it does not seem efficient

df_A = df[df.category=='A']
df_A = op(df_A)
df_B = df[df.category=='B']
df_B = op(df_B)
..
..
..
df_Z = df[df.category=='Z']
df_Z = op(df_Z)
final_df = pd.concat[df_A,df_B,....df_Z]

Question: How do I apply the function to each value in the column separately more efficiently, for example if there are more than 50 categories?

NOTE: Because of the time column, groupby is not the right option, each category of same value is different. Therefore the GROUP BY does not work

0 Answers
Related