itertools.permutations的Pandas数据框架索引使用了太多的内存。

问题描述 投票:3回答:1

我试图根据另一个Dataframe的组合来制作一个新的Dataframe。 这里是原始Dataframe。 价格是指数。

df1
Price     Bid   Ask
1          .01   .05
2          .04   .08
3          .1    .15  
.           .      .
130        2.50  3.00

第二个Dataframe是为了从df1中提取指数,并创建一个Dataframe(df2),它是基于4个价格的df1指数的变体,如下面的例子输出。

df2
 #     price1   price2   price 3  price 4
 1       1        2         3       4
 2       1        2         3       5
 3       1        2         3       6
 ..       ..       ..        ..      ..

为了达到这个目的,我使用了 itertools.permutation但我遇到了内存问题,无法执行大量的排列组合。 这是我用来进行排列组合的代码。

price_combos = list(x for x in itertools.permutations(df1.index, 4))
df2 = pd.DataFrame(price_combos , columns=('price1', 'price2', 'price3', 'price4'))                                       
python pandas numpy dataframe itertools
1个回答
1
投票
  • dtypes 可能导致内存分配膨胀。
    • 导致内存分配膨胀。df1.indexInt64Index
    • 我找到的最好的办法是,针对你的情况,将数据框的索引设置为一个numpy数组,并在数组中加入一个 int16 dtype.
      • 的数值范围。int8 是-128到128。 因为你的指数是0到130。int8 是不够的。
    • 创建一个 price_combos 变量,然后再创建一个数据帧,会使用两倍的内存,所以创建一个 df2 没有中间步骤。
    • 如果你在创建数据帧时没有指定数据帧的 dtype,因为你正在做, dtype 将是 int64
    • 通过下面的实施,将有一个对象。df2即2,180,905,112字节
      • 在原来的实施方式下,会有两个 int64 每一个8GB的对象,总共16GB。
  • 如果你使用的是Jupyter,它的内存管理很糟糕。
  • 也许增加虚拟内存swap文件的大小,会给你提供额外的缓冲区需要的内存。虚拟内存是Windows的,swap文件是Linux的。这很容易做到,只要Google一下就可以了。
import numpy as np
import pandas a pd
from itertools import permutations

# synthetic data set and create dataframe
np.random.seed(365)
data = {'Price': list(range(1, 131)),
        'Bid': [np.random.randint(1, 10)*0.1 for _ in range(130)]}

df1 = pd.DataFrame(data)
df1['Ask'] = df1.Bid + 0.15
df1.set_index('Price', inplace=True)

# convert the index to an int16 array
values = df1.index.to_numpy(dtype='int16')

# create df2
%%time
df2 = pd.DataFrame(np.array(list(permutations(values, 4))), columns=('price1', 'price2', 'price3', 'price4')) 
>>> Wall time: 2min 45s

print(df2.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 272613120 entries, 0 to 272613119
Data columns (total 4 columns):
 #   Column  Dtype
---  ------  -----
 0   price1  int16
 1   price2  int16
 2   price3  int16
 3   price4  int16
dtypes: int16(4)
memory usage: 2.0 GB

df2.head()

   price1  price2  price3  price4
0       1       2       3       4
1       1       2       3       5
2       1       2       3       6
3       1       2       3       7
4       1       2       3       8

df2.tail()

           price1  price2  price3  price4
272613115     130     129     128     123
272613116     130     129     128     124
272613117     130     129     128     125
272613118     130     129     128     126
272613119     130     129     128     127
© www.soinside.com 2019 - 2024. All rights reserved.