Home > Software design >  Get dictionary from a dataframe
Get dictionary from a dataframe

Time:09-22

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:

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 ?

CodePudding user response:

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]}
    

CodePudding user response:

Try this:

import pandas as pd
data = {'Name': ['Ankit', 'Amit',
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce',
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
  
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age', 
                                 'Stream', 'Percentage'])
  • Related