how to iterate rows in dataframe and at the same time change value
Jump to turn (6)
- User
how to iterate rows in dataframe and at the same time change value
- Assistant
Here's an example of how to iterate rows in a dataframe and at the same time change value.
codeimport pandas as pd # create a sample dataframe df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # iterate over rows for index, row in df.iterrows(): # change the value of column 'A' to '10' df.at[index, 'A'] = 10 # print the updated dataframe print(df)Output:
codeA B 0 10 4 1 10 5 2 10 6In the above example, we first create a sample dataframe with two columns 'A' and 'B'. We then iterate over the rows using the
iterrows()method of the dataframe. For each row, we use the method to change the value of column 'A' to '10'. Finally, we print the updated dataframe.