【发布时间】:2020-05-03 12:55:18
【问题描述】:
我正在研究如何通过删除列来释放内存。
import numpy as np
import pandas as pd
big_df = pd.DataFrame(np.random.randn(100000,20))
big_df.memory_usage().sum()
> 16000128
现在有various ways 将列的子集复制 放入新的数据框。我们来看看其中几个的内存使用情况。
small_df = big_df[[0, 1]]
small_df.memory_usage().sum()
> 1600128
small_df_filtered = big_df.filter([0, 1], axis='columns')
small_df_filtered.memory_usage().sum()
> 1600128
small_df_copied = big_df[[0, 1]].copy()
small_df_copied.memory_usage().sum()
> 1600128
small_df_dropped = big_df.drop([0, 1], axis='columns')
small_df_dropped.memory_usage().sum()
> 14400128
small_df_dropped = big_df.drop([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], axis='columns')
small_df_dropped.memory_usage().sum()
> 1600128
添加deep=True 不会改变结果。
复制后添加del big_df 不会改变结果。
因此,这些较小的副本中没有一个比原始数据帧占用更少的内存,甚至更奇怪的删除 18 列保持内存不变,但删除 2 个增加内存。
发生了什么事?这些真的是副本吗?如果是这样,为什么它们不比原来的小?
【问题讨论】:
-
第一个切片少了一个数字。在复制时,大小保持与切片数据帧相同。
-
太棒了,冒着让我看起来像个白痴的风险,你可以把它写成答案@Vishnudev
标签: pandas