I am trying to create a for loop wherein a new dataframe is created based on a conditional statement of a column, but all I end up with is are only the column names without any values.
What I am doing now is the following:
for i in range(3):
df_new = df[df['col'] == i]
but this does not seem to work.
CodePudding user response:
Essentially with this for loop you are overwriting df
and since the first and second conditions can't be applied simultaneously, you will end with an empty dataframe.
You could create them dynamically within a dictionary, where the key is the name of the dataframe and the value the filtered dataframe. Try with:
dfs = {}
for i in range(3):
dfs["df_" str(i)] = df[df['col'] == i]
This will generate a dictionary that looks like the following structure:
{df_1:df[df['col']==1],
df_2:df[df['col']==2]}
And you can access them via its key name dfs['df_1']