【问题标题】:fillna method is slower for square bracket column selection than loc for pandas dataframe对于方括号列选择,fillna 方法比熊猫数据框的 loc 方法慢
【发布时间】:2021-10-23 17:04:06
【问题描述】:

我发现对于 pandas 数据框的不同列选择技术,fillna 的处理时间存在显着差异。

数据帧的fillna 花费的时间,其列是使用loc 选择的

df1 = df.copy()
t1 = time.time()
df1.loc[:, col] = df1.loc[:, col].fillna(method="ffill")
t2 = time.time()
print(t2-t1)

3.908552885055542

fillna 的数据帧所用的时间,其列是使用方括号选择的:

df1 = df.copy()
t1 = time.time()
df1[col] = df1[col].fillna(method="ffill")
t2 = time.time()
print(t2-t1)

223.85472440719604

这个post 建议使用 loc 和方括号进行列选择是相似的:-
选择列列表 (df[['A', 'B', 'C']] 是一样的as df.loc[:, ['A', 'B', 'C']] -> 选择列 A、B 和 C)

谁能帮忙解释一下为什么会有时差?谢谢!!

【问题讨论】:

  • 我测试了一下,结果差不多;您的测试中可能有问题。也许如果您为此观察提供样本数据,那么我们可以重现这种巨大的差异
  • 在我自己的数据上用%%timeit 做的,.loc[col] 是 680us 而[col] 是 396us。
  • 我上传了示例数据框file[col] 10 秒而 loc[col] 0.3 秒对于此示例数据
  • 数据框索引一项复杂的任务,涉及索引和列数组。它比numpy 使用位置和紧凑多维数组的索引涉及更多。首先,您可以查看 df.__getitiem__ 以查看启动索引的代码(可能是 python)。

标签: python pandas dataframe numpy fillna


【解决方案1】:

我在 2014 年收集了几个点,而我正在测试超过 200 万行。我从 SO 线程中发现它很有趣,我收集如下。

一般来说,您应该使用 loc 进行基于标签的分配,使用 iloc 进行基于整数/位置的分配,因为规范保证它们始终在原始值上运行。

最好看select a subset of a DataFrame

- loc is faster, because it does not try to create a copy of the data.

- loc is meant to modify your existing dataframe inplace, which is more memory efficient.

- loc is predictable, it has one behavior.

- df.loc's syntax is explicit, with df.loc[indexer] you know automatically that df.loc is selecting rows. In contrast, it is not clear if df[indexer] will select rows or columns (or raise ValueError) without knowing details about indexer and df.

当使用loc

df.loc[:] = 数据框

df.loc[int] = Dataframe 如果您有多个列,Series 如果您在数据框中只有 1 列

df.loc[:, ["col_name"]] = Dataframe 如果您有不止一行,Series 如果您只有 1 行选择

df.loc[:, "col_name"] = 系列

不使用loc

df["col_name"] = 系列

df[["col_name"]] = 数据框

查看here for some interesting details在使用和不使用 .loc 的情况下对多列“链式分配”的性能考虑

【讨论】:

  • 没有真正回答问题
  • sammywemmy,这更多是与性能相关的问题,可能无法直接回答,但可以提供一些提示和用例,我已经看到了对此的讨论,并看到许多冠军有自己的看法根据他们的用例,这是我的答案部分下的内容,因为我不能把这些学习放在 cmets 上,希望你能明白!
猜你喜欢
  • 2018-10-25
  • 1970-01-01
  • 2022-10-04
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
相关资源
最近更新 更多