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

Create a custom column in a dict format

I currently have a dataframe like this

Person Analysis Dexterity Skills
174 3.76 4.12 1.20
239 4.10 3.78 3.77
557 5.00 2.00 4.40
674 2.23 2.40 2.80
122 3.33 4.80 4.10

I want to add an column to compile all this information like below

Person Analysis Dexterity Skills new_column
174 3.76 4.12 1.20 {"Analysis":"3.76", "Dexterity":"4.12", "Skills":"1.20"}
239 4.10 3.78 3.77 {"Analysis":"4.10", "Dexterity":"3.78", "Skills":"3.77"}
557 5.00 2.00 4.40 {"Analysis":"5.00", "Dexterity":"2.00", "Skills":"4.40"}
674 2.23 2.40 2.80 {"Analysis":"2.23", "Dexterity":"2.40", "Skills":"2.80"}
122 3.33 4.80 4.10 {"Analysis":"3.33", "Dexterity":"4.80", "Skills":"4.10"}

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

>Solution :

You can use to to_dict method like so:

import pandas as pd

rows = [
    {'a': 1, 'b': 2},
    {'a': 3, 'b': 4},
]

df = pd.DataFrame(rows)

# define new column as the json format of another
# also convert to str as that is what you have in your output
df['c'] = df[['a', 'b']].astype(str).to_dict(orient='records')

to_dict has a really nice interface for transforming to JSON format or to other object types. In this instance you are looking for orient='records' which is a dictionary of keys.

In your case, you will use:

df['new_column'] = df[
    ['Analysis', 'Dexterity', 'Skills']
].astype(str).to_dict(orient='records')
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