如何引用row_iterator Pandas中的另一行?

时间:2014-06-28 09:15:25

标签: python pandas

我有以下代码

row_iterator = temp.iterrows()
for i, row in row_iterator:
    row['InterE'] = row['xs'] - (row['xs'] - row['InterS']) * exp(-row['ak1'])
    if row['InterE'][:-1] < 1:
        row['InterS'] = row['InterE'][:-1]
    else:
        row['InterS'] = row['InterE'][:-1] - row['InterE'][:-1] * row['xi'][:-1]

但是它返回了以下错误:

invalid index to scalar variable.

你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

你应该避免迭代,特别是当你可以矢量化操作时。

所以

# calculate 'InterE' column for entire dataframe
temp['InterE'] = temp['xs'] - (temp['xs'] - temp['InterS']) * exp(-temp['ak1'])
# now for those values less than 1 assign the previous row value, this is what shift does
temp.loc[temp['InterE'] < 1, 'InterS'] = temp['InterE'].shift(-1)
# for the other condition perform the alternative calculation and assign
temp.loc[temp['InterE'] >=1, 'InterS'] = temp['InterE'].shift(-1) - (temp['InterE'].shift(-1) * temp['xi'].shift(-1))

让我知道这是否符合您的要求,如果没有,则发布数据和所需的输出