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

Getting data from Excel in python using pandas in dictionary format

I Have a Excel Data Like This

  Category  Item
  old       apple
  new       mango
  old       grape
  new       ginger

I need to get that data in python using pandas in the dictionary format like –

{'old': ['apple', 'grape'], 'new': ['mango', ginger']}

From one of the references from stack overflow They provide code like this

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

import pandas as pd

df = pd.read_excel("Skills.xlsx", index_col=0)
df = df.where(pd.notnull(df), None)

print(df.to_dict())

I am getting like output like

{'Skills': {'old': 'grape', 'new': 'ginger'}}

But I need the output like this

{'Skills': {'old': ['apple', 'grape'], 'new': ['mango', ginger']}}

>Solution :

You can use apply function after groupby.

df
    Category      Item
0          old   apple
1          new   mango
2          old   grape
3          new  ginger
df.groupby('Category')['Item'].apply(list).to_dict()
{'new': ['mango', 'ginger'], 'old': ['apple', 'grape']}
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