Python: How to iterate over appointed rows of dataframe? [closed]

I have a dataframe which contains 100 row and I would like to iterate over 20-40 rows. Is it possible?

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

for index, row in df.iterrows():
    print(row)  #<--  I would like to print 20-40 rows.

Why I am getting the error?

ValueError: Length of values (20) does not match length of index (100)

def points_in_polygons(kaf_start: int, kaf_end: int, bud_start: int, bud_end: int):
    kafelki = df_kafelki()
    budynki = df_budynki()
    budynki2 = df_budynki2()
    urls_column = []
    for index_kafelek, kaf_row in kafelki.iloc[kaf_start:kaf_end].iterrows():
        xmin = kaf_row['wspolrzedne'][1]
        ymin = kaf_row['wspolrzedne'][0]
        xmax = kaf_row['wspolrzedne'][3]
        ymax = kaf_row['wspolrzedne'][2]
        lu = geometry.Point(xmin, ymax)
        ld = geometry.Point(xmin, ymin)
        pu = geometry.Point(xmax, ymax)
        pd = geometry.Point(xmax, ymin)
        listpoint = [lu, pu, pd, ld]
        polygon = Polygon(listpoint)
        for index_budynku, bud_row in budynki2.iloc[bud_start:bud_end].iterrows():
            coo = shapely.wkt.loads(bud_row['classification.geometry'])
            m = bud_row['vertex_counter']
            urls_list_of_row = []
            for x, y in coo.exterior.coords:
                point = Point(x, y)
                if polygon.contains(point) == True:
                    m = m - 1
                    if kafelki['url'] not in urls_list_of_row:   
                        urls_list_of_row.append(kafelki['url'])       
                else:
                    m = m - 1
            if m == 0:
                urls_column.append(urls_list_of_row)
                budynki2.drop(index_budynku, inplace = True) 
        budynki['url_kafelka'] = urls_column
        return(budynki)
    
completed_budynki = points_in_polygons(0, 20, 0, 20)   

Answer

You can slice the dataframe then iterate trough it

df2 = df[20:40]

for index, row in df2.iterrows():
    print(row) 

Leave a Reply

Your email address will not be published. Required fields are marked *