I'm looking for an efficient, all-Pandas way of creating an array with group numbers (for every row in the original dataframe I want a number that tells me which group this row belongs to):
df = pandas.DataFrame({'a': [1, 1, 1, 2, 2, 2], 'b': [1, 2, 1, 1, 2, 1]})
groups = df.groupby(['a', 'b'])
group_names = sorted(groups.groups.keys())
group_indices = np.array(df.index)
for index, group in enumerate(group_names):
group_indices[groups.indices[group]] = index
where
In : df
Out]:
a b
0 1 1
1 1 2
2 1 1
3 2 1
4 2 2
5 2 1
In : groups.indices
Out:
{(1, 1): array([0, 2]),
(1, 2): array([1]),
(2, 1): array([3, 5]),
(2, 2): array([4])}
In : group_indices
Out: array([0, 1, 0, 2, 3, 2])
My problem is that if df is around 20000x100 (64 bit floats) and I group by two of the columns, I get memory usage above 6 GB. Which is way more than I'd expect.