Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion dask/array/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1104,6 +1104,10 @@ def npartitions(self):
def shape(self):
return tuple(map(sum, self.chunks))

@property
def _meta(self):
return np.empty(shape=(), dtype=self.dtype)

def _get_chunks(self):
return self._chunks

Expand Down Expand Up @@ -2936,7 +2940,10 @@ def elemwise(op, *args, **kwargs):
vals = [np.empty((1,) * max(1, a.ndim), dtype=a.dtype)
if not is_scalar_for_elemwise(a) else a
for a in args]
dt = apply_infer_dtype(op, vals, {}, 'elemwise', suggest_dtype=False)
try:
dt = apply_infer_dtype(op, vals, {}, 'elemwise', suggest_dtype=False)
except Exception:
return NotImplemented
need_enforce_dtype = any(not is_scalar_for_elemwise(a) and a.ndim == 0 for a in args)

name = kwargs.get('name', None) or '%s-%s' % (funcname(op),
Expand Down
8 changes: 8 additions & 0 deletions dask/array/tests/test_array_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3136,3 +3136,11 @@ def test_empty_chunks_in_array_len():

err_msg = 'len() of unsized object'
assert err_msg in str(exc_info.value)


@pytest.mark.parametrize('dtype', [None, [('a', 'f4'), ('b', object)]])
def test_meta(dtype):
a = da.zeros((1,), chunks=(1,))
assert a._meta.dtype == a.dtype
assert isinstance(a._meta, np.ndarray)
assert a.nbytes < 1000
46 changes: 39 additions & 7 deletions dask/dataframe/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from ..utils import (random_state_data, pseudorandom, derived_from, funcname,
memory_repr, put_lines, M, key_split, OperatorMethodMixin,
is_arraylike)
from ..array import Array
from ..base import Base, tokenize, dont_optimize, is_dask_collection
from . import methods
from .accessor import DatetimeAccessor, StringAccessor
Expand Down Expand Up @@ -3017,29 +3018,60 @@ def is_broadcastable(dfs, s):


def elemwise(op, *args, **kwargs):
""" Elementwise operation for dask.Dataframes """
""" Elementwise operation for Dask dataframes

Parameters
----------
op: callable
Function to apply across input dataframes
*args: DataFrames, Series, Scalars, Arrays,
The arguments of the operation
**kwrags: scalars
meta: pd.DataFrame, pd.Series (optional)
Valid metadata for the operation. Will evaluate on a small piece of
data if not provided.

Examples
--------
>>> elemwise(operator.add, df.x, df.y) # doctest: +SKIP
"""
meta = kwargs.pop('meta', no_default)

_name = funcname(op) + '-' + tokenize(op, kwargs, *args)
_name = funcname(op) + '-' + tokenize(op, *args, **kwargs)

args = _maybe_from_pandas(args)

from .multi import _maybe_align_partitions
args = _maybe_align_partitions(args)
dasks = [arg for arg in args if isinstance(arg, (_Frame, Scalar))]
dasks = [arg for arg in args if isinstance(arg, (_Frame, Scalar, Array))]
dfs = [df for df in dasks if isinstance(df, _Frame)]

# Clean up dask arrays if present
for i, a in enumerate(dasks):
if not isinstance(a, Array):
continue
# Ensure that they have similar-ish chunk structure
if not all(len(a.chunks[0]) == df.npartitions for df in dfs):
msg = ("When combining dask arrays with dataframes they must "
"match chunking exactly. Operation: %s" % funcname(op))
raise ValueError(msg)
# Rechunk to have a single chunk along all other axes
if a.ndim > 1:
a = a.rechunk({i + 1: d for i, d in enumerate(a.shape[1:])})
dasks[i] = a

divisions = dfs[0].divisions
_is_broadcastable = partial(is_broadcastable, dfs)
dfs = list(remove(_is_broadcastable, dfs))
n = len(divisions) - 1

other = [(i, arg) for i, arg in enumerate(args)
if not isinstance(arg, (_Frame, Scalar))]
if not isinstance(arg, (_Frame, Scalar, Array))]

# adjust the key length of Scalar
keys = [d.__dask_keys__() * n
if isinstance(d, Scalar) or _is_broadcastable(d)
else d.__dask_keys__() for d in dasks]
else core.flatten(d.__dask_keys__()) for d in dasks]

