iterate over pandas df in python

You can iterate over rows and columns of DataFrame using for loop and iterrows() or iteritems() functions of pandas library in Python. Here is an example code snippet that demonstrates how to iterate over rows and columns of a Pandas DataFrame.

main.py
import pandas as pd

#creating a sample dataframe
df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6], 'C':[7,8,9]})

#printing the dataframe
print(df)

#iterating over rows using iterrows() function
for index, row in df.iterrows():
    print(row['A'], row['B'], row['C'])

#iterating over columns using iteritems() function
for col_label, column in df.iteritems():
    print(col_label)
    print(column)
399 chars
17 lines

Output:

main.py
   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9
1 4 7
2 5 8
3 6 9
A
0    1
1    2
2    3
Name: A, dtype: int64
B
0    4
1    5
2    6
Name: B, dtype: int64
C
0    7
1    8
2    9
Name: C, dtype: int64
197 chars
23 lines

related categories

gistlibby LogSnag