Skip to content

Supprising type of nc.variables[foo][:]. (ndarray or MaskedArray depending on its data) #785

@MeraX

Description

@MeraX

Hi all,

for me it is surprising, that the return of nc.variables[foo][:] is either a ndarray or a MaskedArray depending on its data content: MaskedArrays are used as long as there is any "missing" entry in the data, ndarray otherwise. Even more surprising this data depending rules also apply to slices:

import netCDF4
import numpy as np

print(netCDF4.__version__)

with netCDF4.Dataset('test.nc', 'w') as nc:
    dim = 'test'
    nc.createDimension(dim, size=10)

    var = nc.createVariable('test-var', np.int,
        dim, fill_value=5)
    var[:] = np.arange(10)
    print('var[:]', var[:], type(var[:]))
    print('var[:5]', var[:5], type(var[:5]))
    print('var[:6]', var[:6], type(var[:6]))

output:

1.3.1
var[:] [0 1 2 3 4 -- -- -- -- --] <class 'numpy.ma.core.MaskedArray'>
var[:5] [0 1 2 3 4] <class 'numpy.ndarray'>
var[:6] [0 1 2 3 4 --] <class 'numpy.ma.core.MaskedArray'>

On the first glance it might seem convenient to get a MaskedArray, only if there is any missing data, but it confuses me very much, that one slice has another type (and behavior) as the other. And it is the same for the whole [:]: Imagine one day-file with missing entries, but another day without any.

If one likes to work with MaskedArrays, this means that one always have to check for the type and add a full False mask in case of no missing entries.

Is there any chance to make the return of var[:] more consistent and less surprising?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions