Skip to content

Instantly share code, notes, and snippets.

@krisbolton
Last active March 9, 2024 19:26
Show Gist options
  • Save krisbolton/b406aff18195102dda2df5663fe6cf85 to your computer and use it in GitHub Desktop.
Save krisbolton/b406aff18195102dda2df5663fe6cf85 to your computer and use it in GitHub Desktop.
How to iterate and update pandas dataframe row by row

Problem

I want to iterate over a single column in a pandas dataframe and update cells in that column one by one. In my use-case I want user input to provide the update input.

New solution accesses cells directly reducing performance hit and avoiding potential side effects of iterrows().

New Solution

for index, row in df['Col'].items():
    user_input = input("Enter value: ".format(index))
    df.at[index, 'Col'] = user_input

Original Solution

for i, row in df.iterrows():
    user_input = input('Enter value: ')
    df.at[i, 'user_input'] = user_input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment