Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a panda's dataframe out of a single variable that contains a dict

I am trying to get dataFrame from this function :

def total_sum(self):
    c = defaultdict(int)
    for slot in self.data:
        c[slot['accountLabelType']] += slot['totalPrice']
    return(c)

it returns a variable that contains a whole dict with a key:value structure.

When I try to create the panda's dataframe like this :

def source_revenue(self):
        # df = pandas.DataFrame(self.data, columns=[
                            #   'Source Of Business', 'Revenue'])
        df = pandas.DataFrame({'CASH' : self.data})
        print(df)

I get this :

                                  CASH
BYD - Other                      500.0
BYD - Retail                    1584.0

But i want it to be like :

SOURCE                            CASH
BYD - Other                      500.0
BYD - Retail                    1584.0

But I can't do df = pandas.DataFrame({'SOURCE : self.data[0]'CASH' : self.data[1})

Because it is a dictionary, how do I properly extract both values so I can create the dataframe ?

sample output dictionary :

defaultdict(<class 'int'>, {'Spa': 3052, 'GS - Retail': 386, 'SCH Beverage - A La Carte': 119, 'BYD - Retail': 1584, 'BYD - Transport': 42498, 'BYD - Other': 500, 'BYD Food - Catering Banquet': 53796, 'Orchard Retail': 130, 'SCH - Retail': 375.4, 'SCH - Transport': 888, 'BYD Food - A La Carte 瓦厂食品-零点': 68365, 'XLM Beverage - A La Carte': 38, 'GS Food - A La Carte': 48, 'BYD Rooms 瓦厂房间': 5148, 'BYD Beverage - A La Carte': 39401.5, 'SCH - Food - A La Carte': 96})
like image 639
xavier Avatar asked Oct 26 '25 07:10

xavier


1 Answers

You could just put your dictionary into a list:

import pandas as pd
some_dict = {'a': 1, 'b': 2, 'c': 11, 'd': 66}  
df = pd.DataFrame([some_dict])
like image 52
sehan2 Avatar answered Oct 27 '25 21:10

sehan2