Home > Back-end >  How to save a Dictionary inside a Pandas DataFrame?
How to save a Dictionary inside a Pandas DataFrame?

Time:10-25

Context

I have a Pandas DataFrame and a Use Case, where I need to store a Collection (Dictionary) in of the Columns. I do know, that a DataFrame is probably not designed for this, however, I am looking for a simple solution without Relationships between multiple DataFrames, Series, etc.

I am currently getting the following Error:

ValueError: Length of values (3) does not match length of index (5)


Code

procedures = {'A': 'Procedure A', 'B': 'Procedure B', 'C': 'Procedure C'}

# I would like to create a new Column 'Procedures' and assign the Dictionary above to it for every Row.
data['Procedures'] = procedures

Question

  • Is this possible with Pandas and how can I achieve it?

CodePudding user response:

Repeat list of dict by multiple by length of DataFrame:

data['Procedures'] = [procedures] * len(data)

CodePudding user response:

To save a Dictionary inside a Pandas DataFrame use the pd.DataFrame.from_dict().

If you think it's not clear refer this link:

enter link description here

  • Related