Aran Freel
Aran Freel

Reputation: 3215

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 :)

Upvotes: 5

Views: 6679

Answers (2)

Aran Freel
Aran Freel

Reputation: 3215

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)

Upvotes: 5

skynet1010
skynet1010

Reputation: 191

The above answer with correct indent

def update_row_with_dict(df,d,idx):
    for key in d.keys():
        df.loc[idx, key] = d.get(key)

more short would be

def update_row_with_dict(df,d,idx):
    df.loc[idx,d.keys()] = d.values()

for your code snipped the syntax would be:

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

for idx in dataframe.index:
    y = {'a':1,'b':2,'c':3}
    update_row_with_dict(dataframe,y,idx)

Upvotes: 3

Related Questions