[英]force int32 as dtype instead of int64 in pandas load_csv with dtype and converters
[英]How to change index dtype of pandas DataFrame to int32?
DataFrame 索引的默認 dtype 是int64
,我想將其更改為int32
。
我嘗試使用pd.DataFrame.set_index
和 NumPy 數組int32
更改它,還嘗試使用dtype=np.int32
創建新索引。 它不起作用,總是返回int64
索引。
有人可以展示一個工作代碼來生成具有int32
大小的 Pandas 索引嗎?
我使用 conda Pandas v0.20.1。
不確定這在實踐中是否值得做,但以下應該有效:
class Int32Index(pd.Int64Index):
_default_dtype = np.int32
@property
def asi8(self):
return self.values
i = Int32Index(np.array([...], dtype='int32'))
(從這里)
我能找到的所有代碼路徑都強制使用 dtype:
pandas.Index.__new__()
入pandas.Index.__new__()
if issubclass(data.dtype.type, np.integer):
from .numeric import Int64Index
return Int64Index(data, copy=copy, dtype=dtype, name=name)
這允許傳遞NumericIndex().__new__()
,但在NumericIndex().__new__()
我們有:
if copy or not is_dtype_equal(data.dtype, cls._default_dtype):
subarr = np.array(data, dtype=cls._default_dtype, copy=copy)
這改變了dtype。
有人可以展示一個工作代碼來生成 int32 大小的熊貓索引嗎?
@PietroBattiston 的回答可能有效。 但是值得解釋為什么您通常不希望用Int64
/ Int32
索引替換默認RangeIndex
。
將邏輯存儲在一系列值后面比將每個整數存儲在一個范圍內占用的內存更少。 例如,當您將 Python 的內置range
與 NumPy np.arange
進行比較時,這一點應該很清楚。 如pd.RangeIndex
文檔中所述:
RangeIndex
是一個節省內存的特例Int64Index
不限於表示單調范圍。 在某些情況下,使用RangeIndex
可能會提高計算速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.