我使用具有高内存使用率的大数据帧,我读到如果我更改重复值列上的 dtype,我可以节省大量内存。
我试过了,它确实将内存使用量降低了 25%,但后来我遇到了我无法理解的性能缓慢。
我在 dtype 'category' 列上进行分组聚合,在更改 dtype 之前大约需要 1 秒,更改之后大约需要 1 分钟。
此代码演示了 2 倍的性能下降:
import pandas as pd
import random
animals = ['Dog', 'Cat']
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday']
columns_dict = {'animals': [],
'days': []}
for i in range(1000000):
columns_dict['animals'].append(animals[random.randint(0, len(animals)-1)])
columns_dict['days'].append(days[random.randint(0, len(days)-1)])
# df without 'category' dtype
df = pd.DataFrame(columns_dict)
df.info(memory_usage='deep') # will result in memory usage of 95.5 MB
%timeit -n100 df.groupby('days').agg({'animals': 'first'})
# will result in: 100 loops, best of 3: 54.2 ms per loop
# df with 'category' dtype
df2 = df.copy()
df2['animals'] = df2['animals'].astype('category')
df2.info(memory_usage='deep') # will result in memory usage of 50.7 MB
%timeit -n100 df2.groupby('days').agg({'animals': 'first'})
# will result in: 100 loops, best of 3: 111 ms per loop
我试图理解的是这种缓慢的原因是什么,以及是否有办法克服它。
谢谢!