【问题标题】:inplace version of DataFrame.head() in pandas熊猫中 DataFrame.head() 的就地版本
【发布时间】:2019-03-15 13:10:52
【问题描述】:

pandas 中是否有 df.head(max_rows) 的就地版本?

当数据框中的行数太多而无法处理时,我需要限制它们的数量。

目前我正在做df = df.head(10000000),但我认为这是内存效率低下。

【问题讨论】:

  • 我不明白这点,但In [2]: import pandas as pd In [3]: pd.options.display.max_rows Out[3]: 60
  • 请看下面的答案,如果你想硬编码要显示的行,它会更干净,这是熊猫提供的干净利落
  • this的可能重复

标签: python pandas performance indexing in-place


【解决方案1】:

您可以使用pd.DataFrame.drop 进行就地操作:

n = 10000000
df.drop(df.index[n:], inplace=True)

但这可能无济于事。根据@unutbu's comment

df.drop(..., inplace=True) 确实就地修改了df,但由于 方式inplace操作是在Pandas中实现的,没有真正的 这样做比更直接地重新分配到 变量名。我个人更喜欢返回值的函数 修改值的函数,因为前者是赋值 语法让修改内容一目了然。

这在Jeff's answer 中有进一步解释。

此外,请注意此方法不适用于重复索引。

【讨论】:

  • 这种方法也不适用于重复索引
  • @Donbeo,正确,我将其添加为免责声明。
  • 抱歉,您有参考解释为什么 inplace 会起作用吗?
  • 对不起,我想知道您是否可以澄清/解释声明ut due to the way inplace operations are implemented in Pandas, there is no real advantage to doing
  • @Donbeo,查看我添加的链接
猜你喜欢
  • 1970-01-01
  • 2017-10-09
  • 2018-04-25
  • 1970-01-01
  • 2016-11-03
  • 2018-12-20
相关资源
最近更新 更多