How to change dtype pandas DataFrame index to int32?

The default Dtype for the DataFrame index is 'int64' and I would like to change it to 'int32'. I tried changing it using .set_index () and the numpy int32 array, also tried to create a new index with dtype = np.int32. It did not work, always returning an int64 index.

Can someone show working code for creating pandas index with int32 size?

I am using the latest conda pandas 0.20.1 package.

+5
source share
2 answers

Not sure if this is something worth doing in practice, but the following should work:

class Int32Index(pd.Int64Index): _default_dtype = np.int32 @property def asi8(self): return self.values i = Int32Index(np.array([...], dtype='int32')) 

(from here )

+2
source

All the code paths I could find force dtype:

Check pandas.Index.__new__()

 if issubclass(data.dtype.type, np.integer): from .numeric import Int64Index return Int64Index(data, copy=copy, dtype=dtype, name=name) 

This allows us to pass dtype, but in NumericIndex().__new__() we have:

 if copy or not is_dtype_equal(data.dtype, cls._default_dtype): subarr = np.array(data, dtype=cls._default_dtype, copy=copy) 

What changes dtype.

+1
source

Source: https://habr.com/ru/post/1268060/


All Articles