我正在尝试迭代一个列表,其中数据框中的一列每行都有列表。
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/