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

Get dictionary from a dataframe

I have a dataframe like below:

df = pd.DataFrame({
'Aapl': [12, 5, 8],
'Fs': [18, 12, 8],
'Bmw': [6, 18, 12],
'Year': ['2020', '2025', '2030']

})

I want a dictionary like:

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

d={'2020':[12,18,16],
   '2025':[5,12,18],
   '2030':[8,8,12]
  }

I am not able to develop the whole logic:

lst = [list(item.values()) for item in df.to_dict().values()]
dic={}
for items in lst:
    for i in items[-1]:
        dic[i]=#2000 will hold all the 0th values of other lists and so on 

Is there any easier way using pandas ?

>Solution :

Convert Year to index, transpose and then in dict comprehension create lists:

d = {k: list(v) for k, v in df.set_index('Year').T.items()}
print (d)
{'2020': [12, 18, 6], '2025': [5, 12, 18], '2030': [8, 8, 12]}
        

Or use DataFrame.agg:

d = df.set_index('Year').agg(list, axis=1).to_dict()
print (d)
{'2020': [12, 18, 6], '2025': [5, 12, 18], '2030': [8, 8, 12]}
    
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