如何基于另一个列的值(在Python中为列表)将列值的某些值设为零
S.No Num_1 Num_2 Num_3 Num_4 Num_5 id Final
0 2 4 2 1 1 1 1.1
1 2.5 4.6 2.7 1.2 1.1 1 1.2
2 2 4 2 1 1 1 1.3
3 2.5 4.6 2.7 1.2 1.1 2 1.4
4 2 4 2 1 1 2 1.5
5 2.5 4.6 2.7 1.2 1.1 2 1.6
6 2 4 2 1 1 3 1.7
7 2.5 4.6 2.7 1.2 1.1 4 1.8
8 2 4 2 1 1 4 1.9
9 2.5 4.6 2.7 1.2 1.1 5 2
10 2 4 2 1 1 5 2.1
11 2.5 4.6 2.7 1.2 1.1 6 2.2
12 2 4 2 1 1 6 2.3
13 2.5 4.6 2.7 1.2 1.1 6 2.4
14 2 4 2 1 1 6 2.5
15 2.5 4.6 2.7 1.2 1.1 7 2.6
16 2 4 2 1 1 7 2.7
17 2.5 4.6 2.7 1.2 1.1 7 2.8
18 2 4 2 1 1 7 2.9
19 2.5 4.6 2.7 1.2 1.1 8 3
20 2 4 2 1 1 8 3.1
21 2.5 4.6 2.7 1.2 1.1 8 3.2
22 2 4 2 1 1 10 3.3
23 2.5 4.6 2.7 1.2 1.1 10 3.4
和id = [2,4,5,6,8]
无论我的ID在哪里,最终值应为0(零)
如何在python或Pandas中执行此操作?
答案 0 :(得分:1)
使用np.where
import numpy as np
id_ = [2,4,5,6,8] # as id is a keyword in Python
df['Final'] = np.where(df['id'].isin(id_), 0, df['Final'])
答案 1 :(得分:0)
您可以mask
您的系列:
ids = [2, 4, 5, 6, 8]
df['Final'] = df['Final'].mask(df['id'].isin(ids), 0)
答案 2 :(得分:0)
尝试一下:
id_ = [2,4,5,6,8]
df['Final'].loc[df['id'].isin(id_)] = 0