I have a Dataframe with Dates, Tickers and Close Some rows have the same dates
key= date value= ticker value close
import pandas as pd
data = {'Ticker': ['laptop', 'printer', 'tablet', 'desk', 'chair'],
'close': [1200, 150, 300, 450, 200]
}
df = pd.DataFrame(data, index=
['27/01/2022','27/01/2022','25/01/2022','24/01/2022','23/01/2022'])
df
Ticker close
27/01/2022 laptop 1200
27/01/2022 printer 150
25/01/2022 tablet 300
24/01/2022 desk 450
23/01/2022 chair 200
I'm trying to get a dictionary that looks like this
Key
27/01/2022 laptop : 1200, printer : 150
25/01/2022 tablet : 300
24/01/2022 desk 450
23/01/2022 chair 200
CodePudding user response:
As baileythegreen alludes to in a comment, your sample output isn't a valid dictionary. If you want the output
{'23/01/2022': {'chair': 200},
'24/01/2022': {'desk': 450},
'25/01/2022': {'tablet': 300},
'27/01/2022': {'laptop': 1200, 'printer': 150}}
you can do
{date: dict(zip(sub_df['Ticker'], sub_df['close']))
for date, sub_df in df.groupby(df.index)}