熊猫:有条不紊地更新行的麻烦

时间:2017-09-11 19:15:03

标签: python pandas dataframe

我有以下DataFrame:

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

我的目标是将rtt除以requests到位,如果 requests不是NaN,否则请{0}}保持不变。我尝试了各种各样的事情,第二行设置为rtt,如下所示:

NaN

或者DataFrame并未全部更新

期望的最终产出

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

3 个答案:

答案 0 :(得分:1)

使用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

或者,/代替div

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

或者,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

答案 1 :(得分:1)

或使用np.where

df['rtt'] = np.where(df['requests'].notnull(), df['rtt']/df['requests'], df['rtt'])


        rtt requests
asn     
1000    40.0    100.0
2000    50.0    NaN
3000    60.0    300.0

答案 2 :(得分:1)

使用divfill_value=1

df.assign(rtt = df.rtt.div(df.requests, fill_value=1))

输出:

       rtt  requests
asn                 
1000  40.0     100.0
2000  50.0       NaN
3000  60.0     300.0