Python Pandas iterrows() 与前一个值

10

I have a pandas Dataframe in the form:

            A           B       K      S
2012-03-31  NaN         NaN     NaN    10
2012-04-30  62.74449    15.2    71.64   0
2012-05-31  2029.487    168.8   71.64   0
2012-06-30  170.7191    30.4    71.64   0

我将尝试创建一个函数,使用df['S'][index-1]的值替换df['S']。

例如:

for index,row in df.iterrows:
     if index = 1: 
         pass
     else:
         df['S'] = min(df['A'] + df['S'][index-1]?? - df['B'], df['K'])

but i dont know how to get df['S'][index - 1]


1
有关使用 iterrows() 处理当前/前一行,请参见 iterrows pandas get next rows value - xtian
3个回答

10

看起来你的初步回答已经很接近了。

以下代码应该可以正常运行:

for index, row in df.iterrows():
    if df.loc[index, 'S'] != 0:
        df.loc[index, 'S'] = df.loc[str(int(index) - 1), 'S']

基本上,对于除了第一个索引即0之外的所有索引,在“S”列中的值要更改为前一行中的值。注意:这假设数据帧具有顺序索引。

iterrows()方法不允许您仅通过调用该行来修改值,因此您需要使用df.loc()来标识数据帧中的单元格,然后更改其值。

还值得注意的是,index不是整数,因此使用int()函数减去1。这都在str()函数内完成,以便最终索引输出为预期的字符串。


4
< p > iterrows 的作用是逐行操作,因此您无法访问之前的行。无论如何,您的函数都会很慢,而有一个更快的方法:

df['S_shifted'] = df.S.shift()

compared = pd.concat([df['A'] + df['S_shifted'] - df['B'], df['K']], axis=1)

df['S'] = compared.min(axis=1)

In [29]: df['S']
Out[29]: 
2012-03-31         NaN
2012-04-30    57.54449
2012-05-31    71.64000
2012-06-30    71.64000
Name: S, dtype: float64

1
另一种方法可以是:

另一个方法是:

for (index, row), ii in zip(df.iterrows(), range(len(df.index))):
  # index: current row index
  # row: current row
  # df.iloc[ii-1]: prv row (of course make sure, prv row is present)
  # df.iloc[ii+1]: next row (of course make sure, next row is present)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接