numpy.full

Here are the examples of the python api numpy.full taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

Example 1

Project: chainer
Source File: test_constant.py
View license
    def check_initializer(self, w):
        initializer = initializers.Constant(fill_value=self.fill_value)
        initializer(w)
        testing.assert_allclose(
            w, numpy.full(self.shape, self.fill_value),
            **self.check_options)

Example 2

Project: chainer
Source File: test_constant.py
View license
    def check_shaped_initializer(self, xp):
        initializer = initializers.Constant(
            fill_value=self.fill_value, dtype=self.dtype)
        w = initializers.generate_array(initializer, self.shape, xp)
        self.assertIs(cuda.get_array_module(w), xp)
        self.assertTupleEqual(w.shape, self.shape)
        self.assertEqual(w.dtype, self.dtype)
        testing.assert_allclose(
            w, numpy.full(self.shape, self.fill_value),
            **self.check_options)

Example 3

View license
    def setUp(self):
        self.dates = date_range('2014-01-01', periods=5, freq='D')
        self.assets = Int64Index(range(5))
        self.f = F()
        self.g = G()
        self.h = H()
        self.d = DateFactor()
        self.fake_raw_data = {
            self.f: full((5, 5), 3, float),
            self.g: full((5, 5), 2, float),
            self.h: full((5, 5), 1, float),
            self.d: full((5, 5), 0, dtype='datetime64[ns]'),
        }
        self.mask = DataFrame(True, index=self.dates, columns=self.assets)

Example 4

Project: zipline
Source File: dispatch_bar_reader.py
View license
    def _make_raw_array_out(self, field, shape):
        if field != 'volume' and field != 'sid':
            out = full(shape, nan)
        else:
            out = zeros(shape, dtype=int64)
        return out

Example 5

Project: zipline
Source File: labelarray.py
View license
    def empty_like(self, shape):
        """
        Make an empty LabelArray with the same categories as ``self``, filled
        with ``self.missing_value``.
        """
        return type(self)._from_codes_and_metadata(
            codes=np.full(
                shape,
                self.reverse_categories[self.missing_value],
                dtype=int_dtype_with_size_in_bytes(self.itemsize),
            ),
            categories=self.categories,
            reverse_categories=self.reverse_categories,
            missing_value=self.missing_value,
        )

Example 6

Project: zipline
Source File: expression.py
View license
    def _compute(self, arrays, dates, assets, mask):
        """
        Compute our stored expression string with numexpr.
        """
        out = full(mask.shape, self.missing_value, dtype=self.dtype)
        # This writes directly into our output buffer.
        numexpr.evaluate(
            self._expr,
            local_dict={
                "x_%d" % idx: array
                for idx, array in enumerate(arrays)
            },
            global_dict={'inf': inf},
            out=out,
        )
        return out

Example 7

Project: zipline
Source File: core.py
View license
    def get_history_window(self, assets, end_dt, bar_count, frequency, field,
                           ffill=True):
        if frequency == "1d":
            end_idx = \
                self.trading_calendar.all_sessions.searchsorted(end_dt)
            days = self.trading_calendar.all_sessions[
                (end_idx - bar_count + 1):(end_idx + 1)
            ]

            df = pd.DataFrame(
                np.full((bar_count, len(assets)), 100.0),
                index=days,
                columns=assets
            )

            return df

Example 8

Project: filterpy
Source File: sigma_points.py
View license
    def weights(self):
        """ Computes the weights for the scaled unscented Kalman filter.

        Returns
        -------

        Wm : ndarray[n+1]
            weights for mean

        Wc : ndarray[n+1]
            weights for the covariances
        """

        n = self.n
        c = 1. / (n + 1)
        W = np.full(n + 1, c)

        return W, W

Example 9

Project: pyNastran
Source File: cbar.py
View license
    def allocate(self, card_count):
        ncards = card_count[self.type]
        self.n = ncards
        if self.n:
            assert isinstance(ncards, int), ncards
            float_fmt = self.model.float_fmt
            #: Element ID
            self.element_id = zeros(ncards, 'int32')
            #: Property ID
            self.property_id = zeros(ncards, 'int32')
            self.node_ids = zeros((ncards, 2), 'int32')
            self.is_g0 = zeros(ncards, 'bool')
            self.g0 = full(ncards, nan, 'int32')
            self.x = full((ncards, 3), nan, float_fmt)
            self.offt = full(ncards, nan, '|S3')
            self.pin_flags = zeros((ncards, 2), 'int32')
            self.wa = zeros((ncards, 3), float_fmt)
            self.wb = zeros((ncards, 3), float_fmt)

