简体   繁体   中英

How to in-place update values in multiple columns in a DataFrame on condition from another using assignment operator?

There is one DataFrame S to be updated:

n ii      a  b     c
0 True   10 11  1.20 
1 False   2  0   NaN
2 True   34 75  2.14
3 True   22 88  0.02

from another DataFrame T with another set of columns

 a  b     c
 8 13  1.19
31 72  2.10
20 83  0.05

Is it possible to have S updated in a function with one line assignment statement?

def process(S):
    ii = S.ii
    # ... internal calculations that produce T
    columns = ['a', 'b', 'c']
    S[ii][columns] = T[columns] # < ----- in-place update

That process works on a pass-by-reference approach leaving S updated after a call

process(S)

Try returning the dataframe:

    def process(S):
        ii = S.ii
        # ... internal calculations that produce T
        columns = ['a', 'b', 'c']
        S.loc[ii, columns] = T[columns] # < ----- in-place update
        return S

And call the function like this:

    S = process(S)

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