Iterating over a DataFrame to access and process each row
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'Column1': [1, 2, 3], 'Column2': ['A', 'B', 'C']})
# Iterate over the DataFrame
for index, row in df.iterrows():
column1_value = row['Column1']
column2_value = row['Column2']
print(f"Row {index}: Column1={column1_value}, Column2={column2_value}")
output:
To iterate over a DataFrame and add values to a specific column, you can use the iterrows()
function in pandas.
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'Column1': [1, 2, 3], 'Column2': ['A', 'B', 'C']})
# Iterate over the DataFrame and add values to a column
for index, row in df.iterrows():
new_value = row['Column1'] + 10
df.at[index, 'Column1'] = new_value
print(df)
output: