Knowledge is the Only Good
  • About

Effective Python: Introspection with Pandas

programming
Python
effective python
Author

Stephen J. Mildenhall

Published

2022-02-15

Modified

2024-02-26

This code defines a function that extracts all an objects properties into a pandas dataframe. It is created as a row so that each column can have the appropriate datatype. This function is part of great2.

import pandas as pd

def rinfo(ob):
    """
    generically export all reasonable data from ob
    store in DataFrame as a ROW and set reasonable data types

    accesses non-callable items only

    :param ob:
    :param index_attribute:
    :param timestamp: add a timestamp column
    """
    d = {}
    for i in dir(ob):
        if i[0] != '_':
            try:
                a = getattr(ob, i, None)
                if a is not None and not callable(a):
                    d[i] = [a]
            except Exception as e:
                d[i] = 'ERROR:' + str(type(e))
    index = str(type(ob))
    df = pd.DataFrame(d, index=[index])
    df.index.name = 'id'
    return df

# make a dummy object
x = type('myClass', (), {})
x.a = 10
x.b = 'A string'
x.c = float.as_integer_ratio
x.d = range(5)

print(rinfo(x).T)
id   <class 'type'>
a                10
b          A string
d   (0, 1, 2, 3, 4)

Stephen J. Mildenhall. License: CC BY-SA 2.0.

 

Website made with Quarto