我正在比较sb_list和psr_list的列表值。如果sb_list['ASINs']的所有列表项都在psr_list['Child ASIN']的任何列表中找到,则sb_list['bucket']被标记为'clean'。这部分代码运行良好..。
我遇到麻烦的是如何填充sb_list['Group']。如果['bucket']被标记为'clean',那么sb_list['Group']应该等于找到匹配的对应psr_list['Group']。
我试图运行这个函数来检查sb_list['ASINs']的每个列表和psr_list['Group'],并返回一个元组,如果找到匹配的话,元组的第一个值是干净/混合的,而元组的第二个值是匹配行的psr_list['Group']值。
这与我几周前提出的另一个问题相似,但与我认为它值得发表自己观点的地方有很大不同。
数据:
import pandas as pd
list1 = [
['1', ['hi', 'there', '10', '14', '15']],
['2', ['7', '13', '25', '46', '50']],
['3', ['hello', 'du', '6', '19', '36']],
['4', ['hi', '19', '24', '26', '29']]]
psr_list = pd.DataFrame(list1, columns =['Group', 'Child ASIN'])
list2 = [
['a', ['hi', 'there']],
['r', ['hello', 'du', 'th']],
['e', ['hello', '9']],
['f', ['hello', '6', '36']],
['w', ['hello', '6', '37']],
['a', ['24', '29']],
['q', ['hi', '14', '15']]]
sb_list = pd.DataFrame(list2, columns =['camp', 'ASINs'])
sb_list['bucket'] = ""
sb_list['Group'] = ""我的尝试:
def process(psr_asin_list, sb_ap_asin_list):
return [compare(psr_asin_list, sb_sp_row) for sb_sp_row in sb_ap_asin_list]
def compare(psr_asin_list, sb_sp_row):
counter = 0
while counter < psr_asin_list.shape[0]:
if all(asins in psr_asin_list[counter] for asins in sb_sp_row): return ('clean', psr_asin_list['Group'])
counter +=1
return ('mixed', '')
sb_list['bucket'] = process(psr_list['Child ASIN'].to_numpy(), sb_list['ASINs'].to_numpy())[0]
sb_list['Group'] = process(psr_list['Child ASIN'].to_numpy(), sb_list['ASINs'].to_numpy())[1]期望产出:
camp ASINs bucket Group
0 a [hi, there] clean 1
1 r [hello, du, th] mixed
2 e [hello, 9] mixed
3 f [hello, 6, 36] clean 3
4 w [hello, 6, 37] mixed
5 a [24, 29] clean 4
6 q [hi, 14, 15] clean 1发布于 2022-03-08 00:41:53
可以在列表理解中使用set.issubset检查sb_list中的任何列表是否包含在psr_list中的任何列表中。如果列表存在,则在存在"Group“值的地方获取”Group“值,如果没有使用""填充。请注意,这假设psr_list中只有一个列表包含来自sb_list的列表。
然后根据是否找到“组”值,填写bucket:
def get_group(asin):
group = psr_list.loc[[set(asin).issubset(y) for y in psr_list['Child ASIN'].tolist()], 'Group']
return group.iat[0] if not group.empty else ''
sb_list['Group'] = sb_list['ASINs'].apply(get_group)
sb_list['bucket'] = np.where(sb_list['Group']=='', 'mixed', 'clean')输出:
camp ASINs bucket Group
0 a [hi, there] clean 1
1 r [hello, du, th] mixed
2 e [hello, 9] mixed
3 f [hello, 6, 36] clean 3
4 w [hello, 6, 37] mixed
5 a [24, 29] clean 4
6 q [hi, 14, 15] clean 1https://stackoverflow.com/questions/71388201
复制相似问题