Example 10

Project: pyNastran
Source File: cbush.py
View license
    def allocate(self, card_count):
        ncards = card_count[self.type]
        if ncards:
            self.n = ncards
            float_fmt = self.model.float_fmt
            #: Element ID
            self.element_id = zeros(ncards, 'int32')
            #: Property ID
            self.property_id = zeros(ncards, 'int32')
            self.node_ids = zeros((ncards, 2), 'int32')
            self.is_g0 = zeros(ncards, 'bool')
            self.g0 = full(ncards, nan, 'int32')
            self.x = full((ncards, 3), nan, float_fmt)
            self.cid = full(ncards, nan, 'int32')
            self.s = full(ncards, nan, float_fmt)
            self.ocid = full(ncards, nan, 'int32')
            self.si = full((ncards, 3), nan, float_fmt)

Example 11

Project: qcache
Source File: __init__.py
View license
def _add_stand_in_columns(df, stand_in_columns):
    if not stand_in_columns:
        return df

    for column_name, stand_in_value in stand_in_columns:
        if column_name not in df:
            if stand_in_value in df:
                df.loc[:, column_name] = df[stand_in_value]
            else:
                dtype = _get_dtype(stand_in_value)
                stand_in_value = unquote(stand_in_value)
                arr = numpy.full(len(df), stand_in_value, dtype=dtype)
                df.loc[:, column_name] = pandas.Series(arr, index=df.index)

Example 12

Project: drmad
Source File: grads.py
View license
def make_grad_np_sum(ans, x, axis=None, keepdims=False):
    if not isarray(x):
        return [I]
    shape = x.shape
    if axis is None:
        return [lambda g : np.full(shape, g)]
    else:
        if keepdims:
            return [lambda g : np.repeat(g, shape[axis], axis)]
        else:
            return [lambda g : np.repeat(np.expand_dims(g, axis),
                                         shape[axis], axis)]

Example 13

Project: drmad
Source File: grads.py
View license
def make_grad_np_mean(ans, x, axis=None, keepdims=False):
    if not isarray(x):
        return [I]
    shape = x.shape
    if axis is None:
        return [lambda g : np.full(shape, g) / np.prod(shape)]
    else:
        if keepdims:
            return [lambda g : np.repeat(g, shape[axis], axis) / shape[axis]]
        else:
            return [lambda g : np.repeat(np.expand_dims(g, axis),
                                         shape[axis], axis) / shape[axis]]

Example 14

Project: drmad
Source File: nn_utils.py
View license
def fill_parser(parser, items):
    """Build a vector by assigning each block the corresponding value in
       the items vector."""
    partial_vects = [np.full(parser[name].size, items[i])
                     for i, name in enumerate(parser.names)]
    return np.concatenate(partial_vects, axis=0)

Example 15

View license
def test_density():
    b = 0xffff0000
    data = np.full((4, 4), b, dtype='uint32')
    assert tf._density(data) == 1.0
    data = np.zeros((4, 4), dtype='uint32')
    assert tf._density(data) == np.inf
    data[2, 2] = b
    assert tf._density(data) == 0
    data[2, 1] = data[1, 2] = data[1, 1] = b
    assert np.allclose(tf._density(data), 3./8.)

Example 16

Project: distributed
Source File: test_collections.py
View license
@gen_cluster(timeout=60, client=True)
def test__futures_to_dask_array(c, s, a, b):
    import dask.array as da
    remote_arrays = [[[c.submit(np.full, (2, 3, 4), i + j + k)
                        for i in range(2)]
                        for j in range(2)]
                        for k in range(4)]

    x = yield _futures_to_dask_array(remote_arrays, client=c)
    assert x.chunks == ((2, 2, 2, 2), (3, 3), (4, 4))
    assert x.dtype == np.full((), 0).dtype

    assert isinstance(x, da.Array)
    expr = x.sum()
    result = yield c._get(expr.dask, expr._keys())
    assert isinstance(result[0], np.number)

Example 17

