for loop dataframe code example
Example 1: iterate over rows dataframe
df = pd.DataFrame([{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}])
for index, row in df.iterrows():
print(row['c1'], row['c2'])
Example 2: creating data frame in python with for loop
df = pd.DataFrame(columns=["A", "B"])
for i in range(2):
this_column = df.columns[i]
df[this_column] = [i, i+1]
print(df)
#OUTPUT
# A B
#0 0 1
#1 1 2
Example 3: dataframe for loop
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'],
'Age': [21, 19, 20, 18],
'Stream': ['Math', 'Commerce', 'Arts', 'Biology'],
'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age', 'Stream', 'Percentage'])
print("Given Dataframe :\n", df)
print("\nIterating over rows using iterrows() method :\n")
# iterate through each row and select
# 'Name' and 'Age' column respectively.
for index, row in df.iterrows():
print (row["Name"], row["Age"])