本文介绍了Pandas Dataframe检查列值是否在列列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框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中,然后选择或标记它.我尝试了以下变化,并收到了注释的错误:

I need to check and see if id is in the idlist, and select or flag it. I have tried variations of the following and receive the commented error:

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是解决方案的其他可能方法吗?

Some possible other methods to a solution would be .apply in a list comprehension?

我在这里寻找一种解决方案,要么选择idlistid所在的行,要么选择idlistid的行标记为1.结果df应该是:

I am looking for a solution here that either selects the rows where id is in idlist, or flags the row with a 1 where id is in idlist. The resulting df should be either:

   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]

感谢您的帮助!

推荐答案

使用apply:

df['flag'] = df.apply(lambda x: int(x['id'] in x['idlist']), axis=1)
print (df)
    id                idlist  flag
0   12    [1, 5, 7, 12, 112]     1
1  112  [5, 7, 12, 111, 113]     0

类似:

df['flag'] = df.apply(lambda x: x['id'] in x['idlist'], axis=1).astype(int)
print (df)
    id                idlist  flag
0   12    [1, 5, 7, 12, 112]     1
1  112  [5, 7, 12, 111, 113]     0

使用list comprehension:

df['flag'] = [int(x[0] in x[1]) for x in df[['id', 'idlist']].values.tolist()]
print (df)
    id                idlist  flag
0   12    [1, 5, 7, 12, 112]     1
1  112  [5, 7, 12, 111, 113]     0


过滤解决方案:


Solutions for filtering:

df = df[df.apply(lambda x: x['id'] in x['idlist'], axis=1)]
print (df)
   id              idlist
0  12  [1, 5, 7, 12, 112]

df = df[[x[0] in x[1] for x in df[['id', 'idlist']].values.tolist()]]
print (df)

   id              idlist
0  12  [1, 5, 7, 12, 112]

这篇关于Pandas Dataframe检查列值是否在列列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 15:20