Skip to content

Latest commit

 

History

History
88 lines (60 loc) · 2.4 KB

Python_Looping_Over_Dataframe.md

File metadata and controls

88 lines (60 loc) · 2.4 KB



Template request | Bug report | Generate Data Product

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

Author: Oketunji Oludolapo

Description: This notebook provides an overview of how to use loops to iterate over a dataframe in Python.

Input

Import Library

import pandas as pd
import numpy as np

Model

Loopring over dataframes can be a a lifesaver when there are lots of columns and we want to view our data at a go. This is an advntage of for loop in a dataframe.

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),
}
data = pd.DataFrame(dict1)
data

Output

Looping over the data to get the column name

for column in data:
    print(column)

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

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

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

for k, v in data.iterrows():
    print(k)
    print(v)

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

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