一种干净有效的方法来更新pandas DataFrames中的单元格

时间:2015-01-06 06:55:53

标签: python pandas

我正在寻找一种更清洁的方法来实现以下目标:

我有一个DataFrame,其中包含某些列,如果有新信息到达,我想要更新这些列。 pandas DataFrame(来自CSV文件)的这个“新信息”可以有更多或更少的行,但是,我只想添加

原始DataFrame

enter image description here

带有新信息的DataFrame

enter image description here

(请注意此处缺少的名称“c”以及名称“a”的“状态”更改<)

现在,我编写了以下“不方便”的代码,用新信息更新原始DataFrame

根据“名称”列

更新“状态”列
for idx,row in df_base.iterrows():
    if not df_upd[df_upd['name'] == row['name']].empty:
        df_base.loc[idx, 'status'] = df_upd.loc[df_upd['name'] == row['name'], 'status'].values

enter image description here

它实现了我想要的,但它既不好看也不高效,我希望可能有更清洁的方式。我尝试了pd.merge方法,但问题是它会添加新列而不是“更新”该列中的单元格。

pd.merge(left=df_base, right=df_upd, on=['name'], how='left')

enter image description here

我期待着您的提示和想法。

1 个答案:

答案 0 :(得分:2)

你可以set_index("name")然后拨打.update

>>> df_base = df_base.set_index("name")
>>> df_upd = df_upd.set_index("name")
>>> df_base.update(df_upd)
>>> df_base
      status
name        
a          0
b          1
c          0
d          1

更一般地说,您可以将索引设置为适当的值,更新,然后根据需要重置。