Skip to content

Latest commit

 

History

History
81 lines (56 loc) · 2.37 KB

Pandas_Looping_Over_Dataframe.md

File metadata and controls

81 lines (56 loc) · 2.37 KB



Template request | Bug report | Generate Data Product

Tags: #pandas #python #loops #dataframes #forloop #loop #snippet #operations

Author: Oketunji Oludolapo

Description: This notebook provides an overview of multiples ways to use loops to iterate over a dataframe.

References:

Input

Import libraries

import pandas as pd
import numpy as np

Model

Create Sample Dataframe

dict1 = {
    "student_id": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    "student_name": [
        "Peter",
        "Dolly",
        "Maggie",
        "David",
        "Isabelle",
        "Harry",
        "Akin",
        "Abbey",
        "Victoria",
        "Sam",
    ],
    "student_course": np.random.choice(["Biology", "Physics", "Chemistry"], size=10),
}
df = pd.DataFrame(dict1)
df

Output

Looping over the data to get the column name

for column in df:
    print(column)

Looping over the data to view the columns and their values sequentially

for k, v in df.iteritems():
    print(k, v)

Looping over dataframes to get the information about a row with respect to its columns

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

Looping over dataframes to view the data per row as a tuple with the column values

for row in df.itertuples():
    print(row)