Search⌘ K
AI Features

Solution: Looping, Aggregation, and apply() Method

Explore techniques to manipulate pandas DataFrames by looping through rows and applying aggregation methods to calculate maximum and minimum values. Learn practical skills for effective data analysis and handling data in tabular form.

We'll cover the following...

Problem 1: Solution

Given the following dataset:

100 56 17
12 23 1
49 3 65
32 19 41
99 100 41

Create a DataFrame named df. Loop over each row and calculate the maximum and minimum values.

Python 3.10.4
import numpy as np
import pandas as pd
matrix = [(100, 56, 17),
(12, 23, 1),
(49, 3, 65),
(32, 19, 43),
(99, 100, 41)
]
# Create a DataFrame
df = pd.DataFrame(matrix, index = list('abcde'), columns = list('xyz'))
# iterate through each row and select
for i in range(len(df)):
print("max value in row", i,": ",max(df.iloc[i, 0], df.iloc[i,1], df.iloc[i, 2]))
print("min value in row", i,": ",min(df.iloc[i, 0], df.iloc[i,1], df.iloc[i, 2]))
...