user1999109
user1999109

Reputation: 441

Pandas Dataframe/Python : How to update dataframe cell value using for loop at each iteration in python?

I have a pandas data frame with 2 columns(UserId,RandNo). In this UserId has the values for 10 rows as below

enter image description here

Now, I fill the RandNo column through for loop as below.

import pandas as pd
import random

df=pd.read_csv('df_sto.csv', skipinitialspace=True)

rand=0
for index, row in df.iterrows():
    try:
            rand=random.randint(0,100)

            df.at[index, 'RandNo'] = rand           
    except Exception as e:
        print(e)
df.to_csv("df_sto1.csv", sep=',')

Here, I get the updated value in df_sto1.csv file only, the updated value not affected in df_sto.csv.

If the data frame rows are large and if the for loop face any problem after 95% of rows are updated in df.iterrows(): for 'df_sto.csv' Then I want to repeat the process form 0% itself(from 0th row itself). To avoid this problem I want to update the data frame for 'df_sto.csv' each and every for loop iteration itself rather than to get updated value through df.to_csv("df_sto1.csv", sep=',')

Guide me to update the data frame cell value using for loop in each iteration itself. Thanks in advance.

Upvotes: 2

Views: 3798

Answers (1)

kerwei
kerwei

Reputation: 1842

I don't think the try block is necessary at all but if you insist on using it, perhaps the operations are more than just assigning random numbers, then how about wrapping it up in a function?

import pandas as pd
import random

df=pd.read_csv('df_sto.csv', skipinitialspace=True)
copy_df = df.copy()

def update_df(frame):
    for index, row in frame.iterrows():
        rand=random.randint(0,100)
        frame.at[index, 'RandNo'] = rand

    return frame


status = 0
while status == 0:
    try:
        copy_df = update_df(copy_df)
        status = 1
    except Exception as e:
        copy_df = df
        print(e)


df = copy_df
df.to_csv("df_sto1.csv", sep=',')

Upvotes: 1

Related Questions