通过循环索引条件使用前一行值

时间:2018-03-15 09:25:43

标签: python pandas loops if-statement dataframe

如果我的数据框是x列。 我想创建一个新列x_new但我希望将此新列的第一行设置为特定数字(假设为-2)。 然后从第2行开始,使用前一行来迭代cx函数

data = {'x':[1,2,3,4,5]}
df=pd.DataFrame(data)

def cx(x):
   if df.loc[1,'x_new']==0:
      df.loc[1,'x_new']= -2
   else:
      x_new = -10*x + 2
   return x_new

df['x_new']=(cx(df['x']))

最终数据框

enter image description here

我不确定如何做到这一点。 谢谢你的帮助

2 个答案:

答案 0 :(得分:0)

我会通过使用循环来生成新数据来做到这一点 - 如果特别大但可能不是理想的但它是一个快速操作。让我知道你是如何继续这样做的:

data = {'depth':[1,2,3,4,5]}
df=pd.DataFrame(data)

res = data['depth']
res[0] = -5.63
for i in range(1, len(res)):
    res[i] = -3 * res[i-1] + 1

df['new_depth'] = res
print(df)

获得

   depth  new_depth
0      1      -5.63
1      2      17.89
2      3     -52.67
3      4     159.01
4      5    -476.03

答案 1 :(得分:0)

这是我到目前为止所做的:

data = {'depth':[1,2,3,4,5]}
df=pd.DataFrame(data)
df

# calculate equation
def depth_cal(d):
    z = -3*d+1 #d must be previous row
    return z

depth_cal=(depth_cal(df['depth'])) # how to set d as previous row
print (depth_cal)

depth_new =[]
for row in df['depth']:
    if row == 1:
        depth_new.append('-5.63')
    else:
        depth_new.append(depth_cal) #Does not put list in a column

    df['Depth_correct']= depth_new

correct output:

这还有两个问题: 1.它没有将depth_cal列表正确放入列中 2.在depth_cal函数中,我希望d成为前一行 谢谢