python - Pandas: Trouble Updating Rows Conditionally -


i have following dataframe:

>>>df      rtt   requests asn   1000 4000  100 2000 50    nan 3000 18000 300 

my goal divide rtt requests in place if requests not nan, otherwise leave rtt untouched. i've tried various things , either second row gets set nan so:

>>>df      rtt   requests asn   1000 40    100 2000 nan   nan 3000 60    300 

or dataframe isn't updated @ all

desired final output

>>>df      rtt   requests asn   1000 40    100 2000 50    nan 3000 60    300 

use fillna

in [1889]: df['rtt'] = df['rtt'].div(df['requests']).fillna(df['rtt'])  in [1890]: df out[1890]:        rtt  requests asn 1000  40.0     100.0 2000  50.0       nan 3000  60.0     300.0 

or, / instead of div

in [1895]: (df['rtt'] / df['requests']).fillna(df['rtt']) out[1895]: asn 1000    40.0 2000    50.0 3000    60.0 dtype: float64 

or, combine_first

in [1897]: df['rtt'].div(df['requests']).combine_first(df['rtt']) out[1897]: asn 1000    40.0 2000    50.0 3000    60.0 dtype: float64 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -