Exploring GroupBy Objects - Data Aggregation

Hi everyone,

Just a little curious as to why there need to be two square brackets around the north_america = happiness2015.iloc[[4,14]] instead of just one square bracket? I know it’s a silly question but I keep making this mistake in my code! :face_with_monocle:

Screen Link:

My Code:

grouped = happiness2015.groupby('Region')
north_america = happiness2015.iloc[4,14]
na_group = grouped.get_group("North America")
equal = north_america == na_group

What I expected to happen:
Correct Output

What actually happened:

IndexError: single positional indexer is out-of-bounds

Thank you!!

Hi h.mojid72

In order to select multiple rows, we have to pass the list labels or indexes. Hence we have to pass [4, 14] to happiness2015.iloc[].

Hope it’s clear now?


Hi everyone ,
I’m not sure as to why i’m getting this error , if someone can help me out it’ll be great!
grouped = happiness2015.groupby(‘Region’)
north_america = happiness2015.iloc[4:15]
na_group = grouped.get_group(‘North America’)
equal = north_america == na_group
link : Learn data science with Python and R projects

Error : ValueError: Can only compare identically-labeled DataFrame objects


Welcome to the community!
If you run the code grouped.groups, you could see in the output that the for the North America group the indices are 4 and 14.

Hence your code should have been
north_america = happiness2015.iloc[[4, 14]]
instead of

Hope it’s clear now.