简体   繁体   中英

How to multiply two columns in pandas, by only non-NaN values?

I am curious if it is possible to multiply two columns A,B by only non NAN values.

I have the following dataframe with the expected results:

                         A     B     C
    Date     Symbol  

  1/1/2017    BTC       Nan    2     Nan
              ETH        3     Nan   6
              XRP        2     Nan   4
  1/2/2017    BTC       Nan    3     Nan
              ETH        1     Nan    3
              XRP        2     Nan    6

I am trying to multiply non Nan values of column A by non-NaN values of Column B and assign the result to column C . I want to iterate over the dataframe. I have tried few things, but nothing is working.

Check with ffill

#df=df.replace('Nan',np.nan)# Nan is not NaN , replace it 
#df=df.apply(pd.to_numeric,1) # convert to numeric 
df.C=df.A*(df.B.ffill())
df
Out[130]: 
                   A    B    C
Date     Symbol               
1/1/2017 BTC     NaN  2.0  NaN
         ETH     3.0  NaN  6.0
         XRP     2.0  NaN  4.0
1/2/2017 BTC     NaN  3.0  NaN
         ETH     1.0  NaN  3.0
         XRP     2.0  NaN  6.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