update a dataframe row from another row in python

To update a DataFrame row from another row in Python, you can use the pandas DataFrame .update() method or numpy where.

Here's an example using the .update() method:

main.py
import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'Name': ['John', 'Sarah', 'Peter', 'Kelly'],
                    'Age': [25, 29, 31, 28],
                    'Salary': [50000, 60000, 70000, 80000]})

# print the original DataFrame
print(df)

# create a new row with updated information
new_row = {'Name': 'Peter', 'Age': 32, 'Salary': 75000}

# update the DataFrame using the .update() method
df.update(pd.DataFrame(new_row, index=[2]))

# print the updated DataFrame
print(df)
498 chars
19 lines

And here's an example using numpy.where:

main.py
import pandas as pd
import numpy as np

# create a sample DataFrame
df = pd.DataFrame({'Name': ['John', 'Sarah', 'Peter', 'Kelly'],
                    'Age': [25, 29, 31, 28],
                    'Salary': [50000, 60000, 70000, 80000]})

# print the original DataFrame
print(df)

# create a row with updated information
updated_row = {'Age': 32, 'Salary': 75000}

# use numpy.where to update the row in the DataFrame
df.loc[np.where(df['Name'] == 'Peter')] = pd.Series(updated_row)

# print the updated DataFrame
print(df)
524 chars
20 lines

gistlibby LogSnag