Python中的apply函数报错 – 对象不可迭代

huangapple go评论113阅读模式
英文:

apply function in Python throws the error - object not iterable

问题

我在应用函数时遇到了错误。对于每个条件,我应该在当前行中参考前一行的值以及当前行中的下一行值。如果我有多个引用前一行值的情况,那么就会出现错误。请建议我以不同的方式解决这个问题。

  1. import pandas as pd
  2. data = {
  3. 'A': [1, 1, 1, 1, 1],
  4. 'B': [6, 7, 8, 9, 10]
  5. }
  6. df = pd.DataFrame(data)
  7. # 定义一个自定义函数,使用前一行和后一行的值
  8. def process_row(row):
  9. previous_row = df.shift(1).loc[row.name]
  10. next_row = df.shift(-1).loc[row.name]
  11. # 访问前一行和后一行的值
  12. prev_value_A = previous_row['A']
  13. prev_value_B = previous_row['B']
  14. next_value_A = next_row['A']
  15. next_value_B = next_row['B']
  16. # 使用前一行和后一行的值进行计算
  17. result = {}
  18. result['x'] = ((prev_value_B - prev_value_A) - (next_value_B - next_value_A))
  19. return result
  20. # 将该函数应用于DataFrame中的每一行
  21. df = df.apply(process_row, axis=1)
  22. print(df)
英文:

I am getting an error while applying a function. For each condition, I am supposed to refer to the previous row values and also the next values while present in the current row. If i have more than one reference of previous row values, then it is giving an error. Please advise how do i fix this in a different way.

  1. import pandas as pd
  2. data = {
  3. 'A': [1, 1, 1, 1, 1],
  4. 'B': [6, 7, 8, 9, 10]
  5. }
  6. df = pd.DataFrame(data)
  7. # Define a custom function that uses values from the previous and next rows
  8. def process_row(row):
  9. previous_row = df.shift(1).loc[row.name]
  10. next_row = df.shift(-1).loc[row.name]
  11. # Access values from previous and next rows
  12. prev_value_A = previous_row['A']
  13. prev_value_B = previous_row['B']
  14. next_value_A = next_row['A']
  15. next_value_B = next_row['B']
  16. # Perform calculations using previous and next values
  17. result = {}
  18. result['x'] = ((prev_value_B - prev_value_A) - (next_value_B - next_value_A))
  19. return result
  20. # Apply the function to each row in the DataFrame
  21. df = df.apply(process_row, axis=1)
  22. print(df)

答案1

得分: 2

你不应该使用函数和 apply 来实现这个,直接使用 shift 来向量化你的计算:

  1. s = df['B'] - df['A']
  2. df['x'] = s.shift() - s.shift(-1)

输出:

  1. A B x
  2. 0 1 6 NaN
  3. 1 1 7 -2.0
  4. 2 1 8 -2.0
  5. 3 1 9 -2.0
  6. 4 1 10 NaN
英文:

You shouldn't use a function and apply for that, directly vectorize your calculation with shift:

  1. s = df['B']-df['A']
  2. df['x'] = s.shift()-s.shift(-1)

Output:

  1. A B x
  2. 0 1 6 NaN
  3. 1 1 7 -2.0
  4. 2 1 8 -2.0
  5. 3 1 9 -2.0
  6. 4 1 10 NaN

huangapple
  • 本文由 发表于 2023年7月6日 19:45:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定