To be able to use numpy
arrays you must first have installed the numpy
package..
You can use numpy
1d and 2d arrays as argument types to pass ranges
of data into your function, and as return types for returing for array
functions. A maximum of two dimensions are supported, as higher dimension
arrays don’t fit well with how data is arranged in a spreadsheet. You can,
however, work with higher-dimensional arrays as Python objects.
To specify that a function should accept a numpy array as an argument or as
its return type, use the numpy_array
, numpy_row
or numpy_column
types in the xl_func
function signature.
These types can be parameterized, meaning you can set some additional options when specifying the type in the function signature.
numpy_array<dtype=float, ndim=2, casting='unsafe'>
dtype
Data type of the items in the array (e.g. float, int, bool etc.).ndim
Array dimensions, must be 1 or 2.casting
Controls what kind of data casting may occur. Default is ‘unsafe’.'unsafe'
Always convert to chosen dtype. Will fail if any input can’t be converted.'nan'
If an input can’t be converted, replace it with NaN.'no'
Don’t do any type conversion.numpy_row<dtype=float, casting='unsafe'>
dtype
Data type of the items in the array (e.g. float, int, bool etc.).casting
Controls what kind of data casting may occur. Default is ‘unsafe’.'unsafe'
Always convert to chosen dtype. Will fail if any input can’t be converted.'nan'
If an input can’t be converted, replace it with NaN.'no'
Don’t do any type conversion.numpy_column<dtype=float, casting='unsafe'>
dtype
Data type of the items in the array (e.g. float, int, bool etc.).casting
Controls what kind of data casting may occur. Default is ‘unsafe’.'unsafe'
Always convert to chosen dtype. Will fail if any input can’t be converted.'nan'
If an input can’t be converted, replace it with NaN.'no'
Don’t do any type conversion.For example, a function accepting two 1d numpy arrays of floats and returning a 2d array would look like:
from pyxll import xl_func
import numpy
@xl_func("numpy_array<float, ndim=1> a, numpy_array<float, ndim=1> b: numpy_array<float>")
def numpy_outer(a, b):
return numpy.outer(a, b)
The ‘float’ dtype isn’t strictly necessary as it’s the default. If you don’t want to set the type parameters in
the signature, use the xl_arg
and xl_return
decorators instead.
PyXLL will automatically resize the range of the array formula to match the returned data if you specify
auto_resize=True
in your py:func:xl_func call.
Floating point numpy arrays are the fastest way to get data out of Excel into Python. If you are working
on performance sensitive code using a lot of data, try to make use of numpy_array<float>
or
numpy_array<float, casting='nan'>
for the best performance.
See Array Functions for more details about array functions.