Search code examples
python-3.xpandasdictionary

Python Pandas - Update row with dictionary based on index, column


I have a dataframe with empty columns and a corresponding dictionary which I would like to update the empty columns with based on index, column:

import pandas as pd    
import numpy as np

dataframe = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 6, 2], [3, 4, 1]])
dataframe.columns = ['x', 'y', 'z']
additional_cols = ['a', 'b', 'c']

for col in additional_cols:
     dataframe[col] = np.nan

    x   y   z   a  b  c
0   1   2   3           
1   4   5   6           
2   7   8   9           
3   4   6   2           
4   3   4   1           

for row, column in x.iterrows():
    #caluclations to return dictionary y
    y = {"a": 5, "b": 6, "c": 7}
    df.loc[row, :].map(y)

Basically after performing the calculations using columns x, y, z I would like to update columns a, b, c for that same row :)


Solution

  • I could use a function as such but as far as the pandas library and a method for the DataFrame object I am not sure:

    def update_row_with_dict(dictionary, dataframe, index):  
        for key in dictionary.keys():  
            dataframe.loc[index, key] = dictionary.get(key)