【发布时间】:2018-05-10 20:06:29
【问题描述】:
我有一个数据框df:
data = {'id':[12,112],
'idlist':[[1,5,7,12,112],[5,7,12,111,113]]
}
df=pd.DataFrame.from_dict(data)
看起来像这样:
id idlist
0 12 [1, 5, 7, 12, 112]
1 112 [5, 7, 12, 111, 113]
我需要检查id 是否在idlist 中,然后选择或标记它。我尝试了以下变体并收到注释错误:
df=df.loc[df.id.isin(df.idlist),:] #TypeError: unhashable type: 'list'
df['flag']=df.where(df.idlist.isin(df.idlist),1,0) #TypeError: unhashable type: 'list'
解决方案的其他一些可能方法是列表理解中的.apply?
我在这里寻找一种解决方案,它要么选择id 位于idlist 中的行,要么将id 位于idlist 中的行标记为1。生成的df 应该是:
id idlist
0 12 [1, 5, 7, 12, 112]
或:
flag id idlist
0 1 12 [1, 5, 7, 12, 112]
1 0 112 [5, 7, 12, 111, 113]
感谢您的帮助!
【问题讨论】:
标签: python pandas where list-comprehension apply