Project: distributed
Source File: test_collections.py
View license
@pytest.mark.skipif(not sys.platform.startswith('linux'),
                    reason='KQueue error - uncertain cause')
def test_futures_to_dask_array(loop):
    with cluster() as (c, [a, b]):
        with Client(('127.0.0.1', c['port']), loop=loop) as c:
            remote_arrays = [[c.submit(np.full, (3, 3), i + j)
                                for i in range(3)]
                                for j in range(3)]

            x = futures_to_dask_array(remote_arrays, client=c)
            assert x.chunks == ((3, 3, 3), (3, 3, 3))
            assert x.dtype == np.full((), 0).dtype

            assert x.sum().compute(get=c.get) == 162
            assert (x + x.T).sum().compute(get=c.get) == 162 * 2

            y = futures_to_collection(remote_arrays, client=c)
            assert x.dask == y.dask

Example 18

Project: minpy
Source File: numpy_core.py
View license
def _sum_grad(ans, x, axis=None, keepdims=False):
    """ Generate gradient function of sum """
    if axis is None:
        return lambda g: np.full(x.shape, g)
    if isinstance(axis, int):
        axis = [axis]
    elif isinstance(axis, tuple):
        axis = list(axis)
    ans_shape_expanded = list(x.shape)
    for a in axis:
        ans_shape_expanded[a] = 1
    xshape = x.shape  # Only shape is needed, hope array `x` could be GC'ed.
    return lambda g: np.zeros(xshape) + np.reshape(g, ans_shape_expanded)

Example 19

Project: hmmlearn
Source File: base.py
View license
    def _init(self, X, lengths):
        """Initializes model parameters prior to fitting.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Feature matrix of individual samples.

        lengths : array-like of integers, shape (n_sequences, )
            Lengths of the individual sequences in ``X``. The sum of
            these should be ``n_samples``.
        """
        init = 1. / self.n_components
        if 's' in self.init_params or not hasattr(self, "startprob_"):
            self.startprob_ = np.full(self.n_components, init)
        if 't' in self.init_params or not hasattr(self, "transmat_"):
            self.transmat_ = np.full((self.n_components, self.n_components),
                                     init)

Example 20

Project: automl-phase-2
Source File: sandpit.py
View license
def global_test():
    raw_input('I begin')
    # global my_global
    global_data.my_global = np.full((2**17, 2 * 2**10), 42)
    raw_input('Globals created')
    processing_pool = Pool(10)
    processing_pool.map(import_and_print_globals, [None] * 10)
    processing_pool.close()
    processing_pool.join()
    raw_input('Multiprocessing complete')

Example 21

Project: deep-go-wrap
Source File: analyze_board.py
View license
def npclose(a, empty, closeset, verbose=False):
    inf = a.shape[0] * 2
    ret = np.full(a.shape, inf)
    it = np.nditer(empty, flags=['multi_index'])
    while not it.finished:
        x,y = it.multi_index

        dist,xs,ys = closeset[x][y]
        arg = a[xs,ys].argmax()
        if a[xs[arg],ys[arg]]:
            ret[x][y] = dist[arg]

        it.iternext()

    return ret

Example 22

Project: deep-go-wrap
Source File: analyze_board.py
View license
def npclose(a, empty, closeset, verbose=False):
    inf = a.shape[0] * 2
    ret = np.full(a.shape, inf)
    it = np.nditer(empty, flags=['multi_index'])
    while not it.finished:
        x,y = it.multi_index

        dist,xs,ys = closeset[x][y]
        arg = a[xs,ys].argmax()
        if a[xs[arg],ys[arg]]:
            ret[x][y] = dist[arg]

        it.iternext()

    return ret

Example 23

View license
  def make_param(self, shape, init_scheme):
    """Create Theano shared variables, which are used as trainable model parameters."""
    if isinstance(init_scheme, numbers.Number):
      init_value = np.full(shape, init_scheme, floatX)
    elif init_scheme == 'uniform':
      init_value = self._np_rng.uniform(low=-self._init_scale, high=self._init_scale, size=shape).astype(floatX)
    else:
      raise AssertionError('unsupported init_scheme')
    p = theano.shared(init_value)
    self._params.append(p)
    return p

Example 24

