dg_no_9
dg_no_9

Reputation: 1013

Python - Get group names from aggregated results in pandas

I have a dataframe like this:

   minute   values
0   1        3
1   2        4
2   1        1
3   4        6
4   3        7
5   2        2

When I apply

df.groupby('minute').sum().sort('values', ascending=False)

This gives:

         values
minute
3        7
2        6
4        6
1        4

I want to get first two values in minute column in an array like [3,2]. How can I access values in minute column

Upvotes: 1

Views: 778

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

If what you want is the values from the minute column in the grouped dataframe (which would be the index column as well) , you can use DataFrame.index , to access that column. Example -

grouped = df.groupby('minute').sum().sort('values', ascending=False)
grouped.index[:2]

If you really want it as a list, you can use .tolist() to convert it to a list. Example -

grouped.index[:2].tolist()

Demo -

In [3]: df
Out[3]:
   minute  values
0       1       3
1       2       4
2       1       1
3       4       6
4       3       7
5       2       2

In [4]: grouped = df.groupby('minute').sum().sort('values', ascending=False)

In [5]: grouped.index[:2]
Out[5]: Int64Index([3, 2], dtype='int64', name='minute')

In [6]: grouped.index[:2].tolist()
Out[6]: [3, 2]

Upvotes: 1

Related Questions