5

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

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

this works, but it is amazingly slow, 5ms++ on my 4.0GHz box. Does anyone have any better way?
3

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)

2 Comments

df.loc[idx,d.keys()] = d.values() sets all the columns matching keys to some tuple/iterable containing all the values.
df.loc[idx,d.keys()] = tuple(d.values()) will give the right hint to pandas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.