I am trying to assign all the three unique groups from the group
column in df
to different variables (see my code) using Python. How do I incorporate this inside a for loop? Obviously var i
does not work.
import pandas as pd
data = {
'group': ['a', 'a', 'a', 'b', 'b', 'c', 'c'],
'num': list(range(7))
}
df = pd.DataFrame(data)
unique_groups = df['group'].unique()
# How do I incorporate this logic inside a for loop??
var1 = df[df['group'] == unique_groups[0]]
var2 = df[df['group'] == unique_groups[1]]
var3 = df[df['group'] == unique_groups[2]]
# My approach:
for i in range(len(unique_groups)):
var i = df[df['group'] == unique_groups[i]] # obviously "var i" does not work
CodePudding user response:
You can do this using a dictionary, basically:
all_vars ={}
for i in range(len(unique_groups)):
all_vars[f"var{i}"] = df[df['group'] == unique_groups[i]]
CodePudding user response:
From your comment it seems it is okay for all_vars
to be a list so that all_vars[0]
is the first group, all_vars[1]
the second, etc. In that case, consider using groupby
instead:
all_vars = [group for k, group in df.groupby("group")]