我遇到了以下我想用python解决的问题。我想把零件随机分配到具有一定容量的容器中。下面是一个虚拟数据帧(带熊猫)的示例,展示了我想要实现的目标:
dfA =
Car Container Capcity_container Container_type
0 CAR1 E-1 1 E
1 CAR1 A-2 2 A
2 CAR1 B-2 1 B
3 CAR1 A-6 2 A
4 CAR2 B-4 1 B
5 CAR2 A-1 4 A
6 CAR2 B-5 1 B
7 CAR3 C-2 2 C
8 CAR3 B-8 1 B
9 CAR3 B-3 2 B
dfB =
Part Car Container_Type
8 Part9 CAR2 B
0 Part1 CAR1 A
1 Part2 CAR1 A
2 Part3 CAR1 B
3 Part4 CAR1 E
9 Part10 CAR1 A
12 Part13 CAR1 A
4 Part5 CAR2 A
5 Part6 CAR2 A
6 Part7 CAR2 A
13 Part14 CAR2 B
7 Part8 CAR3 B
10 Part11 CAR3 B
11 Part12 CAR3 B
在dfA中,它知道哪辆车装的是什么时间的具有指定容量的集装箱。你知道吗
在dfB中,知道哪个部件需要放在哪个车厢和集装箱的类型中。 汽车所有部件的总和与dfA中集装箱容量的总和相同。你知道吗
我的目标是:我想'分配'的部分随机容器与正确的类型。容器“满”后,剩余的零件应分配给另一个具有右键的容器类型。理想情况下它会返回这样的结果:
result =
Part Car Container_Type Container_assign
0 Part1 CAR1 A A-2
1 Part2 CAR1 A A-2
2 Part3 CAR1 B B-2
3 Part4 CAR1 E E-1
9 Part10 CAR1 A A-1
12 Part13 CAR1 A A-1
4 Part5 CAR2 A A-1
5 Part6 CAR2 A A-1
6 Part7 CAR2 A A-5
8 Part9 CAR2 B B-2
13 Part14 CAR2 B B-5
7 Part8 CAR3 B B-8
10 Part11 CAR3 B B-8
11 Part12 CAR3 B B-3
请注意,只要满足容量要求,并且零件位于正确类型的集装箱和正确的汽车/ULD中,它们就可以在集装箱上随机分配。你知道吗
**编辑#2** @博维尔上校:这是你的代码,我在潜入try函数后做了一些调整,这对我来说是全新的。你知道吗
for i, r in dfB.iterrows():
mask = (dfA['count']!=0) & (dfA['Container_type']==r['Container_Type']) & (dfA['CAR']==r['CAR'])
df = dfA[mask]
try:
l.append(df.iloc[0]['Container'])
dfA.ix[df.index[0],'count'] = dfA.ix[df.index[0],'count'] - 1
except Exception as e:
l.append('Not Assigned')
dfB['Container_assign']=l
返回以下内容:
Part CAR Container_Type Container_assign
0 Part9 CAR2 B B-4
1 Part1 CAR1 A A-2
2 Part2 CAR1 A A-2
3 Part3 CAR1 B B-2
4 Part4 CAR1 E E-1
5 Part10 CAR1 A Not Assigned
6 Part13 CAR1 A Not Assigned
7 Part5 CAR2 A A-1
8 Part6 CAR2 A A-1
9 Part7 CAR2 A A-1
10 Part14 CAR2 B B-5
11 Part8 CAR3 B B-8
12 Part11 CAR3 B B-3
13 Part12 CAR3 B B-3
例如,我将A-6的容量改为零,以便取回2个未分配的部件。成功了!你知道吗
Container CAR Capcity_container Container_type count
0 E-1 CAR1 1 E 0
1 A-2 CAR1 2 A 0
2 B-2 CAR1 1 B 0
3 A-6 CAR1 0 A 0
4 B-4 CAR2 1 B 0
5 A-1 CAR2 4 A 1
6 B-5 CAR2 1 B 0
7 C-2 CAR3 2 C 2
8 B-8 CAR3 1 B 0
9 B-3 CAR3 2 B 0
如何使用else或finally打印“所有部件都分配”之类的内容容量满足部件数量,所有部件都分配,换句话说,没有错误?当我添加它时,它会返回每个部分的值。 编辑#3
我觉得这很好,很简单。。。你知道吗
l = []
dfA['count'] = dfA['Capcity_container']
erroryesno = 'All parts are Assinged'
for i, r in dfB.iterrows():
mask = (dfA['count']!=0) & (dfA['Container_type']==r['Container_Type']) & (dfA['CAR']==r['CAR'])
df = dfA[mask]
try:
l.append(df.iloc[0]['Container'])
dfA.ix[df.index[0],'count'] = dfA.ix[df.index[0],'count'] - 1
except Exception as e:
l.append('Not Assigned')
erroryesno = 'Some are not assinged'
print erroryesno
dfB['Container_assign']=l
一种可能的解决方案是遍历
dfB
行并获取dfA
中可用的第一个相应容器。因此,集装箱容量减少一个:相关问题 更多 >
编程相关推荐