View license
  def make_param(self, shape, init_scheme):
    """Create Theano shared variables, which are used as trainable model parameters."""
    if isinstance(init_scheme, numbers.Number):
      init_value = np.full(shape, init_scheme, floatX)
    elif init_scheme == 'uniform':
      init_value = self._np_rng.uniform(low=-self._init_scale, high=self._init_scale, size=shape).astype(floatX)
    else:
      raise AssertionError('unsupported init_scheme')
    p = theano.shared(init_value)
    self._params.append(p)
    return p

Example 25

Project: landlab
Source File: test_flow_routing.py
View license
@with_setup(setup_dans_grid1)
def test_check_field_input():
    """Check we can successfully pass water__discharge_in."""
    mg.add_field('node', 'water__unit_flux_in',
                 np.full(25, 3.), units='m**3/s')
    fr = FlowRouter(mg)
    assert_array_equal(np.full(25, 3.), mg.at_node['water__unit_flux_in'])
    fr = FlowRouter(mg, infile)
    assert_array_equal(np.full(25, 2.), mg.at_node['water__unit_flux_in'])

Example 26

Project: landlab
Source File: test_flow_routing.py
View license
@with_setup(setup_dans_grid1)
def test_check_field_input():
    """Check we can successfully pass water__discharge_in."""
    mg.add_field('node', 'water__unit_flux_in',
                 np.full(25, 3.), units='m**3/s')
    fr = FlowRouter(mg)
    assert_array_equal(np.full(25, 3.), mg.at_node['water__unit_flux_in'])
    fr = FlowRouter(mg, infile)
    assert_array_equal(np.full(25, 2.), mg.at_node['water__unit_flux_in'])

Example 27

Project: landlab
Source File: dual.py
View license
    def _create_link_at_face(self):
        link_at_nodes = {}
        for link, pair in enumerate(self.nodes_at_link):
            pair.sort()
            link_at_nodes[tuple(pair)] = link

        link_at_face = np.full((self.number_of_faces, ), -1, dtype=int)
        for face, pair in enumerate(self._nodes_at_face):
            pair.sort()
            link_at_face[face] = link_at_nodes[tuple(pair)]
        self._link_at_face = link_at_face
        return self._link_at_face

Example 28

Project: landlab
Source File: dual.py
View license
    def _create_link_at_face(self):
        link_at_nodes = {}
        for link, pair in enumerate(self.nodes_at_link):
            pair.sort()
            link_at_nodes[tuple(pair)] = link

        link_at_face = np.full((self.number_of_faces, ), -1, dtype=int)
        for face, pair in enumerate(self._nodes_at_face):
            pair.sort()
            link_at_face[face] = link_at_nodes[tuple(pair)]
        self._link_at_face = link_at_face
        return self._link_at_face

Example 29

Project: landlab
Source File: test_status_at_node.py
View license
def test_set_status_with_array_bool():
    """Test setting node status with boolean array."""
    grid = RasterModelGrid((4, 5))
    inds = np.full((20, ), False, dtype=bool)
    inds[6] = True
    inds[7] = True
    inds[13] = True

    grid.status_at_node[inds] = 2
    assert_array_equal(grid.status_at_node,
                       [FV, FV, FV, FV, FV,
                        FV,  2,  2,  0, FV,
                        FV,  0,  0,  2, FV,
                        FV, FV, FV, FV, FV])

Example 30

Project: landlab
Source File: test_status_at_node.py
View license
def test_set_status_with_array_bool():
    """Test setting node status with boolean array."""
    grid = RasterModelGrid((4, 5))
    inds = np.full((20, ), False, dtype=bool)
    inds[6] = True
    inds[7] = True
    inds[13] = True

    grid.status_at_node[inds] = 2
    assert_array_equal(grid.status_at_node,
                       [FV, FV, FV, FV, FV,
                        FV,  2,  2,  0, FV,
                        FV,  0,  0,  2, FV,
                        FV, FV, FV, FV, FV])

Example 31

Project: numpy-groupies
Source File: aggregate_numba.py
View license
    def _initialize(self, flat_size, fill_value, dtype):
        if self.nans:
            # For avoiding branches
            flat_size += 1
        if self.forced_fill_value is None:
            ret = np.full(flat_size, fill_value, dtype=dtype)
        else:
            ret = np.full(flat_size, self.forced_fill_value, dtype=dtype)
        counter = np.full_like(ret, self.counter_fill_value, dtype=self.counter_dtype)
        if self.mean_fill_value is not None:
            mean = np.full_like(ret, self.mean_fill_value, dtype=ret.dtype)
        else:
            mean = None
        return ret, counter, mean

