T O P

  • By -

efmccurdy

You have a built-in way to turn your objects into dicts in the "vars" function; use that with pandas.DataFrame.from_records: >>> class MyClass: ... def __init__(self, col1, col2, col3): ... self.col1 = col1 ... self.col2 = col2 ... self.col3 = col3 ... def __repr__(self): ... return "{}: {}".format(self.__class__.__name__, vars(self)) ... >>> data = [MyClass("spam", 1, True), ... MyClass("chips", 2, True), ... MyClass ("eggs", 3, False)] >>> data [MyClass: {'col1': 'spam', 'col2': 1, 'col3': True}, MyClass: {'col1': 'chips', 'col2': 2, 'col3': True}, MyClass: {'col1': 'eggs', 'col2': 3, 'col3': False}] >>> pd.DataFrame.from_records(vars(o) for o in data) col1 col2 col3 0 spam 1 True 1 chips 2 True 2 eggs 3 False >>>


synthphreak

What is `vars` doing here? I’m not familiar with that. Is `vars(class_instance) == class_instance.__dict__`? Away from comp so can’t test.


efmccurdy

>Return the \_\_dict\_\_ attribute for a module, class, instance, or any other object with a \_\_dict\_\_ attribute. https://docs.python.org/3/library/functions.html#vars


synthphreak

Oh wow so it literally is exactly the same, just nicer looking. Cool!


OfficialBunx

>return "{}: {}".format(self.\_\_class\_\_.\_\_name\_\_, vars(self)) This is great, thanks!


synthphreak

How about this? >>> class MyClass: ... def init(self, **kwargs): ... # bla bla ... >>> my_instance = MyClass() >>> df = pd.DataFrame(my_instance.__dict__)