![](/img/trans.png)
[英]Pandas select rows where columns are dynamic and a single column's value is greater than zero
[英]Looking for a way to group together rows so that columns match and numbers of one column are greater than or equal to zero in Python/Pandas
我在這里的第一篇文章,希望我提供正確的信息,以便您能夠提供幫助。
我編寫了一個很長的 Python/Pandas 程序,它運行正常,但我希望對其中的一個元素進行微調。
我正在開展一個項目,以便可以合並不同物理區域中的項目,以實現最大的區域優化。
所以我有一個不同狀態、類型和存儲區域的項目列表。以及該特定區域中該項目的數量。 每個區域也有一個相關的數量,該數量仍然可以存儲在那里,直到它裝滿為止。
我想要做的是將這些物品鏈接在一起,以便將物品以一種方式合並在一起,即數量最少的區域與一個至少還有剩余數量的包可以填充的區域合並。 我還需要狀態和類型來匹配要匹配的區域。
如果以數據幀的形式呈現,那么數據幀將輸出滿足上述語句的可能移動列表,這將是理想的。
請參閱下面的示例數據集/代碼:
import pandas as pd
data = {
'ITEM NUMBER': [100, 105, 100, 100, 100, 100, 105, 105, 105, 105, 100],
'STATUS': ["OK", "OK", "NG", "NG", "OK", "OK", "OK", "NG", "OK", "OK", "NG"],
'TYPE': ["RED", "YELLOW", "RED", "BLACK", "RED", "BLACK", "YELLOW", "YELLOW", "RED", "YELLOW", "BLACK"],
'AREA': ['A01', 'B01', "A02", "A03", "A04", "A05", "B02", "B03", "B04", "B05", "A06"],
'QUANTITY': [5, 15, 8, 4, 9, 2, 19, 20, 3, 4, 1],
'PACKS TO FILL': [10, 5, 2, 6, 1, 8, 1, 0, 17, 16, 9]
}
df = pd.DataFrame(data)
df.set_index("ITEM NUMBER", inplace=True)
print(df)
基於上述條件,A04 區的 100 件物品應合並到 A01 區,因為它與 A01 中當前存儲的物品編號、狀態和類型相同,並且 A04 區中的數量少於 A01 區的包裝數量。 這與下面示例數據框中的其他兩項相同:
data = {
'ITEM NUMBER': [100, 105, 100],
'STATUS': ["OK", "OK", "NG"],
'TYPE': ["RED", "YELLOW", "BLACK"],
'AREA': ['A04', 'B05', "A06"],
'MOVE TO': ['A01', "B01", "A03"]
}
df = pd.DataFrame(data)
df.set_index("ITEM NUMBER", inplace=True)
print(df)
我以前一直使用數據透視表將項目組合在一起並手動將區域鏈接在一起,但這是一個漫長的過程,因此如果可能的話,我希望將其自動化。
謝謝你。
國際大學聯盟,
#create a grouping to get the first items in each group
#do not sort, leave table as is
grouping = (df
.groupby(['ITEM NUMBER','STATUS','TYPE'],sort = False)
.agg(move_to=('AREA','first'))
)
(df
#set index so i can use the join method
.set_index(['ITEM NUMBER','STATUS','TYPE'])
.join(grouping)
#get the pack to fill value for values in move_to column
.assign(pack_size = lambda x: x.loc[x.AREA.eq(x.move_to),'PACKS TO FILL'])
#we need only rows where quantity is less than pack size
#and value in area not in move_to
.query('QUANTITY < pack_size and AREA != move_to')
.filter(['AREA','move_to'])
.reset_index([1,2])
)
STATUS TYPE AREA move_to
ITEM NUMBER
100 NG BLACK A06 A03
100 OK RED A04 A01
105 OK YELLOW B05 B01
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.