在逐行重复的同时更新 pandas 中的数据框 [英] Update a dataframe in pandas while iterating row by row

查看:233
本文介绍了在逐行重复的同时更新 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在循环中分配值: / p>

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.

这篇关于在逐行重复的同时更新 pandas 中的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