检查一个列元素是否存在于另一个主元素列表中,如果是,则用相同索引的 1 标记第三列(如果确实存在)

Check if one column elements are there in another master list of elements and if yes, label a third column with 1 of same index if it does exist

提问人:Sachin Santhosh 提问时间:7/1/2023 最后编辑:Andrej KeselySachin Santhosh 更新时间:7/1/2023 访问量:35

问:

enter image description here

这是一个包含 5 列的数据框。

我想用 Python 解决。我尝试将list_1和list_2转换为实际列表并与主列表列进行比较,但没有奏效。任何帮助都是值得赞赏的!可悲的是,我也只有 Python 2.7 可供使用。

list_1  list_2 master_list l1 l2
a        c        a        1   0
b        d        b        1   0
         e        c        0   1
                  d        0   1
                  e        0   1

逐个列表和列表元素到列元素的比较,但没有工作。

Python 熊猫 python-2.7

评论


答:

0赞 Scott Boston 7/1/2023 #1

IIUC,

import pandas as pd

import numpy as np

df = pd.DataFrame({'list_1':['a','b',np.nan,np.nan, np.nan],
                   'list_2':['c','d','e', np.nan, np.nan],
                   'master_list':[*'abcde']})
df['l1'] = df['master_list'].isin(df['list_1']).astype(int)

df['l2'] = df['master_list'].isin(df['list_2']).astype(int)

print(df)

输出:

  list_1 list_2 master_list  l1  l2
0      a      c           a   1   0
1      b      d           b   1   0
2    NaN      e           c   0   1
3    NaN    NaN           d   0   1
4    NaN    NaN           e   0   1

评论

1赞 Sachin Santhosh 7/3/2023
像魅力一样工作,谢谢!:-)