Example 32

Project: numpy-groupies
Source File: aggregate_numpy.py
View license
def _prod(group_idx, a, size, fill_value, dtype=None):
    dtype = minimum_dtype_scalar(fill_value, dtype, a)
    ret = np.full(size, fill_value, dtype=dtype)
    if fill_value != 1:
        ret[group_idx] = 1  # product starts from 1
    np.multiply.at(ret, group_idx, a)
    return ret

Example 33

Project: numpy-groupies
Source File: aggregate_numpy.py
View license
def _all(group_idx, a, size, fill_value, dtype=None):
    check_boolean(fill_value)
    ret = np.full(size, fill_value, dtype=bool)
    if not fill_value:
        ret[group_idx] = True
    ret[group_idx.compress(np.logical_not(a))] = False
    return ret

Example 34

Project: numpy-groupies
Source File: aggregate_numpy.py
View license
def _any(group_idx, a, size, fill_value, dtype=None):
    check_boolean(fill_value)
    ret = np.full(size, fill_value, dtype=bool)
    if fill_value:
        ret[group_idx] = False
    ret[group_idx.compress(a)] = True
    return ret

Example 35

Project: numpy-groupies
Source File: aggregate_numpy.py
View license
def _generic_callable(group_idx, a, size, fill_value, dtype=None,
                      func=lambda g: g):
    """groups a by inds, and then applies foo to each group in turn, placing
    the results in an array."""
    groups = _array(group_idx, a, size, (), dtype=dtype)
    ret = np.full(size, fill_value, dtype=object)

    for i, grp in enumerate(groups):
        if np.ndim(grp) == 1 and len(grp) > 0:
            ret[i] = func(grp)
    return ret

Example 36

View license
def _any(group_idx, a, size, fill_value, dtype=None):
    check_boolean(fill_value)
    ret = np.full(size, fill_value, dtype=bool)
    if fill_value:
        ret[group_idx] = False  # any-test should start from False
    np.logical_or.at(ret, group_idx, a)
    return ret

Example 37

View license
def _all(group_idx, a, size, fill_value, dtype=None):
    check_boolean(fill_value)
    ret = np.full(size, fill_value, dtype=bool)
    if not fill_value:
        ret[group_idx] = True  # all-test should start from True
    np.logical_and.at(ret, group_idx, a)
    return ret

Example 38

View license
def _sum(group_idx, a, size, fill_value, dtype=None):
    dtype = minimum_dtype_scalar(fill_value, dtype, a)
    ret = np.full(size, fill_value, dtype=dtype)
    if fill_value != 0:
        ret[group_idx] = 0  # sums should start at 0
    np.add.at(ret, group_idx, a)
    return ret

Example 39

View license
def _prod(group_idx, a, size, fill_value, dtype=None):
    """Same as aggregate_numpy.py"""
    dtype = minimum_dtype_scalar(fill_value, dtype, a)
    ret = np.full(size, fill_value, dtype=dtype)
    if fill_value != 1:
        ret[group_idx] = 1  # product should start from 1
    np.multiply.at(ret, group_idx, a)
    return ret

Example 40

Project: numpy-groupies
Source File: aggregate_pandas.py
View license
def _wrapper(group_idx, a, size, fill_value, func='sum', dtype=None, ddof=0):
    kwargs = dict()
    if func in ('var', 'std'):
        kwargs['ddof'] = ddof
    if isstr(func):
        grouped = getattr(pd.DataFrame({'group_idx': group_idx, 'a': a})
                          .groupby('group_idx'), func)(**kwargs)
    else:
        grouped = pd.DataFrame({'group_idx': group_idx, 'a': a})\
                    .groupby('group_idx').aggregate(func, **kwargs)

    dtype = check_dtype(dtype, getattr(func, '__name__', func), a, size)
    ret = np.full(size, fill_value, dtype=dtype)
    ret[grouped.index] = grouped
    return ret

Example 41

