Python Forum

Full Version: iloc
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
in pandas, in order to obtain the 8th row from the 4th to the 7th column,
the following command works properly:
(data.iloc[9, 5:8] )
but what if I would like to repeat the same operation for other specific rows,
for instance the 15th, the 18th and so on, is there anything that I can implement
in the line of code above or I must write data.iloc for every row that I am interested in?
data.iloc[[9,15,18], [5:8]] 
your line produces an error:

Error:
File "C:/Users/file.py", line 11 print(data.iloc[[9,15,18], [5:8]]) ^ SyntaxError: invalid syntax
I have tried another strategy but it doesn't always work:

the for loop itself prints all the lines the right way, (I am converting them to lists)
    for i in range(9,100,18):
        return(( (data.iloc[i,2:10]).values.tolist()  ))
but inside a function, only the first list is printed.
How come? How to fix this function in order to obtain
the same outcome as the for loop?

def total_lists(start, end, step):
    for i in range(start,end,step):
        return(( (data.iloc[i,2:10]).values.tolist()  ))

print(total_lists(9,100,18)) # just prints the first line
Return will exit function on the first row. Try like this

def total_lists(start, end, step):
    lst = []
    for i in range(start,end,step):
        lst.append(data.iloc[i,2:10]).values.tolist())
    return(lst)
same thing. Only the first line is printed.
(Apr-25-2020, 08:52 AM)d8a988 Wrote: [ -> ]same thing. Only the first line is printed.

Can you post complete code?
That's ok, I figured out another way.
All you need to do is to convert it to a list
outside the function.