if other:
dsk = {(_name, i):
Expand All @@ -3051,12 +3083,12 @@ def elemwise(op, *args, **kwargs):
dsk = merge(dsk, *[d.dask for d in dasks])

if meta is no_default:
if len(dfs) >= 2 and len(dasks) != len(dfs):
if len(dfs) >= 2 and not all(hasattr(d, 'npartitions') for d in dasks):
# should not occur in current funcs
msg = 'elemwise with 2 or more DataFrames and Scalar is not supported'
raise NotImplementedError(msg)
# For broadcastable series, use no rows.
parts = [d._meta if _is_broadcastable(d)
parts = [d._meta if _is_broadcastable(d) or isinstance(d, Array)
else d._meta_nonempty for d in dasks]
with raise_on_meta_error(funcname(op)):
meta = partial_by_order(*parts, function=op, other=other)
Expand Down
61 changes: 53 additions & 8 deletions dask/dataframe/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytest

import dask
import dask.array as da
import dask.dataframe as dd
from dask.base import compute_as_if_collection
from dask.utils import put_lines, M
Expand Down Expand Up @@ -997,17 +998,17 @@ def test_combine():
first = lambda a, b: a

# DataFrame
for da, db, a, b in [(ddf1, ddf2, df1, df2),
(ddf1.A, ddf2.A, df1.A, df2.A),
(ddf1.B, ddf2.B, df1.B, df2.B)]:
for dda, ddb, a, b in [(ddf1, ddf2, df1, df2),
(ddf1.A, ddf2.A, df1.A, df2.A),
(ddf1.B, ddf2.B, df1.B, df2.B)]:
for func, fill_value in [(add, None), (add, 100), (first, None)]:
sol = a.combine(b, func, fill_value=fill_value)
assert_eq(da.combine(db, func, fill_value=fill_value), sol)
assert_eq(da.combine(b, func, fill_value=fill_value), sol)
assert_eq(dda.combine(ddb, func, fill_value=fill_value), sol)
assert_eq(dda.combine(b, func, fill_value=fill_value), sol)

assert_eq(ddf1.combine(ddf2, add, overwrite=False),
df1.combine(df2, add, overwrite=False))
assert da.combine(db, add)._name == da.combine(db, add)._name
assert dda.combine(ddb, add)._name == dda.combine(ddb, add)._name


def test_combine_first():
Expand Down Expand Up @@ -2943,7 +2944,6 @@ def test_cumulative_multiple_columns():

@pytest.mark.parametrize('func', [np.asarray, M.to_records])
def test_map_partition_array(func):
import dask.array as da
from dask.array.utils import assert_eq
df = pd.DataFrame({'x': [1, 2, 3, 4, 5],
'y': [6.0, 7.0, 8.0, 9.0, 10.0]},
Expand All @@ -2968,7 +2968,6 @@ def test_map_partition_array(func):

def test_map_partition_sparse():
sparse = pytest.importorskip('sparse')
import dask.array as da
df = pd.DataFrame({'x': [1, 2, 3, 4, 5],
'y': [6.0, 7.0, 8.0, 9.0, 10.0]},
index=['a', 'b', 'c', 'd', 'e'])
Expand All @@ -2985,3 +2984,49 @@ def f(d):
computed = result.compute()
assert (computed.data == expected.data).all()
assert (computed.coords == expected.coords).all()


def test_mixed_dask_array_operations():
df = pd.DataFrame({'x': [1, 2, 3]}, index=[4, 5, 6])
ddf = dd.from_pandas(df, npartitions=2)

assert_eq(df.x + df.x.values,
ddf.x + ddf.x.values)
assert_eq(df.x.values + df.x,
ddf.x.values + ddf.x)

assert_eq(df.x + df.index.values,
ddf.x + ddf.index.values)
assert_eq(df.index.values + df.x,
ddf.index.values + ddf.x)


def test_mixed_dask_array_operations_errors():
df = pd.DataFrame({'x': [1, 2, 3, 4, 5]}, index=[4, 5, 6, 7, 8])
ddf = dd.from_pandas(df, npartitions=2)

x = da.arange(5, chunks=((1, 4),))
x._chunks = ((np.nan, np.nan),)

with pytest.raises(ValueError):
(ddf.x + x).compute()

x = da.arange(5, chunks=((2, 2, 1),))
with pytest.raises(ValueError) as info:
ddf.x + x

assert 'add' in str(info.value)


def test_mixed_dask_array_multi_dimensional():
df = pd.DataFrame({'x': [1, 2, 3, 4, 5],
'y': [5., 6., 7., 8., 9.]},
columns=['x', 'y'])
ddf = dd.from_pandas(df, npartitions=2)

x = (df.values + 1).astype(float)
dx = (ddf.values + 1).astype(float)

assert_eq(ddf + dx + 1, df + x + 1)
assert_eq(ddf + dx.rechunk((None, 1)) + 1, df + x + 1)
assert_eq(ddf[['y', 'x']] + dx + 1, df[['y', 'x']] + x + 1)
1 change: 1 addition & 0 deletions docs/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ DataFrame
+++++++++

- Add ``dd.tseries.Resampler.agg`` (:pr:`3202`) `Richard Postelnik`_
- Support operations that mix dataframes and arrays (:pr:`3230`) `Matthew Rocklin`_

Bag
+++
Expand Down