計算多索引 pandas 資料幀外部索引每行的總和
我有一個資料框:seller
、item
、price
、shipping
、免費送貨最低
、count available
和count required
。我的目標是根據稍後計算的 total
找到 seller
和 item
的最便宜的組合(計算程式碼如下所示)。範例資料如下:
import pandas as pd item1 = ['item 1', 'item 2', 'item 1', 'item 1', 'item 2'] seller1 = ['seller 1', 'seller 2', 'seller 3', 'seller 4', 'seller 1'] price1 = [1.85, 1.94, 2.00, 2.00, 2.02] shipping1 = [0.99, 0.99, 0.99, 2.99, 0.99] freeship1 = [5, 5, 5, 50, 5] countavailable1 = [1, 2, 2, 5, 2] countneeded1 = [2, 1, 2, 2, 1] df1 = pd.dataframe({'seller':seller1, 'item':item1, 'price':price1, 'shipping':shipping1, 'free shipping minimum':freeship1, 'count available':countavailable1, 'count needed':countneeded1}) # create columns that states if seller has all counts needed. # this will be used to sort by to prioritize the smallest number of orders possible for index, row in df1.iterrows(): if row['count available'] >= row['count needed']: df1.at[index, 'fulfills count needed'] = 'yes' else: df1.at[index, 'fulfills count needed'] = 'no' # dont want to calc price based on [count available], so need to check if seller has count i need and calc cost based on [count needed]. # if doesn't have [count needed], then calc cost on [count available]. for index, row in df1.iterrows(): if row['count available'] >= row['count needed']: df1.at[index, 'price x count'] = row['count needed'] * row['price'] else: df1.at[index, 'price x count'] = row['count available'] * row['price']
但是,任何一個seller
都可以出售多個item
。我想盡量減少支付的運費,所以我想透過 seller
將 item
s 分組在一起。因此,我根據我在另一個線程中看到的方式使用 .first()
方法對它們進行分組,以便將每一列保留在新的分組資料框中。
# don't calc [total] until sellers have been grouped # use first() method to return all columns and perform no other aggregations grouped1 = df1.sort_values('price').groupby(['seller', 'item']).first()
此時我想透過seller
計算total
。所以我有以下程式碼,但它為每個item
計算total
,而不是seller
,這意味著shipping
根據每個群組中的商品數量被多次添加,或當price x count
結束時不應用免費送貨最低免運費
。
# calc [Total] for index, row in grouped1.iterrows(): if (row['Free Shipping Minimum'] == 50) & (row['Price x Count'] > 50): grouped1.at[index, 'Total'] = row['Price x Count'] + 0 elif (row['Free Shipping Minimum'] == 5) & (row['Price x Count'] > 5): grouped1.at[index, 'Total'] = row['Price x Count'] + 0 else: grouped1.at[index, 'Total'] = row['Price x Count'] + row['Shipping']
實際上看起來我可能需要在計算total
時對每個seller
求和price x count
,但這本質上是同一個問題,因為我不知道如何計算外部索引的每行列。我可以使用什麼方法來做到這一點?
另外,如果有人對如何實現我的後半部目標有任何建議,請儘管提出。我只想退回我需要的每件商品。例如,我需要 2 個「項目 1」和 2 個「項目 2」。如果“賣家1”有2 個“商品1”和1 個“商品2”,而“賣家2”有1 個“商品1”和1 個“商品2”,那麼我想要“賣家1”的所有商品(假設它最便宜),但只有「賣家2」的1 個「商品1」。這似乎會影響 total
列的計算,但我不確定如何實現它。
正確答案
我最終決定先將seller
分組,並對price x count
進行求和以找到subtotal
s,將其轉換為資料幀,然後將df1
與新的subtotal
資料幀合併以建立groupedphpcnend cphpcn 資料框。然後我使用 <code>np.where
建議創建了 totals
列(這比我的 for 循環優雅得多,並且可以輕鬆處理 nan 值)。最後按seller
、total
、item
分組傳回我想要的結果。最終程式碼如下:
import pandas as pd import numpy as np item1 = ['item 1', 'item 2', 'item 1', 'item 1', 'item 2'] seller1 = ['Seller 1', 'Seller 2', 'Seller 3', 'Seller 4', 'Seller 1'] price1 = [1.85, 1.94, 2.69, 2.00, 2.02] shipping1 = [0.99, 0.99, 0.99, 2.99, 0.99] freeship1 = [5, 5, 5, 50, 5] countavailable1 = [1, 2, 2, 5, 2] countneeded1 = [2, 1, 2, 2, 1] df1 = pd.DataFrame({'Seller':seller1, 'Item':item1, 'Price':price1, 'Shipping':shipping1, 'Free Shipping Minimum':freeship1, 'Count Available':countavailable1, 'Count Needed':countneeded1}) # create columns that states if seller has all counts needed. # this will be used to sort by to prioritize the smallest number of orders possible for index, row in df1.iterrows(): if row['Count Available'] >= row['Count Needed']: df1.at[index, 'Fulfills Count Needed'] = 'Yes' else: df1.at[index, 'Fulfills Count Needed'] = 'No' # dont want to calc price based on [count available], so need to check if seller has count I need and calc cost based on [count needed]. # if doesn't have [count needed], then calc cost on [count available]. for index, row in df1.iterrows(): if row['Count Available'] >= row['Count Needed']: df1.at[index, 'Price x Count'] = row['Count Needed'] * row['Price'] else: df1.at[index, 'Price x Count'] = row['Count Available'] * row['Price'] # subtotals by seller, then assign calcs to column called [Subtotal] and merge into dataframe subtotals = df1.groupby(['Seller'])['Price x Count'].sum().reset_index() subtotals.rename({'Price x Count':'Subtotal'}, axis=1, inplace=True) grouped = df1.merge(subtotals[['Subtotal', 'Seller']], on='Seller') # calc [Total] grouped['Total'] = np.where(grouped['Subtotal'] > grouped['Free Shipping Minimum'], grouped['Subtotal'], grouped['Subtotal'] + grouped['Shipping']) grouped.groupby(['Seller', 'Total', 'Item']).first()
以上是計算多索引 pandas 資料幀外部索引每行的總和的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。
