'Convert lists of model objects to pandas dataframe based on the values of each object

I have a number of lists of objects of this class:

from typing import List,Optional
from pydantic import BaseModel

class Concept(BaseModel):
  text: str
  type: str

class ClassObject(BaseModel):
  question_text: str
  question_entity: Optional[List[Concept]]
  answer_text: str
  answer_entity: Optional[List[Concept]]

The lists:

answers1 = [
ClassObject(question_text='Question 1', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 1', answer_entity=[Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')]),
ClassObject(question_text='Question 2', question_entity=[], answer_text=' ', answer_entity=[]),
ClassObject(question_text='Question 3', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 3', answer_entity=[])
]

 answers2 = [
ClassObject(question_text='Question 1', question_entity=[], answer_text='Answer 1', answer_entity=[Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')]),
ClassObject(question_text='Question 2', question_entity=[], answer_text='Answer 2', answer_entity=[]),
ClassObject(question_text='Question 3', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 3', answer_entity=[Concept(text='Concept 1',type='Type 1')])
]

I would like to convert this to a pandas dataframe by taking the values from question_text as columns and the answer_entity as row value. Example for column 1 with column name question_text= 'Question 1'

  Question 1                                                                   
0 Concept(text='Concept 2',type='Type 1')  
1 Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')  

Any idea on how to achieve this? I have tried playing with the DataFrame function but it doesn't cover my question.

 df = pd.DataFrame([t.__dict__ for t in answers1])


Solution 1:[1]

Is it what you expect:

df = pd.json_normalize({t.question_text: t.answer_entity for t in answers1})
print(df)

# Output
                                          Question 1 Question 2 Question 3
0  [text='Concept 2' type='Type 1', text='Concept...         []         []

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corralien