1

Here a sample code to get an object list:

import numpy as np

class simpleobj():

    def __init__(self,name):
        self.attr1 = name
        self.attr2 = f"{name}_{np.random.randint(1,100)}"
        self.x= np.random.randint(1,100,size=(100,1))
        self.y1= np.random.randint(1,100,size=(100,1))
        self.y2= np.random.randint(1,100,size=(100,1))

objectlist=[simpleobj(i) for i in list('SAMPLETHINGTOWIRTENOIDEA') ]

I want to convert these list of object into a mi-dataframe. I've always end up with nested arrays in the dataframe... how to reach a multiindexed dataframe like this:

|----indexes----|
attr1 | attr2 | x | y1 | y2
'S' | 'S50' | 1 | 4 | 3
'S' | 'S50' | 2 | 5 |10

1 Answer 1

1

You can use __dict__ method to pull out attributes of object like this, and then you set multi-index.

import pandas as pd
df = pd.DataFrame([obj.__dict__ for obj in objectlist]).set_index(['attr1', 'attr2'])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply. I also tried this solution. But I failed to use x as an index too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.