Skip to content
Advertisement

Select rows of a data frame in a loop based on list of indexes

I have one data frame & two (or multiple) lists of indexes:

data_ = {'Number_a': [12, 13, 14,15,16,17],'Number_b':[11,11,11,12,12,12],'Number_c': [10,5,4,3,2,1]}

data = pd.DataFrame(data=data_)

idx1= [0,2,4]
idx2=[1,3,5]
idx3 =[...,...,..]

I want to create a loop where I can select the rows of data. for each iteration, I use one list. so for 1st iteration data has the rows shown in idx1 0,2,4.

how I can do that ?

This is a simplified example, in my actual code, there are different functions that I need to loop on. for each iteration having different rows. Therefore it’s important for me to do that within a loop.

Advertisement

Answer

You can select rows with data.loc[rows].

data_ = {'Number_a': [12, 13, 14,15,16,17],'Number_b':[11,11,11,12,12,12],'Number_c': [10,5,4,3,2,1]}

data = pd.DataFrame(data=data_)
idx1 = [0,2,4]
idx2 = [1,3,5]

for r in (idx1, idx2):
    print(data.loc[r])

Output:

   Number_a  Number_b  Number_c
0        12        11        10
2        14        11         4
4        16        12         2
   Number_a  Number_b  Number_c
1        13        11         5
3        15        12         3
5        17        12         1
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement