python - Pandas Dataframe 检查列值是否在列列表中

标签 python pandas where list-comprehension apply

我有一个数据框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 在列表理解中?

我在这里寻找一个解决方案,要么选择 idlistid 的行,要么用 1 标记行,其中 ididlist 中。生成的 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]

感谢您的帮助!

最佳答案

使用应用:

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

使用列表理解:

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

过滤解决方案:

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]

关于python - Pandas Dataframe 检查列值是否在列列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47513408/

相关文章:

python - Pandas 时间序列: aggregate by day and transpose

python - 将序列拆分为重叠 block 的更好方法?

python - 如何更改 matplotlib 中多个绘图的默认颜色?

python - 在 Python 中通过套接字发送的字符串一旦 .recv'd 后将不会与等效字符串进行比较

python - Pandas:如何比较导入的 csv 文件的列以确保它们相同?

Laravel Scout,使用 where 子句搜索

python - 如何解析包含相似数据的不同 JSON 模式?

python - 通过仅跳过空白行来读取 excel 文件 (pd.read_excel())

SQL:为每个不同的值选择三行

android - 如何将 query() 与 WHERE 子句一起使用?