@@ -1951,24 +1951,36 @@ def collapsed(self, dims_to_collapse=None):
19511951 if np .issubdtype (self .dtype , np .str_ ):
19521952 # Collapse the coordinate by serializing the points and
19531953 # bounds as strings.
1954- def serialize (x ):
1955- return "|" .join ([str (i ) for i in x .flatten ()])
1954+ def serialize (x , axis ):
1955+ if axis is None :
1956+ return "|" .join (x .flatten ())
1957+ # np.apply_along_axis does not work with str.join, so we
1958+ # need to loop through the array directly. First move (possibly
1959+ # multiple) axis of interest to trailing dims, then make a 2D
1960+ # array we can loop through.
1961+ work_array = np .moveaxis (x , axis , range (- len (axis ), 0 ))
1962+ out_shape = work_array .shape [: - len (axis )]
1963+ work_array = work_array .reshape (np .prod (out_shape ), - 1 )
1964+
1965+ joined = []
1966+ for arr_slice in work_array :
1967+ joined .append ("|" .join (arr_slice ))
1968+
1969+ return np .array (joined ).reshape (out_shape )
19561970
19571971 bounds = None
19581972 if self .has_bounds ():
1959- shape = self ._bounds_dm .shape [1 :]
1973+ shape = self ._bounds_dm .shape [- 1 :]
19601974 bounds = []
19611975 for index in np .ndindex (shape ):
19621976 index_slice = (slice (None ),) + tuple (index )
1963- bounds .append (serialize ( self . bounds [ index_slice ]))
1964- dtype = np . dtype ( "U{}" . format ( max ( map ( len , bounds ))) )
1965- bounds = np . array ( bounds , dtype = dtype ). reshape (( 1 ,) + shape )
1966- points = serialize ( self . points )
1967- dtype = np . dtype ( "U{}" . format ( len ( points )) )
1977+ bounds .append (
1978+ serialize ( self . bounds [ index_slice ], dims_to_collapse )
1979+ )
1980+ bounds = np . array ( bounds ). reshape (( 1 ,) + shape )
1981+ points = serialize ( self . points , dims_to_collapse )
19681982 # Create the new collapsed coordinate.
1969- coord = self .copy (
1970- points = np .array (points , dtype = dtype ), bounds = bounds
1971- )
1983+ coord = self .copy (points = np .array (points ), bounds = bounds )
19721984 else :
19731985 # Collapse the coordinate by calculating the bounded extremes.
19741986 if self .ndim > 1 :
0 commit comments