Home > other >  Create new column with elements of the first list if value is equal to the second list elements
Create new column with elements of the first list if value is equal to the second list elements

Time:08-09

I have a dataset df1 with two columns :

d1=[9,9,26,28,43,43,43,44,85]
df1 = pd.DataFrame(data = d1)
df1['sl']=""

And 2 lists with the same length (but not the same length than the df1) :

list1=[9,26,28,43,44,85]
list2=[2,1,1,1,1,1,1]

I would like to add in my column 'sl' (df1), the values of the list2 if the value of my column 1 (of df1) is equal to the elements of the list1.

I mean, expected output for df1:

0 sl
9 2
9 2
26 1
28 1
43 1
43 1
43 1
43 1
44 1
85 1

I have tried a lot of solution before posting but without success...

Thanks a lot,

AL

CodePudding user response:

Use Series.map by dictionary created by zip by both lists:

d1=[9,9,26,28,43,43,43,44,85]
df1 = pd.DataFrame(data = d1)

list1=[9,26,28,43,44,85]
list2=[2,1,1,1,1,1]

df1['sl']= df1[0].map(dict(zip(list1, list2)))
print (df1)
    0  sl
0   9   2
1   9   2
2  26   1
3  28   1
4  43   1
5  43   1
6  43   1
7  44   1
8  85   1
  • Related