loop on dataframe lines python 1

loop on dataframe lines python

for index, row in df.iterrows():
    print(f'Index: {index}, row: {row.values}')

for index, row in df.iterrows():
    print(f'Index: {index}, column_a: {row.get("column_a", 0)}')

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

# But !
# The .apply() function provides a more efficient
# method for updating a DataFrame.
# see : https://towardsdatascience.com/pandas-apply-for-power-users-f44d0e0025ce

Here is what the above code is Doing:
1. We create a new column called ‘new_column’
2. We iterate over each row in the DataFrame
3. We get the value of the ‘column_a’ column
4. We add the value of the ‘column_a’ column to the value of the ‘column_b’ column
5. We assign the result to the ‘new_column’ column

Similar Posts