Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate through list but return prescribed index numbers grouped together

I’m trying to figure out how to loop through a df and return not just one row of data, but a prescribed group of data. Hard to explain so I’ll use a simple example

import pandas as pd

data = [['apple', 1], ['orange', 2], ['pear', 3], ['peach', 4],['plum', 5], ['grape', 6]]
#index_groups = [0],[1,2],[3,4,5]
df = pd.DataFrame(data, columns=['Name', 'Number'])

for i in range(len(df)):
    print(df['Number'][i])


       Name     Age
0      apple    1
1      orange   2
2      pear     3
3      peach    4
4      plum     5
5      grape    6

I need to know how to set my [i] to be either 0, (1&2), (3&4&5) (see the index_groups column)

I want to group my results but by a grouping I determine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Do you mean something like

index_groups = [0], [1, 2], [3, 4, 5]
for group in index_groups:
    print(df.loc[group])

    Name  Number
0  apple       1

     Name  Number
1  orange       2
2    pear       3

    Name  Number
3  peach       4
4   plum       5
5  grape       6

If you want just Number column

for group in index_groups:
    print(df['Number'].loc[group])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading