我需要从两个列表中获取可用的项目,然后检查它们是否在字符串中可用。
list1 = ['Cat', 'Dog', 'Crow']
list2 = ['Wild', 'Pet']
Df
ind Camp
1 Ball_Dog_Wild_Ear
2 Dog_Ball_Pet_Dos
3 Wild_Dos_Cat_Pre
4 Pet_Cer_Crow_Tre
5 Dos_Cat_Wild_Tre
我需要根据“_”拆分“Camp”,然后检查位置 0 和 2 是否列表中的项目完全匹配。
期望的输出:
ind Camp
1 Ball_Dog_Wild_Ear False #False because 0 position has ball(not in list)
2 Dog_Ball_Pet_Dos True #True because 0 and 2 both available in the list
3 Wild_Dos_Cat_Pre True
4 Pet_Cer_Crow_Tre True
5 Dos_Cat_Wild_Tre False
我可以通过 df['Camp'].str.rsplit("_", Expand=True) 进行拆分
并检查.isin()
,但不确定我们如何对每一行进行操作以获得所需的输出。
最佳答案
这是我的建议:
#get all combinations of 2 from list1 &list2 both ways:
l = [(i,k) for i in list1 for k in list2] + [(i,k) for i in list2 for k in list1]
#get the items from positions 0 and 2 as tuple:
df['new']=df.Camp.apply(lambda x: (x.split('_')[0],x.split('_')[2]))
#check if this pair is in l:
df['check']=df.new.apply(lambda x: x in l)
del df['new']
>>>print(df)
ind Camp check
0 1 Ball_Dog_Wild_Ear False
1 2 Dog_Ball_Pet_Dos True
2 3 Wild_Dos_Cat_Pre True
3 4 Pet_Cer_Crow_Tre True
4 5 Dos_Cat_Wild_Tre False
关于python - 需要拆分并检查列表元素在 pandas df 中是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68484226/