Python Forum
newbie: loop, modify dataframe cells - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: newbie: loop, modify dataframe cells (/thread-24757.html)



newbie: loop, modify dataframe cells - expat_th - Mar-03-2020

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.


RE: newbie: loop, modify dataframe cells - Larz60+ - Mar-03-2020

Here's a quickie bare bones tutorial: https://pandas.pydata.org/pandas-docs/stable/getting_started/10


RE: newbie: loop, modify dataframe cells - expat_th - Mar-03-2020

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.


RE: newbie: loop, modify dataframe cells - perfringo - Mar-03-2020

What is wrong with simple .apply? Something like:

>>> df[“colname”] = df[“colname”].apply(do_your_magic_here)



RE: newbie: loop, modify dataframe cells - Larz60+ - Mar-03-2020

corrected link: https://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html


RE: newbie: loop, modify dataframe cells - jefsummers - Mar-03-2020

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