应用需要列中其他值的函数?

Applying a function which requires other values from a column?

我正在尝试创建一个非常简单的模型来检查给定周与前一周的能源价格比较。所以我在整个熊猫数据框中应用了一个函数。我正在努力解决的问题是在列中获取较早的值。我已将索引转移到另一列(称为计数器),因此我可以使用它来减去偏移量。我可以使用它来获得所需的位置,但我无法从该 int 转到列中的值。我知道第一个值会产生错误(加上原始数据中的一些缺失值),所以我使用 try/except 并且我收集了额外的数据,这样一开始就不会出现一些 NaN 的问题。

def u(df):
if df['Weekday'] in {0,1,4,5,6}: # For Mon, Tue, Thur, Fri, Sat & Sun one week shift
    offset=168
else:
    offset=24
position=df['Counter']-offset    
try:
    
    oldprice=df.iat[position,'Price'] #Never works, always leads to exception
    
except:
    oldprice = np.nan

try:
    olddemand =df.iat[position,'Demand']
except:
    olddemand = np.nan

print(oldprice)
newdemand = df['Demand']
currentprice =df['Price']
expprice=oldprice*(olddemand/newdemand)
u=currentprice-expprice
return u


results=df2.apply(u,axis=1)

问题是尝试永远不会成功,我得到了全面的 NaN(我也尝试通过将异常设置为 1000 并获得高值)。柜台似乎工作正常。我早些时候打印了它,它的行为符合预期并且是一个整数。我也试过 .at 但没有成功。谢谢你的时间。

目前,对于 axis=1,您的函数 u() 使用的参数不是整个 DataFrame,而是单个行,因此您无法访问其他行。一种解决方案是将整个 DataFrame 作为参数传递。您的函数 u() 将变为:

def u(row, df):
    if row['Weekday'] in {0, 1, 4, 5, 6}:  # For Mon, Tue, Thur, Fri, Sat & Sun one week shift
        offset = 168
    else:
        offset = 24

    position = row['Counter'] - offset
    try:

        oldprice = df.loc[position]['Price']

    except:
        oldprice = np.nan

    try:
        olddemand = df.loc[position]['Demand']
    except:
        olddemand = np.nan

    print(oldprice)
    newdemand = row['Demand']
    currentprice = row['Price']
    expprice = oldprice * (olddemand / newdemand)
    u = currentprice - expprice
    return u

为了传递数据帧,您需要添加 arg :

results = df2.apply(u, args=(df2,), axis=1)

请注意,如果没有您的数据样本,我无法确保输出是正确的。