python—如何迭代 Dataframe 并在其上运行函数

2j4z5cfb  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(208)

我将我的csv数据保存为数据框,我希望获取一行的值,然后在函数中使用它们。我会努力展示我在寻找什么。我尝试过按数量排序,但我能找出在这一步之后如何分离数据。我是Pandas队的新手,如果有任何有用的、与问题相关的反馈,我将不胜感激。
更新:如果你建议在 Dataframe 上使用.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
mrwjdhj3

mrwjdhj31#

你可以用这样的东西:

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...

相关问题