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

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

apply function in Python throws the error - object not iterable

问题

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

import pandas as pd

data = {
    'A': [1, 1, 1, 1, 1],
    'B': [6, 7, 8, 9, 10]
}
df = pd.DataFrame(data)

# 定义一个自定义函数,使用前一行和后一行的值
def process_row(row):
    previous_row = df.shift(1).loc[row.name]
    next_row = df.shift(-1).loc[row.name]
    
    # 访问前一行和后一行的值
    prev_value_A = previous_row['A']
    prev_value_B = previous_row['B']
    next_value_A = next_row['A']
    next_value_B = next_row['B']
    
    # 使用前一行和后一行的值进行计算
    result = {}
    result['x'] = ((prev_value_B - prev_value_A) - (next_value_B - next_value_A))
    
    return result

# 将该函数应用于DataFrame中的每一行
df = df.apply(process_row, axis=1)

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.

import pandas as pd

data = {
    'A': [1, 1, 1, 1, 1],
    'B': [6, 7, 8, 9, 10]
}
df = pd.DataFrame(data)

# Define a custom function that uses values from the previous and next rows
def process_row(row):
    previous_row = df.shift(1).loc[row.name]
    next_row = df.shift(-1).loc[row.name]
    
    # Access values from previous and next rows
    prev_value_A = previous_row['A']
    prev_value_B = previous_row['B']
    next_value_A = next_row['A']
    next_value_B = next_row['B']
    
    # Perform  calculations using previous and next values
    result = {}
    result['x'] = ((prev_value_B - prev_value_A) - (next_value_B - next_value_A))
    
    return result

# Apply the function to each row in the DataFrame
df = df.apply(process_row, axis=1)

print(df)

答案1

得分: 2

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

s = df['B'] - df['A']

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

输出:

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

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

s = df['B']-df['A']

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

Output:

   A   B    x
0  1   6  NaN
1  1   7 -2.0
2  1   8 -2.0
3  1   9 -2.0
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:

确定