【问题标题】:How can I iterate over a Pandas DataFrame and run a function over them如何遍历 Pandas DataFrame 并在它们上运行函数
【发布时间】:2021-09-19 04:20:53
【问题描述】:

我将 CSV 数据保存为数据框,我想获取一行的值,然后在函数中使用它们。我会尽力展示我在寻找什么。我已经尝试按金额排序,但我可以弄清楚如何在该步骤之后分离出数据。我是 Pandas 的新手,如果有任何有用的和与问题相关的反馈,我将不胜感激。

更新:如果您建议在数据框上使用 .apply,您能否向我展示一种应用复杂函数的好方法。 Pandas 文档仅显示了简单的函数,鉴于上下文,我认为这些函数没有用处。

这里是df

            Date   Amount
0     12/27/2019      NaN
1     12/27/2019   -14.00
2     12/27/2019   -15.27
3     12/30/2019    -1.00
4     12/30/2019   -35.01
5     12/30/2019    -9.99
6     01/02/2020    -7.57
7     01/03/2020  1225.36
8     01/03/2020   -40.00
9     01/03/2020   -59.90
10    01/03/2020    -9.52
11    01/06/2020   100.00
12    01/06/2020    -6.41
13    01/06/2020   -31.07
14    01/06/2020    -2.50
15    01/06/2020    -7.46
16    01/06/2020   -18.98
17    01/06/2020    -1.25
18    01/06/2020    -2.50
19    01/06/2020    -1.25
20    01/06/2020  -170.94
21    01/06/2020  -150.00
22    01/07/2020   -20.00
23    01/07/2020   -18.19
24    01/07/2020    -4.00
25    01/08/2020    -1.85
26    01/08/2020    -1.10
27    01/09/2020   -21.00
28    01/09/2020   -31.00
29    01/09/2020    -7.13
30    01/10/2020   -10.00
31    01/10/2020    -1.75
32    01/10/2020  -125.00
33    01/13/2020   -10.60
34    01/13/2020    -2.50
35    01/13/2020    -7.00
36    01/13/2020   -46.32
37    01/13/2020    -1.25
38    01/13/2020   -39.04
39    01/13/2020    -9.46
40    01/13/2020  -179.00
41    01/13/2020  -140.00
42    01/15/2020  -150.04

我想从一行中获取金额值,然后查找匹配的金额值。一旦找到匹配值,我想在具有匹配值的两行之间运行 timedelta。

到目前为止,每次我尝试某种条件语句时都会出错。有谁知道我如何能够完成这项任务?

这是我开始使用的一些代码。


amount_1 = df.loc[1, 'Amount']
amount_2 = df.loc[2, 'Amount']
print(amount_1, amount_2)

date_1 = df.loc[2, 'Date'] #skipping the first row.
x = 2
x += 1
date_2 = df.loc[x, 'Date']


## Not real code, but a logical flow I am aiming for

if amount_2 == amount_1:
   timed = date_2 - date_1
   print(timed, amount_2)

elif amount_2 != amount_1:
  # go to the next row and check


【问题讨论】:

  • 你不能按数量分组吗?他们将有相同的金额,但您可以找到不同的日期。
  • 您需要创建所需的函数,然后将其传递给 pandas 中的 .apply() 函数。 pandas.pydata.org/pandas-docs/stable/reference/api/…
  • @PraysonW.Daniel 我知道如何按数量排序,但我不知道如何从排序后的格式中提取我需要的信息。
  • @Geom 我去看看,谢谢建议

标签: python pandas algorithm dataframe loops


【解决方案1】:

你可以使用类似的东西:

distinct_values = df["Amount"].unique()  # Select all distinct values

for value_unique in distinct_values:  # for each distinct value
    temp_df = df.loc[df["Amount"] == value_unique]  # find rows of that value

    # You could iterate over that temp df to do your timedelta operations...

【讨论】:

  • 您会建议使用 while 语句进行迭代吗?
猜你喜欢
  • 1970-01-01
  • 2022-10-25
  • 2018-12-28
  • 2014-10-17
  • 2012-05-30
相关资源
最近更新 更多