Pandas 操作 DataFrame 就地与非就地(就地 = True vs False)

Ell*_*est 5 python memory pandas

我想知道如果有一个在内存使用量的显著减少,当我们选择操作就地一个数据帧(相对于不就地)。

我在 Stack Overflow 上做了一些搜索,发现了这篇文章,其中的答案指出,如果操作没有就地完成,则会返回数据帧的副本(我想这在有可选参数时有点明显)称为“就地”:P)。

如果我不需要保留原始数据框,那么只修改数据框是有益的(并且合乎逻辑的),对吗?

语境:

当按数据框中的特定“列”排序时,我试图获取顶部元素。我想知道这两个中哪一个更有效:

到位:

df.sort('some_column', ascending=0, inplace=1)
top = df.iloc[0]
Run Code Online (Sandbox Code Playgroud)

对比

复制:

top = df.sort('some_column', ascending=0).iloc[0]
Run Code Online (Sandbox Code Playgroud)

For the 'copy' case, it still allocates memory in making the copy when sorting even though I'm not assigning the copy to a variable right? If so, how long does it take to deallocate that copy from memory?

Thanks for any insights in advance!

cs9*_*s95 7

inplace=True一般来说,显式副本和返回显式副本之间没有区别- 在这两种情况下,都会创建副本。恰好,在第一种情况下,副本中的数据被复制回原始df对象中,因此不需要重新分配。

此外,请注意,从 开始v0.21, ,df.sort已被弃用,请sort_values改用。