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

Zipping dictionary to pandas

I am trying to zip my dictionary into a panda’s data frame, and do it by the keys that are in the dictionary and not manually:

import pandas as pd

dict = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
columns = list(dict.keys())   # ['A', 'B']
manual_results = list(zip(dict['A'], dict['B'])) #  [('a1', 'b1'), ('a2', 'b2'), ('a3', 'b3')]
df = pd.DataFrame(manual_results, columns=columns)

I wish to create the results without the need to explicitly write the name of each key (dict[‘A’], dict[‘B’] etc). Any Ideas?

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 :

There is no need to zip it. Pandas can create a dataframe directly from a dict:

import pandas as pd
d = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
df = pd.DataFrame.from_dict(d)
print(df)
    A   B
0  a1  b1
1  a2  b2
2  a3  b3

reference: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html


Note: You can also orient it the other way (so the dict keys become the row index instead of colums) …

import pandas as pd
d = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
df = pd.DataFrame.from_dict(d,orient='index')
print(df)
    0   1   2
A  a1  a2  a3
B  b1  b2  b3
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