简体   繁体   中英

How do you update a Pandas DataFrame with new Indices and Columns

I have

     a,   b,   c
u, 111, 112, 113
v, 121, 122, 123
x, 131, 132, 133

and

     b,   c,   d
x, 211, 212, 213
y, 221, 222, 223
z, 231, 232, 233

I want to arrive at:

     a,   b,   c,   d
u, 111, 112, 113, NaN
v, 121, 122, 123, NaN
x, 131, 343, 345, 213
y, NaN, 221, 222, 223
z, NaN, 231, 232, 233

Here the common data is added. If they are not common the data is retained. If the data is not present on either DF NaN is added.

This is like an "outer" add of 2 DataFrames.

You can use df.add over axis 1 with fill_value param.

# df
#      a    b    c
# u  111  112  113
# v  121  122  123
# x  131  132  133

#df1
#      b    c    d
# x  211  212  213
# y  221  222  223
# z  231  232  233

df.add(df1, axis=1, fill_value=0)

       a      b      c      d
u  111.0  112.0  113.0    NaN
v  121.0  122.0  123.0    NaN
x  131.0  343.0  345.0  213.0
y    NaN  221.0  222.0  223.0
z    NaN  231.0  232.0  233.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM