Home > Net >  Iterate through list but return prescribed index numbers grouped together
Iterate through list but return prescribed index numbers grouped together

Time:09-06

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.

CodePudding user response:

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])

CodePudding user response:

Change the string "group" to whatever title you want for each group

for i in index_groups:
        print ("group")
        for a in i:
            print (df['Number'][a])
        

CodePudding user response:

this works:

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'])

print('Name', 'Number')
for i in range(len(df)):
    print (df['Name'][i], df['Number'][i])
  • Related