首页 > 解决方案 > 将新行分配给大熊猫 DataFrame 导致 OOM

问题描述

我有一个df像这样的DataFrame:

      0 1 2 3 4 5 ... 1154161
1     a b c d e f ... A
2     g h i j k l ... B
3     m n o p q r ... C
...
86405 Q V W X Y Z ... ZY

这是一个86405 rows × 1154161 columns数据框。请注意,索引从 开始1。我正在尝试分配一行index=0

df.loc[0] = 0

但我遇到了错误:

MemoryError: Unable to allocate 372. GiB for an array with shape (99725281205,) and data type float32

我希望它看起来像:

      0 1 2 3 4 5 ... 1154161
0     0 0 0 0 0 0 ... 0       <--- add this row
1     a b c d e f ... A
2     g h i j k l ... B
3     m n o p q r ... C
...
86405 Q V W X Y Z ... ZY

是否有另一种分配方式而不会耗尽内存?也许是大块的(最好不是)?

编辑:根据@hpaulj 请求添加 DataFrame 信息。

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1154161 entries, 0 to 1154160
Columns: 86405 entries, 1 to 86405
dtypes: float32(86405)
memory usage: 371.5 GB

EDIT2:请注意,示例 DataFrame 中的字母实际上是数字(float32)

标签: pythonpandasdataframenumpy

解决方案


1.https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#setting-with-enlargement

df.loc[len(df)] = 0
print (df)

2.https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

df = df.append(pd.Series(0, index=df.columns), ignore_index=True)

资料来源: 使用熊猫在数据框中添加一个空行


推荐阅读