Ako želite napraviti petlju preko DataFramea za izvođenje nekih operacija na svakom retku, tada možete koristiti funkciju iterrows() u Pandas.
Pande koriste tri funkcije za ponavljanje redaka DataFramea, tj. iterrows(), iteritems() i itertuples().
Ponavljaj retke s Pandas iterrows:
Iterrows () je odgovoran za prolazak kroz svaki red DataFramea. Vraća iterator koji sadrži indeks i podatke svakog retka kao serije.
Imamo sljedeću funkciju da vidimo sadržaj iteratora.
Ova funkcija vraća svaku vrijednost indeksa zajedno s nizom koji sadrži podatke u svakom retku.
Prinosi:
Primjer1
import pandas as pd import numpy as np info = pd.DataFrame(np.random.randn(4,2),columns = ['col1','col2']) for row_index,row in info.iterrows(): print (row_index,row)
Izlaz
0 name John degree B.Tech score 90 Name: 0, dtype: object 1 name Smith degree B.Com score 40 Name: 1, dtype: object 2 name Alexander degree M.Com score 80 Name: 2, dtype: object 3 name William degree M.Tech score 98 Name: 3, dtype: object
Primjer2
# importing pandas module import pandas as pd # making data frame from csv file data = pd.read_csv('aa.csv') for i, j in data.iterrows(): print(i, j) print()
Izlaz
0 Name Hire Date Salary Leaves Remaining 0 John Idle 03/15/14 50... Name: 0, dtype: object 1 Name Hire Date Salary Leaves Remaining 1 Smith Gilliam 06/01/15 65000... Name: 1, dtype: object 2 Name Hire Date Salary Leaves Remaining 2 Parker Chapman 05/12/14 45000.0 ... Name: 2, dtype: object 3 Name Hire Date Salary Leaves Remaining 3 Jones Palin 11/01/13 700... Name: 3, dtype: object 4 Name Hire Date Salary Leaves Remaining 4 Terry Gilliam 08/12/14 4800... Name: 4, dtype: object 5 Name Hire Date Salary Leaves Remaining 5 Michael Palin 05/23/13 66000... Name: 5, dtype: object