Python Forum

Full Version: newbie: loop, modify dataframe cells
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I really tried to do this myself for hours, and cannot get the hang of it. I simply want to loop through a dataframe, check the value in each cell and optionally modify it. In this case simplicity is more important than efficiency but it would be good to know the most efficient ways of doing it as well.

I can iterate through the dataframe in a number of ways but don't know how to select, inspect and modify the current cell. Also that modification may be based on the value of another cell in the same row so need to know how to find them as well.

Thank you.
Here's a quickie bare bones tutorial: https://pandas.pydata.org/pandas-docs/st...started/10
Thanks but first of all, that link is broken.

Then I've been through many tutorials, both text and video, and while found bits and pieces of what I want to do, none that pull them together. For example, many ways to loop/iterate through the dataframe, but only print the cell contents, not modify it. Or how to modify a specific cell, but not in the context of looping through them - only by selecting a specific one with .loc or another method. So basic introductions are not helpful to me.
What is wrong with simple .apply? Something like:

>>> df[“colname”] = df[“colname”].apply(do_your_magic_here)
This creates a dataframe, loops through and prints the values, and if the value is 6 it is modified to 100.
import pandas as pd
df = pd.DataFrame(({1,2,3},{4,5,6},{7,8,9}))
for row in range(3) :
    for col in range(3) :
        print(df.iloc[row,col])
        if df.iloc[row,col] == 6 :
            df.iloc[row,col] = 100
df