Python 减少专用于数据类型=对象的内存

Python 减少专用于数据类型=对象的内存,python,pandas,object,memory,Python,Pandas,Object,Memory,是否可以在Python中为对象数据类型设置自定义长度? 例如,在我的测试数据框中,一列dtyp=object会将其大小增加约60%。尽管此列中的值仅为“Y”或“N” 传递memory_usage='deep'将启用更准确的内存使用情况报告,该报告将说明所包含对象的全部使用情况 数据类型:datetime64ns、float64(8)、int16(2)、int8(4)、object(1) 内存使用率:14.7 MB df.info() 数据类型:datetime64ns、float64(8)、i

是否可以在Python中为对象数据类型设置自定义长度? 例如,在我的测试数据框中,一列dtyp=object会将其大小增加约60%。尽管此列中的值仅为“Y”或“N”

传递memory_usage='deep'将启用更准确的内存使用情况报告,该报告将说明所包含对象的全部使用情况

数据类型:datetime64ns、float64(8)、int16(2)、int8(4)、object(1) 内存使用率:14.7 MB

df.info()
数据类型:datetime64ns、float64(8)、int16(2)、int8(4)、object(1) 内存使用率:9.2+MB

df.info()

这看起来内存效率非常低,但我找不到任何选项/数据类型,这可能会减小大小。(例如,像int8而不是int64)

处理这个问题的最佳方法是使用。它将使用
int8
存储值

df = pd.DataFrame({'A': np.random.choice(['Y', 'N'], size=10**6)})
df.info(memory_usage='deep')
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000000 entries, 0 to 999999
Data columns (total 1 columns):
A    1000000 non-null object
dtypes: object(1)
memory usage: 62.9 MB

df.info(内存使用率='deep')
范围索引:1000000个条目,0到999999
数据列(共1列):
1000000非空类别
数据类型:类别(1)
内存使用率:976.8 KB

谢谢,它解决了所有问题。刚才有点困惑,read_csv不支持“category”,但这是因为我的语法不好。@GrinvydasKareiva不客气。对于read_csv,我认为对分类的支持始于0.19版。还要确保你有最新的版本。
df['A'] = df['A'].astype('category')
df.info(memory_usage='deep')
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000000 entries, 0 to 999999
Data columns (total 1 columns):
A    1000000 non-null category
dtypes: category(1)
memory usage: 976.8 KB