1

I have the following array of dicts, and I create a Pandas dataframe out of it:

original_data = [
    {'group': 'group1', 'value': 100}, 
    {'group': 'group1', 'value': 25}, 
    {'group': 'group2', 'value': 77}, 
    {'group': 'group2', 'value': 123}, 
    {'group': 'group3', 'value': 44}
]

df = pd.DataFrame(original_data)

This is the resulting dataframe:

group  value
0  group1    100
1  group1     25
2  group2     77
3  group2    123
4  group3     44

The problem is when I try to get the original dict out of the dataset using to_dict(), because I get a completely different object:

df.to_dict()
{'group': {0: 'group1', 1: 'group1', 2: 'group2', 3: 'group2', 4: 'group3'}, 'value': {0: 100, 1: 25, 2: 77, 3: 123, 4: 44}}

How can I get the original dict used to construct the dataframe?

Thanks for your help.

1 Answer 1

1

Try orient='records':

df.to_dict(orient='records')

Output:

[{'group': 'group1', 'value': 100},
 {'group': 'group1', 'value': 25},
 {'group': 'group2', 'value': 77},
 {'group': 'group2', 'value': 123},
 {'group': 'group3', 'value': 44}]
Sign up to request clarification or add additional context in comments.

Comments

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.