我有以下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
答案 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)
使用div
与fill_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