Python将iterrows()与以前的值合并
我有一个熊猫数据框,格式如下:Python将iterrows()与以前的值合并,python,for-loop,pandas,dataframe,Python,For Loop,Pandas,Dataframe,我有一个熊猫数据框,格式如下: 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'][inde
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'])
但是我不知道如何获取df['S'][index-1]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
看起来你的初步答案很接近 以下方面应起作用:
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()
函数中,因此最终的索引输出是一个字符串,正如预期的那样。对于使用iterrows()
的当前/上一行,请参见。