Iterate Through Rows of pandas DataFrame (4 Examples) | for Loop Over Row | iterrows & itertuples

preview_player
Показать описание
Python code of this video:

import pandas as pd # Load pandas

data = pd.DataFrame({'x1':range(1, 5), # Create pandas DataFrame
'x2':['a', 'b', 'c', 'd']})
print(data) # Print pandas DataFrame

print('Index', i, '; x1 =', row['x1'], ';', 'x2 =', row['x2'])
# Index 0 ; x1 = 1 ; x2 = a
# Index 1 ; x1 = 2 ; x2 = b
# Index 2 ; x1 = 3 ; x2 = c
# Index 3 ; x1 = 4 ; x2 = d

print(row['x1'] * 5)
# 5
# 10
# 15
# 20

my_list = [] # Create empty list
print(my_list) # Print list
# []

my_list = my_list + [row['x1'] * 10]

print(my_list) # Print updated list
# [10, 20, 30, 40]

print('Index', i, '; x1 =', row.x1, ';', 'x2 =', row.x2)
# Index 3 ; x1 = 1 ; x2 = a
# Index 3 ; x1 = 2 ; x2 = b
# Index 3 ; x1 = 3 ; x2 = c
# Index 3 ; x1 = 4 ; x2 = d

Follow me on Social Media:

Рекомендации по теме
Комментарии
Автор

What if I want to do a nested for loop that starts with the index of the higher for loop?

sidc.