使用不同数据帧的值更新特定的Pandas行

时间:2015-03-10 01:47:17

标签: python python-2.7 pandas

我有一个包含预算数据的pandas数据框,但我的销售数据位于另一个大小不同的数据框中。如何在预算数据中更新我的销售数据?如何编写条件以便进行更新?

DF budget:
        cust   type   loc   rev   sales   spend
    0   abc    new    north 500   0       250
    1   def    new    south 700   0       150
    2   hij    old    south 700   0       150

DF sales:
        cust    type   loc    sales
    0   abc     new    north  15
    1   hij     old    south  18

DF budget outcome:
        cust   type   loc   rev   sales   spend
    0   abc    new    north 500   15      250
    1   def    new    south 700   0       150
    2   hij    old    south 700   18      150

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

假设' cust'列在您的其他df中是唯一的,您可以在将索引设置为' cust'之后在sales df上调用map。列,这将映射每个' cust'在预算df中它的销售价值,另外你会得到NaN缺少价值的地方,所以你打电话给fillna(0)来填补这些价值:

In [76]:

df['sales'] = df['cust'].map(df1.set_index('cust')['sales']).fillna(0)
df
Out[76]:
  cust type    loc  rev  sales  spend
0  abc  new  north  500     15    250
1  def  new  south  700      0    150
2  hij  old  south  700     18    150