python - 需要拆分并检查列表元素在 pandas df 中是否可用

标签 python pandas list split

我需要从两个列表中获取可用的项目,然后检查它们是否在字符串中可用。

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/

相关文章:

pandas - 从 groupby() 生成的组实例访问分组变量

java - 将列表写入 Parcelable?

algorithm - 模块化游程编码

python - 按日期字符串索引时间序列

Python - 如果字符串列表不在字典键中,则从字典列表中删除字典

python - Django & Celery 使用单例类实例属性作为全局

python - 修补: Replacing a method call with another

python - NLTK 荷兰语 alpino 至 英语

python - 循环遍历列表和逐个循环对象之间的区别?

python - 如何获取 Data Frame Python 中除一列以外的所有列?