[英]Create new column with elements of the first list if value is equal to the second list elements
I have a dataset df1 with two columns:我有一个包含两列的数据集 df1:
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):以及 2 个长度相同的列表(但长度与 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.如果我的列 1(df1)的值等于 list1 的元素,我想在我的列“sl”(df1)中添加 list2 的值。
I mean, expected output for df1:我的意思是,预计 df1 的 output :
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铝
Use Series.map
by dictionary created by zip
by both lists:使用
Series.map
由zip
创建的字典由两个列表:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.