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.
JavaScript
x
19
19
1
import pandas as pd
2
3
data = {
4
'group': ['a', 'a', 'a', 'b', 'b', 'c', 'c'],
5
'num': list(range(7))
6
}
7
df = pd.DataFrame(data)
8
9
unique_groups = df['group'].unique()
10
11
# How do I incorporate this logic inside a for loop??
12
var1 = df[df['group'] == unique_groups[0]]
13
var2 = df[df['group'] == unique_groups[1]]
14
var3 = df[df['group'] == unique_groups[2]]
15
16
# My approach:
17
for i in range(len(unique_groups)):
18
var + i = df[df['group'] == unique_groups[i]] # obviously "var + i" does not work
19
Advertisement
Answer
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:
JavaScript
1
2
1
all_vars = [group for name, group in df.groupby("group")]
2