0

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

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']}}
halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

2

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']}
Lazyer
  • 917
  • 1
  • 6
  • 16
  • Thanks, Lazyer For your answer it is working for me. If you don't mind can you send the document link where I can found that – Ramu Sompalli Oct 27 '22 at 09:25
  • 1
    I recommend looking at this [article](https://stackoverflow.com/questions/22219004/how-to-group-dataframe-rows-into-list-in-pandas-groupby)! – Lazyer Oct 27 '22 at 09:32