Skip to content

Example Scripts: Read JSON and CSV data with Polars and databpy #3

Description

@kolibril13

For reference, here are two scripts to load data into Blender spreadsheets using polars.
My plan is to incorporate them into https://extensions.blender.org/add-ons/csv-importer/ next month, together with databpy.

Read JSON

import polars as pl
import databpy as db
from io import StringIO
import numpy as np


# Example JSON data
json_file = StringIO(
    """
    {
    "Star": [
        [58.2136, 91.8819, 0.0],
        [58.1961, 92.215, 0.0]
    ],
    "Is_Visible": [[true], [false]],
    "Intensity": [[10], [20]]
    }
"""
)

# here's how you'd load a custom json file
# import pathlib as Pathlib 
# json_file = Pathlib.cwd() / "data.json"

df = pl.read_json(json_file)
columns_to_explode = [col for col in df.columns if df[col].dtype == pl.List(pl.List)]
df = df.explode(columns_to_explode)

vertices = np.zeros((len(df), 3), dtype=np.float32)
bob = db.create_bob(vertices, name="Hello JSON")

for col in df.columns:
    data = np.vstack(df.get_column(col).to_numpy())
    bob.store_named_attribute(data, col)

print(bob.named_attribute("Star"))
print(bob.named_attribute("Is_Visible"))
print(bob.named_attribute("Intensity"))
image

Read CSV

import polars as pl
import databpy as db
from io import StringIO
import numpy as np

csv_data = StringIO(
    """MyFloat,Is_Visible,Intensity
42.12,true,10
12.33,false,20
"""
)

# here's how you'd load a custom csv file
# import pathlib as Pathlib
# json_file = Pathlib.cwd() / "data.csv"


df = pl.read_csv(csv_data)

# Since we no longer have nested arrays as in read_json, there's no need to explode columns
vertices = np.zeros((len(df), 3), dtype=np.float32)
bob = db.create_bob(vertices, name="Hello CSV")

# Store each column as an attribute
# Note: .to_numpy() returns a 1D array, so we reshape to 2D if needed.
for col in df.columns:
    data = df[col].to_numpy().reshape(-1, 1)
    bob.store_named_attribute(data, col)

# Print the stored attributes
print(bob.named_attribute("MyFloat"))
print(bob.named_attribute("Is_Visible"))
print(bob.named_attribute("Intensity"))
image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions