Extending pandas#

While pandas provides a rich set of methods, containers, and data types, yourneeds may not be fully satisfied. pandas offers a few options for extendingpandas.

Registering custom accessors#

Libraries can use the decoratorspandas.api.extensions.register_dataframe_accessor(),pandas.api.extensions.register_series_accessor(), andpandas.api.extensions.register_index_accessor(), to add additional“namespaces” to pandas objects. All of these follow a similar convention: youdecorate a class, providing the name of attribute to add. The class’s__init__ method gets the object being decorated. For example:

@pd.api.extensions.register_dataframe_accessor("geo")classGeoAccessor:def__init__(self,pandas_obj):self._validate(pandas_obj)self._obj=pandas_obj@staticmethoddef_validate(obj):# verify there is a column latitude and a column longitudeif"latitude"notinobj.columnsor"longitude"notinobj.columns:raiseAttributeError("Must have 'latitude' and 'longitude'.")@propertydefcenter(self):# return the geographic center point of this DataFramelat=self._obj.latitudelon=self._obj.longitudereturn(float(lon.mean()),float(lat.mean()))defplot(self):# plot this array's data on a map, e.g., using Cartopypass

Now users can access your methods using thegeo namespace:

>>>ds=pd.DataFrame(...{"longitude":np.linspace(0,10),"latitude":np.linspace(0,20)}...)>>>ds.geo.center(5.0, 10.0)>>>ds.geo.plot()# plots data on a map

This can be a convenient way to extend pandas objects without subclassing them.If you write a custom accessor, make a pull request adding it to ourecosystem page.

We highly recommend validating the data in your accessor’s__init__.In ourGeoAccessor, we validate that the data contains the expected columns,raising anAttributeError when the validation fails.For aSeries accessor, you should validate thedtype if the accessorapplies only to certain dtypes.

Extension types#

Note

Thepandas.api.extensions.ExtensionDtype andpandas.api.extensions.ExtensionArray APIs wereexperimental prior to pandas 1.5. Starting with version 1.5, future changes will followthepandas deprecation policy.

pandas defines an interface for implementing data types and arrays thatextendNumPy’s type system. pandas itself uses the extension system for some typesthat aren’t built into NumPy (categorical, period, interval, datetime withtimezone).

Libraries can define a custom array and data type. When pandas encounters theseobjects, they will be handled properly (i.e. not converted to an ndarray ofobjects). Many methods likepandas.isna() will dispatch to the extensiontype’s implementation.

If you’re building a library that implements the interface, please publicize itonthe ecosystem page.

The interface consists of two classes.

ExtensionDtype#

Apandas.api.extensions.ExtensionDtype is similar to anumpy.dtype object. It describes thedata type. Implementers are responsible for a few unique items like the name.

One particularly important item is thetype property. This should be theclass that is the scalar type for your data. For example, if you were writing anextension array for IP Address data, this might beipaddress.IPv4Address.

See theextension dtype source for interface definition.

pandas.api.extensions.ExtensionDtype can be registered to pandas to allow creation via a string dtype name.This allows one to instantiateSeries and.astype() with a registered string name, forexample'category' is a registered string accessor for theCategoricalDtype.

See theextension dtype dtypes for more on how to register dtypes.

ExtensionArray#

This class provides all the array-like functionality. ExtensionArrays arelimited to 1 dimension. An ExtensionArray is linked to an ExtensionDtype via thedtype attribute.

pandas makes no restrictions on how an extension array is created via its__new__ or__init__, and puts no restrictions on how you store yourdata. We do require that your array be convertible to a NumPy array, even ifthis is relatively expensive (as it is forCategorical).

They may be backed by none, one, or many NumPy arrays. For example,pandas.Categorical is an extension array backed by two arrays,one for codes and one for categories. An array of IPv6 addresses maybe backed by a NumPy structured array with two fields, one for thelower 64 bits and one for the upper 64 bits. Or they may be backedby some other storage type, like Python lists.

See theextension array source for the interface definition. The docstringsand comments contain guidance for properly implementing the interface.

ExtensionArray operator support#

By default, there are no operators defined for the classExtensionArray.There are two approaches for providing operator support for your ExtensionArray:

  1. Define each of the operators on yourExtensionArray subclass.

  2. Use an operator implementation from pandas that depends on operators that are already definedon the underlying elements (scalars) of the ExtensionArray.

Note

Regardless of the approach, you may want to set__array_priority__if you want your implementation to be called when involved in binary operationswith NumPy arrays.

For the first approach, you define selected operators, e.g.,__add__,__le__, etc. thatyou want yourExtensionArray subclass to support.

The second approach assumes that the underlying elements (i.e., scalar type) of theExtensionArrayhave the individual operators already defined. In other words, if yourExtensionArraynamedMyExtensionArray is implemented so that each element is an instanceof the classMyExtensionElement, then if the operators are definedforMyExtensionElement, the second approach will automaticallydefine the operators forMyExtensionArray.

A mixin class,ExtensionScalarOpsMixin supports this secondapproach. If developing anExtensionArray subclass, for exampleMyExtensionArray,can simply includeExtensionScalarOpsMixin as a parent class ofMyExtensionArray,and then call the methods_add_arithmetic_ops() and/or_add_comparison_ops() to hook the operators intoyourMyExtensionArray class, as follows:

frompandas.api.extensionsimportExtensionArray,ExtensionScalarOpsMixinclassMyExtensionArray(ExtensionArray,ExtensionScalarOpsMixin):passMyExtensionArray._add_arithmetic_ops()MyExtensionArray._add_comparison_ops()

Note

Sincepandas automatically calls the underlying operator on eachelement one-by-one, this might not be as performant as implementing your ownversion of the associated operators directly on theExtensionArray.

For arithmetic operations, this implementation will try to reconstruct a newExtensionArray with the result of the element-wise operation. Whetheror not that succeeds depends on whether the operation returns a resultthat’s valid for theExtensionArray. If anExtensionArray cannotbe reconstructed, an ndarray containing the scalars returned instead.

For ease of implementation and consistency with operations between pandasand NumPy ndarrays, we recommendnot handling Series and Indexes in your binary ops.Instead, you should detect these cases and returnNotImplemented.When pandas encounters an operation likeop(Series,ExtensionArray), pandaswill

  1. unbox the array from theSeries (Series.array)

  2. callresult=op(values,ExtensionArray)

  3. re-box the result in aSeries

NumPy universal functions#

Series implements__array_ufunc__. As part of the implementation,pandas unboxes theExtensionArray from theSeries, applies the ufunc,and re-boxes it if necessary.

If applicable, we highly recommend that you implement__array_ufunc__ in yourextension array to avoid coercion to an ndarray. Seethe NumPy documentationfor an example.

As part of your implementation, we require that you defer to pandas when a pandascontainer (Series,DataFrame,Index) is detected ininputs.If any of those is present, you should returnNotImplemented. pandas will take care ofunboxing the array from the container and re-calling the ufunc with the unwrapped input.

Testing extension arrays#

We provide a test suite for ensuring that your extension arrays satisfy the expectedbehavior. To use the test suite, you must provide several pytest fixtures and inheritfrom the base test class. The required fixtures are found inpandas-dev/pandas.

To use a test, subclass it:

frompandas.tests.extensionimportbaseclassTestConstructors(base.BaseConstructorsTests):pass

Seepandas-dev/pandasfor a list of all the tests available.

Compatibility with Apache Arrow#

AnExtensionArray can support conversion to / frompyarrow arrays(and thus support for example serialization to the Parquet file format)by implementing two methods:ExtensionArray.__arrow_array__ andExtensionDtype.__from_arrow__.

TheExtensionArray.__arrow_array__ ensures thatpyarrow knowns howto convert the specific extension array into apyarrow.Array (also whenincluded as a column in a pandas DataFrame):

classMyExtensionArray(ExtensionArray):...def__arrow_array__(self,type=None):# convert the underlying array values to a pyarrow Arrayimportpyarrowreturnpyarrow.array(...,type=type)

TheExtensionDtype.__from_arrow__ method then controls the conversionback from pyarrow to a pandas ExtensionArray. This method receives a pyarrowArray orChunkedArray as only argument and is expected to return theappropriate pandasExtensionArray for this dtype and the passed values:

class ExtensionDtype:    ...    def __from_arrow__(self, array: pyarrow.Array/ChunkedArray) -> ExtensionArray:        ...

See more in theArrow documentation.

Those methods have been implemented for the nullable integer and string extensiondtypes included in pandas, and ensure roundtrip to pyarrow and the Parquet file format.

Subclassing pandas data structures#

Warning

There are some easier alternatives before considering subclassingpandas data structures.

  1. Extensible method chains withpipe

  2. Usecomposition. Seehere.

  3. Extending byregistering an accessor

  4. Extending byextension type

This section describes how to subclasspandas data structures to meet more specific needs. There are two points that need attention:

  1. Override constructor properties.

  2. Define original properties

Note

You can find a nice example ingeopandas project.

Override constructor properties#

Each data structure has severalconstructor properties for returning a newdata structure as the result of an operation. By overriding these properties,you can retain subclasses throughpandas data manipulations.

There are 3 possible constructor properties to be defined on a subclass:

  • DataFrame/Series._constructor: Used when a manipulation result has the same dimension as the original.

  • DataFrame._constructor_sliced: Used when aDataFrame (sub-)class manipulation result should be aSeries (sub-)class.

  • Series._constructor_expanddim: Used when aSeries (sub-)class manipulation result should be aDataFrame (sub-)class, e.g.Series.to_frame().

Below example shows how to defineSubclassedSeries andSubclassedDataFrame overriding constructor properties.

classSubclassedSeries(pd.Series):@propertydef_constructor(self):returnSubclassedSeries@propertydef_constructor_expanddim(self):returnSubclassedDataFrameclassSubclassedDataFrame(pd.DataFrame):@propertydef_constructor(self):returnSubclassedDataFrame@propertydef_constructor_sliced(self):returnSubclassedSeries
>>>s=SubclassedSeries([1,2,3])>>>type(s)<class '__main__.SubclassedSeries'>>>>to_framed=s.to_frame()>>>type(to_framed)<class '__main__.SubclassedDataFrame'>>>>df=SubclassedDataFrame({"A":[1,2,3],"B":[4,5,6],"C":[7,8,9]})>>>df   A  B  C0  1  4  71  2  5  82  3  6  9>>>type(df)<class '__main__.SubclassedDataFrame'>>>>sliced1=df[["A","B"]]>>>sliced1   A  B0  1  41  2  52  3  6>>>type(sliced1)<class '__main__.SubclassedDataFrame'>>>>sliced2=df["A"]>>>sliced20    11    22    3Name: A, dtype: int64>>>type(sliced2)<class '__main__.SubclassedSeries'>

Define original properties#

To let original data structures have additional properties, you should letpandas know what properties are added.pandas maps unknown properties to data names overriding__getattribute__. Defining original properties can be done in one of 2 ways:

  1. Define_internal_names and_internal_names_set for temporary properties which WILL NOT be passed to manipulation results.

  2. Define_metadata for normal properties which will be passed to manipulation results.

Below is an example to define two original properties, “internal_cache” as a temporary property and “added_property” as a normal property

classSubclassedDataFrame2(pd.DataFrame):# temporary properties_internal_names=pd.DataFrame._internal_names+["internal_cache"]_internal_names_set=set(_internal_names)# normal properties_metadata=["added_property"]@propertydef_constructor(self):returnSubclassedDataFrame2
>>>df=SubclassedDataFrame2({"A":[1,2,3],"B":[4,5,6],"C":[7,8,9]})>>>df   A  B  C0  1  4  71  2  5  82  3  6  9>>>df.internal_cache="cached">>>df.added_property="property">>>df.internal_cachecached>>>df.added_propertyproperty# properties defined in _internal_names is reset after manipulation>>>df[["A","B"]].internal_cacheAttributeError: 'SubclassedDataFrame2' object has no attribute 'internal_cache'# properties defined in _metadata are retained>>>df[["A","B"]].added_propertyproperty

Plotting backends#

pandas can be extended with third-party plotting backends. Themain idea is letting users select a plotting backend different than the providedone based on Matplotlib. For example:

>>>pd.set_option("plotting.backend","backend.module")>>>pd.Series([1,2,3]).plot()

This would be more or less equivalent to:

>>>importbackend.module>>>backend.module.plot(pd.Series([1,2,3]))

The backend module can then use other visualization tools (Bokeh, Altair,…)to generate the plots.

Libraries implementing the plotting backend should useentry pointsto make their backend discoverable to pandas. The key is"pandas_plotting_backends". For example, pandasregisters the default “matplotlib” backend as follows.

# in setup.pysetup(# noqa: F821...,entry_points={"pandas_plotting_backends":["matplotlib = pandas:plotting._matplotlib",],},)

More information on how to implement a third-party plotting backend can be found atpandas-dev/pandas.

Arithmetic with 3rd party types#

In order to control how arithmetic works between a custom type and a pandas type,implement__pandas_priority__. Similar to numpy’s__array_priority__semantics, arithmetic methods onDataFrame,Series, andIndexobjects will delegate toother, if it has an attribute__pandas_priority__ with a higher value.

By default, pandas objects try to operate with other objects, even if they are not types known to pandas:

>>>pd.Series([1,2])+[10,20]0    111    22dtype: int64

In the example above, if[10,20] was a custom type that can be understood as a list, pandas objects will still operate with it in the same way.

In some cases, it is useful to delegate to the other type the operation. For example, consider I implement acustom list object, and I want the result of adding my custom list with a pandasSeries to be an instance of my listand not aSeries as seen in the previous example. This is now possible by defining the__pandas_priority__ attributeof my custom list, and setting it to a higher value, than the priority of the pandas objects I want to operate with.

The__pandas_priority__ ofDataFrame,Series, andIndex are4000,3000, and2000 respectively. The baseExtensionArray.__pandas_priority__ is1000.

classCustomList(list):__pandas_priority__=5000def__radd__(self,other):# return `self` and not the addition for simplicityreturnselfcustom=CustomList()series=pd.Series([1,2,3])# Series refuses to add custom, since it's an unknown type with higher priorityassertseries.__add__(custom)isNotImplemented# This will cause the custom class `__radd__` being used insteadassertseries+customiscustom