我试图根据另一个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'))
dtypes
可能导致内存分配膨胀。df1.index
是 Int64Index
int16
dtype.int8
是-128到128。 因为你的指数是0到130。int8
是不够的。price_combos
变量,然后再创建一个数据帧,会使用两倍的内存,所以创建一个 df2
没有中间步骤。dtype
,因为你正在做, dtype
将是 int64
df2
即2,180,905,112字节int64
每一个8GB的对象,总共16GB。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