I'd like to ask if there are any smart ways of slicing pandas DataFrame in to smaller ones by column value. What I want to achieve is:
Having dataframe like this:
df = pd.DataFrame(data = {'ID' : [1, 1, 1, 2, 2, 2, 3, 3, 3], 'revenue': [10, 20, 30, 40, 50, 60, 70, 80, 90]})
I want to iterate trough unique ID values, that I have in list by simply doing: id_list = df.ID.unique()
and save it in separate dataframes with assigned name like df_ID (it would be nice, to create dataframe object name with specific ID in it)
Of course there is possibility of just filtering df by column values like:
df_1 = df[['ID' == 1]]
but the problem is if new IDs will be added to my df, I don't want to create another df manually
I was thinking if there is a way of doing something like:
def df_by_ID(df):
df_IDs = df.ID.unique()
for ID in df_IDs:
new_df = df[['ID' = ID]]
#(i know what's below is not correct, altough I have no clue how to describe that part differently)
f'df_{ID}' = new_df
return df_ID
Thanks for your help!