Loop Through Pandas Dataframe And Split Into Multiple Dataframes Based On Unique Column Values
I have a dataframe saved in a list. Is there a way to loop through the list to create separate dataframes based of a column value? ex: Turn this df To this: df1 df2 I have searc
Solution 1:
Try this:
df1 = df.loc[df['ID'] == 0902]
df2 = df.loc[df['ID'] == 0105]
Or this:
df1, df2 = [groupfor _, groupin df.groupby('ID')]
Or if you want it dynamically:
dct = {f'df{idx}': groupfor _, groupin df.groupby('ID')]}
print(dct)
Or:
dct = {}
for idx, v in enumerate(df['ID'].unique()):
dct[f'df{idx}'] = df.loc[df['ID'] == v]
print(dct)
And print like this for specific dataframe:
print(dct['df1'])
Solution 2:
You can create variables df1
and df2
dynamically using locals()
:
for i, (ID, subdf) inenumerate(df.groupby('ID'), 1):
locals()[f'df{i}'] = subdf
Output:
>>>df1IDColourTransport20105 redcar30105 yellowcar40105 orangeboat>>>df2IDColourTransport00902 redcar10902 bluecar
Or you can create a dictionary indexed by the group ID
:
dfs = dict(list(df.groupby('ID')))
Output:
>>>dfs['0105']
ID Colour Transport
2 0105 red car
3 0105 yellow car
4 0105 orange boat
>>>dfs['0902']
ID Colour Transport
0 0902 red car
1 0902 blue car
Post a Comment for "Loop Through Pandas Dataframe And Split Into Multiple Dataframes Based On Unique Column Values"