Skip to content

Error from Data.second_element for some data shapes #249

@davidhassell

Description

@davidhassell

For some Data shapes, the retrieval of the second element causes an error:

>>> import cfdm
>>> import numpy as np
>>> d = cfdm.Data(np.arange(6).reshape(1, 3, 2))  # This shape is OK
>>> d.array
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5]]])
>>> d.second_element()
1
>>> d = cfdm.Data(np.arange(6).reshape(1, 6, 1))  # Not OK
>>> d.second_element()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[51], line 1
----> 1 d.second_element()

File ~/cfdm/cfdm/data/data.py:3009, in Data.second_element(self)
   2981 def second_element(self):
   2982     """Return the second element of the data as a scalar.
   2983 
   2984     .. versionadded:: (cfdm) 1.7.0
   (...)
   3007 
   3008     """
-> 3009     return self._item(
   3010         (slice(0, 1, 1),) * (self.ndim - 1) + (slice(1, 2, 1),)
   3011     )

File ~/cfdm/cfdm/data/data.py:655, in Data._item(self, index)
    652 array = self[index].array
    654 if not numpy.ma.isMA(array):
--> 655     return array.item()
    657 mask = array.mask
    658 if mask is numpy.ma.nomask or not mask.item():

ValueError: can only convert an array of size 1 to a Python scalar
>>> cfdm.environment(paths=False)
Platform: Linux-5.15.0-67-generic-x86_64-with-glibc2.35
HDF5 library: 1.12.1
netcdf library: 4.8.1
Python: 3.10.9
netCDF4: 1.6.0
numpy: 1.22.3
cfdm.core: 1.10.0.3
cftime: 1.6.2
netcdf_flattener: 1.2.0
cfdm: 1.10.0.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions