pandas: 根据一列的条件来替换另一列的值

问题

自己处理数据的时候遇到的问题

dataframe是这样的

df.head(10)
7   RT (min)    Area (Ab*s) Quality patch   similarity
8   10.167      23278313    64      NaN     NaN
9   10.167      23278313    47      NaN     NaN
10  10.167      23278313    38      NaN     NaN
28  10.333      3407159     49      10.167  0.983935
29  10.333      3407159     22      10.167  0.983935
30  10.333      3407159     16      10.167  0.983935
48  10.390      3299202     38      10.333  0.994514
49  10.390      3299202     35      10.333  0.994514
50  10.390      3299202     32      10.333  0.994514
68  10.516      2015786     50      10.390  0.988018

df['similarity']>0.99的时候,df['RT(min)'] = df['patch'],例如处理后的结果应该是这样的

7   RT (min)    Area (Ab*s) Quality patch   similarity
8   10.167      23278313    64      NaN     NaN
9   10.167      23278313    47      NaN     NaN
10  10.167      23278313    38      NaN     NaN
28  10.333      3407159     49      10.167  0.983935
29  10.333      3407159     22      10.167  0.983935
30  10.333      3407159     16      10.167  0.983935
48  10.333      3299202     38      10.333  0.994514
49  10.333      3299202     35      10.333  0.994514
50  10.333      3299202     32      10.333  0.994514
68  10.516      2015786     50      10.390  0.988018

48,49,50行的RT(min) 被相应的patch值给取代了

解决方法

利用mask

参数解释: Where cond is False, keep the original value. Where True, replace with corresponding value fromother. 也就是说,只有条件是true的 ,参会返回value

df['RT'] = df['RT'].mask(df['similarity'] > 0.99, df['patch'])

Pandas mask / where methods versus NumPy np.where

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值