【问题标题】:Iteration over a Pandas DataFrame [duplicate]迭代 Pandas DataFrame [重复]
【发布时间】:2020-01-03 05:27:27
【问题描述】:

迭代 DataFrame 的(最佳实践)正确方法是什么?

我正在使用:

for i in range(working.shape[0]):
    for j in range(1, working.shape[1]):
        working.iloc[i,j] = (100 - working.iloc[i,j])*100

以上是正确的,但与其他 Stack Overflow 答案不一致。我希望有人能解释为什么上面不是最优的,并提出一个更好的实现。

总的来说,我在编程方面非常新手,尤其是在 Pandas 方面。也很抱歉问了一个已经在 SF 上解决的问题:虽然我并没有真正理解这个问题的常规答案。可能重复,但这个答案对于新手来说很容易理解,如果不太全面的话。

【问题讨论】:

  • 太棒了,非常感谢!但是,我的代码省略了第一列 - 我可以更有选择性地使用 applymap 吗?
  • 查看answer 了解有关如何不迭代数据帧的更多信息

标签: python pandas dataframe for-loop iteration


【解决方案1】:

迭代 DataFrame 的(最佳实践)正确方法是什么?

有几种方法(例如iterrows),但一般来说,您应该不惜一切代价尽量避免迭代。 pandas 提供了几种用于矢量化操作的工具,这些工具几乎总是比迭代解决方案更快。

您提供的示例可以使用iloc按以下方式矢量化:

working.iloc[:, 1:] = (100 - working.iloc[:, 1:]) * 100

一些时间安排:

from timeit import Timer

working = pd.DataFrame({'a': range(50), 'b': range(50)})


def iteration():
    for i in range(working.shape[0]):
        for j in range(1, working.shape[1]):
            working.iloc[i, j] = (100 - working.iloc[i, j]) * 100


def direct():
    # in actual code you will have to assign back to working.iloc[:, 1:]
    (100 - working.iloc[:, 1:]) * 100


print(min(Timer(iteration).repeat(50, 50)))
print(min(Timer(direct).repeat(50, 50)))

输出

0.38473859999999993
0.05334049999999735

7 因素差异,只有 50 行。

【讨论】:

  • 太棒了,非常感谢!但是,我的代码省略了第一列 - 我可以更有选择性地使用 applymap 吗?
  • 非常感谢各位 - 谢谢。
猜你喜欢
  • 2021-12-24
  • 2021-12-28
  • 2018-10-13
  • 2013-09-02
  • 2017-08-23
  • 1970-01-01
  • 2019-03-19
  • 2018-08-03
  • 2018-04-30
相关资源
最近更新 更多