Skip to content

Instantly share code, notes, and snippets.

View Finndersen's full-sized avatar

Finn Andersen Finndersen

View GitHub Profile
@Finndersen
Finndersen / polymorphic_related_queryset.py
Last active August 29, 2023 12:53
PolymorphicRelatedQuerySet which allows select_related() to return polymorphic child models instead of base model
@Finndersen
Finndersen / vector.py
Last active January 17, 2023 17:38
Example Coordinate class for Pandas Extension Types article
from functools import total_ordering
from math import sqrt
@total_ordering
class Vector(object):
"""
Simple class to represent a 2D vector with X and Y components.
Could extend with more useful methods etc
"""
def __init__(self, x, y):
@Finndersen
Finndersen / VectorDtype.py
Created December 30, 2022 20:52
VectorDtype definition for Pandas Extension Types example
import numpy as np
import pandas as pd
from pandas.core.dtypes.dtypes import PandasExtensionDtype
from pandas.api.extensions import ExtensionArray, ExtensionScalarOpsMixin, register_extension_dtype
@register_extension_dtype
class VectorDtype(PandasExtensionDtype):
"""
Class to describe the custom Vector data type
"""
@Finndersen
Finndersen / VectorArray.py
Last active January 17, 2023 17:46
Definition of VectorArray for Pandas Extension Types example
class VectorArray(ExtensionScalarOpsMixin, ExtensionArray):
"""
Custom Extension Array type for an array of Vectors
Needs to define:
- Associated Dtype it is used with
- How to construct array from sequence of scalars
- How data is stored and accessed
- Any custom array methods
"""