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 s
(self, cls=None)
| 1031 | return self[:] |
| 1032 | |
| 1033 | def view(self, cls=None): |
| 1034 | """ |
| 1035 | Return a view of the Index with the specified dtype or a new Index instance. |
| 1036 | |
| 1037 | This method returns a view of the calling Index object if no arguments are |
| 1038 | provided. If a dtype is specified through the `cls` argument, it attempts |
| 1039 | to return a view of the Index with the specified dtype. Note that viewing |
| 1040 | the Index as a different dtype reinterprets the underlying data, which can |
| 1041 | lead to unexpected results for non-numeric or incompatible dtype conversions. |
| 1042 | |
| 1043 | Parameters |
| 1044 | ---------- |
| 1045 | cls : data-type or ndarray sub-class, optional |
| 1046 | Data-type descriptor of the returned view, e.g., float32 or int16. |
| 1047 | Omitting it results in the view having the same data-type as `self`. |
| 1048 | This argument can also be specified as an ndarray sub-class, |
| 1049 | e.g., np.int64 or np.float32 which then specifies the type of |
| 1050 | the returned object. |
| 1051 | |
| 1052 | Returns |
| 1053 | ------- |
| 1054 | Index or ndarray |
| 1055 | A view of the Index. If `cls` is None, the returned object is an Index |
| 1056 | view with the same dtype as the calling object. If a numeric `cls` is |
| 1057 | specified an ndarray view with the new dtype is returned. |
| 1058 | |
| 1059 | Raises |
| 1060 | ------ |
| 1061 | ValueError |
| 1062 | If attempting to change to a dtype in a way that is not compatible with |
| 1063 | the original dtype's memory layout, for example, viewing an 'int64' Index |
| 1064 | as 'str'. |
| 1065 | |
| 1066 | See Also |
| 1067 | -------- |
| 1068 | Index.copy : Returns a copy of the Index. |
| 1069 | numpy.ndarray.view : Returns a new view of array with the same data. |
| 1070 | |
| 1071 | Examples |
| 1072 | -------- |
| 1073 | >>> idx = pd.Index([-1, 0, 1]) |
| 1074 | >>> idx.view() |
| 1075 | Index([-1, 0, 1], dtype='int64') |
| 1076 | |
| 1077 | >>> idx.view(np.uint64) |
| 1078 | array([18446744073709551615, 0, 1], |
| 1079 | dtype=uint64) |
| 1080 | |
| 1081 | Viewing as 'int32' or 'float32' reinterprets the memory, which may lead to |
| 1082 | unexpected behavior: |
| 1083 | |
| 1084 | >>> idx.view("float32") |
| 1085 | array([ nan, nan, 0.e+00, 0.e+00, 1.e-45, 0.e+00], dtype=float32) |
| 1086 | """ |
| 1087 | # we need to see if we are subclassing an |
| 1088 | # index type here |
| 1089 | if cls is not None: |
| 1090 | dtype = cls |