0

I have a dataframe:

Name   Fruit    Fruit-Low   Fruit-High
Joe    Apple     8.12       8.74
Joe    Pear      3.54       6.24
Jess   Orange    5.36       8.24
Jess   Apple     5.45       8.44

I am trying to convert the dataframe into a specific dictionary format such as:

dictionary = {Joe: {Apple: (8.12, 8.74), Pear: (3.54, 6.24)}, Jess: {Orange: (5.36, 8.24), Apple: (5.45, 8.44)}}

Is there a pay to specify this format when converting the dataframe? I have tried the to_dict() command but continue to not be able to bring in all the rows as I am trying.

Any help would be greatly appreciated! Thanks in advance.

2 Answers2

0

Perhaps this Stack Overflow thread could help. Your main directions should DataFrame.to_dict documentation

snatchysquid
  • 1,283
  • 9
  • 24
  • I looked into this however I was having trouble being able to remove the column names from the dictionary. For example my output includes Fruit, Fruit-Low, and Fruit-High in the dictionary, when I just want to values if that makes sense? – Joseph Markiewicz May 31 '20 at 22:23
0

I think a possible solution would be something like this, although I'm sure it's not the pandorable way. of solving this:

def to_dict(df):
    result = {}
    for index, row in df.iterrows():
        entry = result.get(row['Name'])
        if entry == None:
            entry = {}
        entry[row['Fruit']] = (row['Fruit-Low'], row['Fruit-High'])
    return result

This assumes that each fruit is unique per name. If that assumption is wrong, the solution would overwrite the previous entry.

Benjamin Eckardt
  • 709
  • 6
  • 10