python-3.x - 检查列表中的项目是否在列表类型的列中可用

标签 python-3.x pandas dataframe

我正在尝试迭代一个列表,其中数据框中的一列每行都有列表。

list1 = ['安装','安装','已安装','替换','修复','修复','替换','部分','二手','新']

df[lwr_nopunc_spc_nostpwrd].head(3)

['daily', 'ask', 'questions']
['daily', 'system', 'check', 'task',  'replace']
['inspection', 'complete', 'replaced', 'horizontal', 'sealing', 'blade', 'inspection', 'complete', 'issues', 'found']

现在,我想在我的数据框中获取两个新列,如果 <new column one> 则应显示 true 或 false df[lwr_nopunc_spc_nostpwrd] 行中的任何一项出现在 list1 <new columns two> 中如果 list1 中的所有项目都出现在 df[lwr_nopunc_spc_nostpwrd] 行中

请让我知道如何实现。我尝试过 all()any()方法,但这似乎不起作用。

def prt_usd(row):
    return(any(item in query['lwr_nopunc_spc_nostpwrd'] for item in part))

for row in query['lwr_nopunc_spc_nostpwrd']:
    prt_usd(query['lwr_nopunc_spc_nostpwrd'])

最佳答案

你可以应用设置,如下所示:

# I changed the list to the second row to show that the column all works
list1 = ['daily', 'system', 'check', 'task',  'replace']
# create a set from it
s1 = set(list1)

# for any word, check that the intersection of s1 
# and the set of the list in this row is not empty
df['col_any'] = df['lwr_nopunc_spc_nostpwrd'].apply(lambda x: any(set(x)&s1))

# for all, subtract the set of this row from the set s1, 
# if not empty then it return True with any
# that you reverse using ~ in front of it to get True if all words from s1 are in this row
df['col_all'] = ~df['lwr_nopunc_spc_nostpwrd'].apply(lambda x: any(s1-set(x)))
print (df)
                             lwr_nopunc_spc_nostpwrd  col_any  col_all
0                            [daily, ask, questions]     True    False
1              [daily, system, check, task, replace]     True     True
2  [inspection, complete, replaced, horizontal, s...    False    False

关于python-3.x - 检查列表中的项目是否在列表类型的列中可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61877712/

相关文章:

python - 如何检查 Pandas 中是否存在列

python - Pandas .groupby 自动选择列

python - 如何计算 python 中我的列中的行的编辑比/距离?

python - Pandas 按降序枚举组

python - 如何检查所有值是否都在pivot_table的输入DataFrame中,并创建一些Python Pandas中不存在的值并用0填充?

python - 使用 Pandas 处理 GPS 数据

python - 如何按行压缩两个元组列表?

python - 手动调用 __enter__ 和 __exit__

python - 客户端使用 Python3 连接到 sybase IQ

Pythonic 使用属性和异常