For both viewing and modifying values, I would use iterrows()
. In a for loop and by using tuple unpacking (see the example: i, row
), I use the row
for only viewing the value and use i
with the loc
method when I want to modify values. As stated in previous answers, here you should not modify something you are iterating over.
for i, row in df.iterrows():
df_column_A = df.loc[i, 'A']
if row['A']df_column_A == 'Old_Value':
df.loc[i,'A']df_column_A = 'New_value'
Here the row
in the loop is a copy of that row, and not a view of it. Therefore, you should NOT write something like row['A'] = 'New_Value'
, it will not modify the DataFrame. However, you can use i
and loc
and specify the DataFrame to do the work.