简体   繁体   中英

How to multiply dataframe rows by an array based on an 'attribute' of the row whilst preserving dataframe rows not matching array attribute?

Very similar to "https://stackoverflow.com/questions/60566053/how-to-multiply-dataframe-rows-by-an-array-based-on-an-attribute-of-the-row" but if the original dataframe has index'ed rows not matching array's attribute, df elements return NaNs. Effectively I would like a "left-join" variant implementation

Operand DataFrame df example (dates as index with columns A, B and C):

                A     B     C
 2000-01-02     1     2     3
 2000-01-03     1     2     3
 2000-01-04     1     2     3
 2000-01-05     1     2     3

df2:

                A     B     C
 2000-01-03     1     2     3
 2000-01-04     1     2     3

Trying to get elementwise df*df2 multiplication dataframe result:

                A     B     C
 2000-01-02     1     2     3
 2000-01-03     1     4     9
 2000-01-04     1     4     9
 2000-01-05     1     2     3

but instead get

                A     B     C
 2000-01-02     NaN   NaN    NaN
 2000-01-03     1     4     9
 2000-01-04     1     4     9
 2000-01-05     NaN     NaN     NaN

using solution based on URL reponse, h/t jezrael df_result = (df.mul(df2, level=0))

with addition of fill_value= to no avail in.mul() as parameter

Would anyone have any suggestions? Thanks in advance

You could update df using update . This will update df in place

>>> df.update(df.mul(df2))
>>> df
              A    B    C
2000-01-02  1.0  2.0  3.0
2000-01-03  1.0  4.0  9.0
2000-01-04  1.0  4.0  9.0
2000-01-05  1.0  2.0  3.0

For a non-inplace update, you could also use the fillna method to fill the nulls with values from your first df:

>>> df.mul(df2).fillna(df)
              A    B    C
2000-01-02  1.0  2.0  3.0
2000-01-03  1.0  4.0  9.0
2000-01-04  1.0  4.0  9.0
2000-01-05  1.0  2.0  3.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