如何使用列子集上的广播系列修改 pandas 数据框

How to modify a pandas dataframe using broadcasting series on a subset of columns

鉴于以下 table:

 import numpy as np
 import pandas as pd
 data = pd.DataFrame(data = np.arange(16).reshape((4, 4)),
                     index = ['Chile', 'Argentina', 'Peru', 'Bolivia'],
                     columns = ['one', 'two', 'three', 'four'])


           one  two three  four
 Chile      0    1   2      3
 Argentina  4    5   6      7
 Peru       8    9   10     11
 Bolivia    12   13  14     15

我想通过在列的子集(onethree)上广播 pandas 系列来应用操作,这将 修改 (更新)table。所以..

ser_to_broad = pd.Series([1, 2], index = ['one', 'three'])
data + ser_to_broad

           one  two three  four
Chile       1   NaN   4     NaN
Argentina   5   NaN   8     NaN    
Peru        9   NaN   12    NaN    
Bolivia     13  NaN   16    NaN 

是否有一种方法可以通过广播方法保留列 twofour 的原始值?

处理reindex,由于ser_to_broad中有遗漏列,那么它将return NaN (NaN + somevalue=NaN)

data+ser_to_broad.reindex(data.columns,fill_value=0)
Out[106]: 
           one  two  three  four
Chile        1    1      4     3
Argentina    5    5      8     7
Peru         9    9     12    11
Bolivia     13   13     16    15

如果你想更新数据,我想这样可以:

ser_to_broad = pd.Series([1, 2], index=['one', 'three'])
data[ser_to_broad.index] += ser_to_broad

print(data)

输出

           one  two  three  four
Chile        1    1      4     3
Argentina    5    5      8     7
Peru         9    9     12    11
Bolivia     13   13     16    15