如果数据框中的列值匹配列表更改为另一个值

时间:2020-04-01 09:19:16

标签: python list dataframe

这很简单,但似乎无法正常工作。我有四个列表,w,x,y,z与列中的值匹配,将它们更改为另一个值。对于w我想要5,对于x我想要1,对于Y我想要8而对于Z我想要10

w = [6,9,12,30]
x = [4,11,13,14]
Y = [10,16,12,2]
Z = [8,25,24,99]

df:

ID:
6
9
12
30
4 
11
13 
14
10
16
12
2 
8
25
24
99


Wanted output:
5
5
5
5
1
1
1
1
8
8
8
8
10
10
10
10

1 个答案:

答案 0 :(得分:0)

我使用np.where进行这种转换: enter image description here

df['Output'] = np.where(df['ID'].isin(w), 5, 
               np.where(df['ID'].isin(x), 1,
               np.where(df['ID'].isin(y), 8,
               np.where(df['ID'].isin(z), 10,
                  'non-dentified'))))

还请检查列ID的格式,以便列表中元素的格式与列中元素的格式相同。