【发布时间】:2019-11-11 07:11:47
【问题描述】:
我有一个数据框,你可以用它来构建:
dflist=[['123',['abc','qw3','123']],
['ab12',['3e4r5','12we3','asd23','q2w3']]]
df=pd.DataFrame(dflist,columns=['check','checklist'])
看起来像这样:
check checklist
0 123 [abc, qw3, 123]
1 ab12 [3e4r5, 12we3, asd23, q2w3]
我想检查“check”列中的项目是否在“checklist”列的列表中。所以我希望生成的数据框看起来像:
check checklist checkisin
0 123 [abc, qw3, 123] True
1 ab12 [3e4r5, 12we3, asd23, q2w3] False
我尝试了几件事,包括以各种形式使用 .isin,包括 apply/lambda。并且直接。
这个:
df['checkisin']=df.check.isin(df.checklist)
产生:
check checklist checkisin
0 123 [abc, qw3, 123] False
1 ab12 [3e4r5, 12we3, asd23, q2w3] False
其中有两个 False。
试试这个: df['checkisin']=df.apply(lambda x:x.check.isin(x.checklist)) 给出这个错误:
AttributeError: ("'Series' object has no attribute 'check'", 'occurred at index check')
试试这个:
df['checkisin']=df.apply(lambda x:x['check'] in x.checklist)
给出这个错误:
KeyError: ('check', 'occurred at index check')
我确定我在这里遗漏了一些简单的东西。我知道我可以循环这个,但是寻找一个 Pandas Dataframe 列明智的解决方案,因为我拥有的 DF 非常大并且试图“最”有效地处理。
谢谢!
【问题讨论】:
标签: python pandas list dataframe apply