pandas.Index.view#
- Index.view(cls=None)[source]#
Return a view of the Index with the specified dtype or a new Index instance.
This method returns a view of the calling Index object if no arguments are provided. If a dtype is specified through the cls argument, it attempts to return a view of the Index with the specified dtype. Note that viewing the Index as a different dtype reinterprets the underlying data, which can lead to unexpected results for non-numeric or incompatible dtype conversions.
- Parameters:
- clsdata-type or ndarray sub-class, optional
Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as self. This argument can also be specified as an ndarray sub-class, e.g., np.int64 or np.float32 which then specifies the type of the returned object.
- Returns:
- Index or ndarray
A view of the Index. If cls is None, the returned object is an Index view with the same dtype as the calling object. If a numeric cls is specified an ndarray view with the new dtype is returned.
- Raises:
- ValueError
If attempting to change to a dtype in a way that is not compatible with the original dtype’s memory layout, for example, viewing an ‘int64’ Index as ‘str’.
See also
Index.copy
Returns a copy of the Index.
numpy.ndarray.view
Returns a new view of array with the same data.
Examples
>>> idx = pd.Index([-1, 0, 1]) >>> idx.view() Index([-1, 0, 1], dtype='int64')
>>> idx.view(np.uint64) array([18446744073709551615, 0, 1], dtype=uint64)
Viewing as ‘int32’ or ‘float32’ reinterprets the memory, which may lead to unexpected behavior:
>>> idx.view("float32") array([ nan, nan, 0.e+00, 0.e+00, 1.e-45, 0.e+00], dtype=float32)