gpt4 book ai didi

python - 如何做 python itertools.combinations

转载 作者:行者123 更新时间:2023-12-04 03:57:01 25 4
gpt4 key购买 nike

我正在尝试从所有供应商组合中找出可能的产品列表。找出组合中的任何一个都可以产生产品

import itertools
import pandas as pd
import numpy as np

Column = {'ID':['1','2','3','4','5'],'Supplier 1':['B','B','A','B','B'],'Supplier 2':['A','NaN','B','NaN','A']}
df=pd.DataFrame(Column)
df

# Define all Supplier Columns
cols = [c for c in df.columns if "Supplier" in c]
# get unique suppliers
suppl = np.unique(np.concatenate([df[c].dropna() for c in cols]))
result = []
for sn in range(len(suppl)):
# generate combinations of suppliers
for combi in itertools.combinations(suppl, sn+1):
result.append({combi:......

来自

ID  Supplier 1  Supplier 2
1 B A
2 B NaN
3 A B
4 B NaN
5 B A

需求(任一供应商均可生产):

Supplier    ID
A 1,3,5
B 1,2,3,4,5
A,B 1,2,3,4,5

新代码:

from itertools import combinations, chain
import pandas as pd
import numpy as np

df = {'ID':['1','2','3','4','5'],'Supplier 1':['B','B','A','B','B'],'Supplier 2':['A',np.nan,'B',np.nan,'A']}
df=pd.DataFrame(Column)
from itertools import combinations, chain

g1 = df.groupby(['Supplier 1'])['ID'].apply(list)
g2 = df.groupby(['Supplier 2'])['ID'].apply(list)

res = (g1 + g2).to_dict()
res = [[','.join(comb), ','.join(sorted(set(chain.from_iterable([res[k] for k in comb]))))]
for x in range(1, len(res) + 1) for comb in combinations(res.keys(), x)]

df2 = pd.DataFrame(res, columns=['Supplier', 'ID'])
print(df2)

最佳答案

这不是一个有效的解决方案,但它会起作用

from itertools import combinations, chain

g1 = df.groupby(['Supplier 1'])['ID'].apply(list)
g2 = df.groupby(['Supplier 2'])['ID'].apply(list)

res = (g1 + g2).to_dict()
res = [[','.join(comb), ','.join(sorted(set(chain.from_iterable([res[k] for k in comb]))))]
for x in range(1, len(res) + 1) for comb in combinations(res.keys(), x)]

df2 = pd.DataFrame(res, columns=['Supplier', 'ID'])
print(df2)

输出:

  Supplier         ID
0 A 1,3,5
1 B 1,2,3,4,5
2 A,B 1,2,3,4,5

关于python - 如何做 python itertools.combinations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63700395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com