Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign multiple column in one go with dictionary values?

I have a pandas dataframe and a function that returns a dictionary. I want to assign the result of the function to multiple columns. But the problem is, the function returns a dictionary that I want to save only the values to columns. I can do this by sending only the values from the function. However, I want to solve if from the recipient side.

Example code:

import pandas as pd

data = {
  "col1": [420, 380, 390],
  "col2": [50, 40, 45]
}

#load data into a DataFrame object:
df = pd.DataFrame(data)

The following function returns a dictionary. ( Can solve by returning return fun_dict.values(), but I want to send the dictionary and solve it from the calling side)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def fun_function(my_input):
    fun_dict = {}
    
    fun_dict["num1"] = str(my_input)[0]
    fun_dict["num2"]  = str(my_input)[1]
    
    return fun_dict

Driving side/recipient side:

df["first_num_col"], df["last_num_col"] = zip(*df["col2"].map(fun_function))

With this code, I only get the key values, under each column. Any help/suggestion is appreciated. Thank you.

>Solution :

The only way I can think of is to do d.values() in the client side:

df["first_num_col"], df["last_num_col"] = zip(*[d.values() for d in df["col2"].map(fun_function)])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading