在逐行迭代时更新 Pandas 中的数据帧 [英] Update a dataframe in pandas while iterating row by row
问题描述
我有一个看起来像这样的 Pandas 数据框(它非常大)
I have a pandas data frame that looks like this (its a pretty big one)
date exer exp ifor mat
1092 2014-03-17 American M 528.205 2014-04-19
1093 2014-03-17 American M 528.205 2014-04-19
1094 2014-03-17 American M 528.205 2014-04-19
1095 2014-03-17 American M 528.205 2014-04-19
1096 2014-03-17 American M 528.205 2014-05-17
现在我想逐行迭代,当我遍历每一行时,ifor
的值每一行都可以根据某些条件而改变,我需要查找另一个数据框.
now I would like to iterate row by row and as I go through each row, the value of ifor
in each row can change depending on some conditions and I need to lookup another dataframe.
现在,我如何在迭代时更新它.试了几样都没有用.
Now, how do I update this as I iterate. Tried a few things none of them worked.
for i, row in df.iterrows():
if <something>:
row['ifor'] = x
else:
row['ifor'] = y
df.ix[i]['ifor'] = x
这些方法似乎都不起作用.我没有看到数据框中更新的值.
None of these approaches seem to work. I don't see the values updated in the dataframe.
推荐答案
您可以使用 df.set_value 在循环中赋值:
You can assign values in the loop using df.set_value:
for i, row in df.iterrows():
ifor_val = something
if <condition>:
ifor_val = something_else
df.set_value(i,'ifor',ifor_val)
如果您不需要行值,您可以简单地遍历 df 的索引,但我保留了原始的 for 循环,以防您需要此处未显示的行值.
If you don't need the row values you could simply iterate over the indices of df, but I kept the original for-loop in case you need the row value for something not shown here.
更新
df.set_value() 从 0.21.0 版本开始被弃用你可以使用 df.at() 代替:
df.set_value() has been deprecated since version 0.21.0 you can use df.at() instead:
for i, row in df.iterrows():
ifor_val = something
if <condition>:
ifor_val = something_else
df.at[i,'ifor'] = ifor_val
这篇关于在逐行迭代时更新 Pandas 中的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!