【问题标题】:How to do a calculation on each line of a pandas dataframe in python?如何在python中对熊猫数据框的每一行进行计算?
【发布时间】:2018-07-19 19:04:19
【问题描述】:

我是 python 的新手,我正在尝试将我在 R 中创建的函数转换为 Python,此处描述的 R 函数:

How to optimize this process?

从我的阅读看来,在 python 中执行此操作的最佳方法是使用采用以下形式的 for 循环

for line 1 in probe test
 find user in U_lookup
 find movie in M_lookup
 take the value found in U_lookup and retrieve that line number from knn_text
 take the values found in that row of knn_text, and retrieve the line numbers from dfm
 for those line numbers in dfm, retrieve column=U_lookup
 take the average of the non zero values found
 save value into pandas datafame in new column for that line

这是完成此类操作的最有效(就计算速度而言)方法吗?来自 R,所以我不确定 pandas 包中是否有更好的功能。

作为后续,python 中是否有与 R 中的函数 dput() 等效的函数? dput 本质上提供了代码来轻松共享此类问题的数据子集。

【问题讨论】:

  • 谷歌你的问题,google.com/…
  • 循环几乎肯定不是最有效的方法。您可能想要pandas.merge 或只是一个简单的映射,但如果您想要一个详细的答案,您需要创建一个minimal reproducible example。

标签: python pandas for-loop


【解决方案1】:

您可以使用df.apply(my_func, axis=1) 将函数/计算应用于数据帧的每一行。 其中,my_func 将包含所需的计算

【讨论】:

    猜你喜欢
    • 2022-12-17
    • 2015-10-07
    • 2020-11-14
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多