Given the following sample Dataframe:
df = pd.DataFrame( { 'A' : [ 1, 1, 1, 2, 2, 2, 3, 3, 3 ],
'B' : [ 'x', 'y', 'z', 'x', 'y', 'y', 'x', 'x', 'x' ] } )
I want to generate a scatterplot of the unique values of B (with the points sized by the number of B values within each group of unique values) against their corresponding values of A, so I want to get the following three lists:
A = [ 1, 1, 1, 2, 2, 3 ]
B = ['x', 'y', 'z', 'x', 'y', 'x']
Bsize = [ 1, 1, 1, 1, 2, 3]
I've tried doing this with groupby:
group = df.groupby(['A','B'])
The keys of the group contain the data I want, but they're not ordered:
group.group.keys()
[(1, 2), (1, 3), (3, 1), (2, 1), (2, 2), (1, 1)]
The 'first' method returns what looks like a Dataframe, but I can't access the 'A' and 'B' keys:
group.first()['A']
...
KeyError: 'A'
If I iterate through the names and groups, things seem to be ordered, so I can get what I want by doing:
A = []
B = []
for name, _ in group:
A.append(name[0])
B.append(name[1])
I can then get the Bsize list by doing:
group['B'].count().values
array([1, 1, 1, 1, 2, 3])
However, this seems clunky in the extreme and suggests to me I haven't understood how to properly use the group.