简体   繁体   English

如果值等于第二个列表元素,则使用第一个列表的元素创建新列

[英]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.mapzip创建的字典由两个列表:

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.

相关问题 按First元素对元素列表进行排序,但如果按第二个元素进行等级排序 - Sorting a List of Elements by the First element but if Equal sort by the second Python 。 如果第二个元素相等,如何对子列表的元素进行排序 按第一个元素对子列表进行排序 - Python . How to sort elements of sub-list if second elements are equal sort the sub-lists by first element 第二列中列表中元素的平均值 - Average of elements in a list in the second column 从第二个列表中减去第一个列表中的元素 - Subtract elements in first list from the second list 检查列表中的元素是否等于列表的总和值 - Check if elements in a list equal to the sum value of the list 如果列表中的第一个元素匹配,如何对列表的第二个元素求和 - How to sum the second elements of the list if the first elements in the list are matching 访问列表元素不等于特定值 - Access list elements that are not equal to a specific value 在每行中相乘2个元素,创建新列,列表列表-Python - Multiply 2 elements in each row, create new column, list of lists - python 如何计算列表中元素的数量并创建新列? - How to count the number of elements in a list and create a new column? 如果第二个元素相同,则将列表中的第一个元素合并为元组? - Merge the first elements in a list a tuples if the second elements are the same?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM