Pydantic to pandas

Converting Pydantic Models to Pandas DataFrames

Pydantic is a powerful library in Python for data validation and parsing. On the other hand, pandas is a popular library for data manipulation and analysis. In this example, we will explore how to convert Pydantic models to pandas DataFrames.

Step 1: Define a Pydantic Model

First, let’s define a simple Pydantic model to work with. For example, we’ll create a model called Person with two fields: name and age.


  from pydantic import BaseModel
  
  class Person(BaseModel):
      name: str
      age: int
  

Step 2: Create Pydantic Instances

Next, we can create instances of the Pydantic model to represent our data. For instance, let’s create three instances:


  person1 = Person(name="John", age=30)
  person2 = Person(name="Alice", age=25)
  person3 = Person(name="Bob", age=35)
  

Step 3: Convert Pydantic Instances to Pandas DataFrames

Now, we can convert these Pydantic instances to pandas DataFrames. We can achieve this by leveraging the dict() method provided by Pydantic and passing the resulting dictionaries to the pandas.DataFrame() constructor.


  import pandas as pd
  
  data = [person1.dict(), person2.dict(), person3.dict()]
  df = pd.DataFrame(data)
  print(df)
  

The resulting output will be:


      name  age
  0   John   30
  1  Alice   25
  2    Bob   35
  

As you can see, we have successfully converted the Pydantic instances to a pandas DataFrame.

Leave a comment