Project: numpy-groupies
Source File: aggregate_numba.py
View license
    def _initialize(self, flat_size, fill_value, dtype):
        if self.nans:
            # For avoiding branches
            flat_size += 1
        if self.forced_fill_value is None:
            ret = np.full(flat_size, fill_value, dtype=dtype)
        else:
            ret = np.full(flat_size, self.forced_fill_value, dtype=dtype)
        counter = np.full_like(ret, self.counter_fill_value, dtype=self.counter_dtype)
        if self.mean_fill_value is not None:
            mean = np.full_like(ret, self.mean_fill_value, dtype=ret.dtype)
        else:
            mean = None
        return ret, counter, mean

Example 42

Project: numpy-groupies
Source File: aggregate_numpy.py
View license
def _prod(group_idx, a, size, fill_value, dtype=None):
    dtype = minimum_dtype_scalar(fill_value, dtype, a)
    ret = np.full(size, fill_value, dtype=dtype)
    if fill_value != 1:
        ret[group_idx] = 1  # product starts from 1
    np.multiply.at(ret, group_idx, a)
    return ret

Example 43

Project: numpy-groupies
Source File: aggregate_numpy.py
View license
def _all(group_idx, a, size, fill_value, dtype=None):
    check_boolean(fill_value)
    ret = np.full(size, fill_value, dtype=bool)
    if not fill_value:
        ret[group_idx] = True
    ret[group_idx.compress(np.logical_not(a))] = False
    return ret

Example 44

Project: numpy-groupies
Source File: aggregate_numpy.py
View license
def _any(group_idx, a, size, fill_value, dtype=None):
    check_boolean(fill_value)
    ret = np.full(size, fill_value, dtype=bool)
    if fill_value:
        ret[group_idx] = False
    ret[group_idx.compress(a)] = True
    return ret

Example 45

Project: numpy-groupies
Source File: aggregate_numpy.py
View license
def _generic_callable(group_idx, a, size, fill_value, dtype=None,
                      func=lambda g: g):
    """groups a by inds, and then applies foo to each group in turn, placing
    the results in an array."""
    groups = _array(group_idx, a, size, (), dtype=dtype)
    ret = np.full(size, fill_value, dtype=object)

    for i, grp in enumerate(groups):
        if np.ndim(grp) == 1 and len(grp) > 0:
            ret[i] = func(grp)
    return ret

Example 46

View license
def _any(group_idx, a, size, fill_value, dtype=None):
    check_boolean(fill_value)
    ret = np.full(size, fill_value, dtype=bool)
    if fill_value:
        ret[group_idx] = False  # any-test should start from False
    np.logical_or.at(ret, group_idx, a)
    return ret

Example 47

View license
def _all(group_idx, a, size, fill_value, dtype=None):
    check_boolean(fill_value)
    ret = np.full(size, fill_value, dtype=bool)
    if not fill_value:
        ret[group_idx] = True  # all-test should start from True
    np.logical_and.at(ret, group_idx, a)
    return ret

Example 48

View license
def _sum(group_idx, a, size, fill_value, dtype=None):
    dtype = minimum_dtype_scalar(fill_value, dtype, a)
    ret = np.full(size, fill_value, dtype=dtype)
    if fill_value != 0:
        ret[group_idx] = 0  # sums should start at 0
    np.add.at(ret, group_idx, a)
    return ret

Example 49

View license
def _prod(group_idx, a, size, fill_value, dtype=None):
    """Same as aggregate_numpy.py"""
    dtype = minimum_dtype_scalar(fill_value, dtype, a)
    ret = np.full(size, fill_value, dtype=dtype)
    if fill_value != 1:
        ret[group_idx] = 1  # product should start from 1
    np.multiply.at(ret, group_idx, a)
    return ret

Example 50

Project: numpy-groupies
Source File: aggregate_pandas.py
View license
def _wrapper(group_idx, a, size, fill_value, func='sum', dtype=None, ddof=0):
    kwargs = dict()
    if func in ('var', 'std'):
        kwargs['ddof'] = ddof
    if isstr(func):
        grouped = getattr(pd.DataFrame({'group_idx': group_idx, 'a': a})
                          .groupby('group_idx'), func)(**kwargs)
    else:
        grouped = pd.DataFrame({'group_idx': group_idx, 'a': a})\
                    .groupby('group_idx').aggregate(func, **kwargs)

    dtype = check_dtype(dtype, getattr(func, '__name__', func), a, size)
    ret = np.full(size, fill_value, dtype=dtype)
    ret[grouped.index] = grouped
    return ret