小编sch*_*wim的帖子

使用切片列表从 DataFrame 中获取行

我有一个数百万行的数据框,以及一个我需要从中选择的有趣部分的列表。我正在寻找一种高效(读作:最快)的方法来做到这一点。

我知道我可以这样做:

slices = [slice(0,10), slice(20,50), slice(1000,5000)]
for slice in slices:
  df.loc[slice, 'somecolumn'] = True
Run Code Online (Sandbox Code Playgroud)

...但这似乎是完成工作的一种低效方式。这是真的慢。

这似乎比上面的 for 循环更快,但我不确定这是否是最好的方法:

from itertools import chain
ranges = chain.from_iterable(slices)
df.loc[ranges, 'somecolumns'] = True
Run Code Online (Sandbox Code Playgroud)

这也不起作用,即使它似乎应该:

df.loc[slices, 'somecolumns'] = True

TypeError: unhashable type: 'slice'
Run Code Online (Sandbox Code Playgroud)

我在这方面主要关心的是性能。由于我正在处理的数据框的大小,我需要最好的方法。

python indexing performance dataframe pandas

1
推荐指数
1
解决办法
1255
查看次数

标签 统计

dataframe ×1

indexing ×1

pandas ×1

performance ×1

python ×1