Adding functionality so we can create dataframe from string representation of dict

In [2]:
import ast
def str_to_dict(string):
    return ast.literal_eval(string)

In [3]:
import pandas as pd

In [4]:
class MySubClass(pd.DataFrame):
    def from_str(self, string):
        df_obj = super().from_dict(str_to_dict(string))
        df_obj.my_string_attribute = string
        return df_obj

In [5]:
data = "{'col_1' : ['a','b'], 'col2': [1, 2]}"

In [7]:
obj = MySubClass().from_str(data)

In [8]:
type(obj)


Out[8]:
__main__.MySubClass

In [9]:
obj


Out[9]:
col2 col_1
0 1 a
1 2 b

In [10]:
obj.my_string_attribute


Out[10]:
"{'col_1' : ['a','b'], 'col2': [1, 2]}"

In [8]:
sales = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
         {'account': 'Alpha Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},
         {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]
df = MySubClass(sales)

In [9]:
df


Out[9]:
Feb Jan Mar account
0 200 150 140 Jones LLC
1 210 200 215 Alpha Co
2 90 50 95 Blue Inc

In [10]:
type(df)


Out[10]:
__main__.MySubClass

In [ ]: