我有一個包含專案價格的串列串列,這些元素的順序也很重要。我還有一個資料框,其中包含這些串列中的專案及其相關價格。我正在嘗試遍歷每個串列,并基本上用相應的專案替換串列串列中的價格元素。我遇到的問題是有兩個價格相同的商品。目前我的代碼只是將這兩個重復的定價專案添加到串列中,但我希望它為這兩個專案創建一個單獨的串列。
當前代碼:
data = {'Item':['Apples', 'Cereal', 'Corn', 'Pasta', 'Detergent', 'Coffee', 'Ketchup', 'Oats', 'Olive Oil'],
'Price':[4, 2, 6, 5, 10, 9, 2, 3, 1]}
df = pd.DataFrame(data)
combos = [[4, 2, 3, 6], [2, 10, 2, 4], [6, 1, 10, 2]]
testing = []
for list in combos:
output = df.set_index('Price').loc[list, 'Item'].to_numpy().tolist()
testing.append(output)
print(testing)
輸出:
[['Apples', 'Cereal', 'Ketchup', 'Oats', 'Corn'], ['Cereal', 'Ketchup', 'Detergent', 'Cereal', 'Ketchup', 'Apples'], ['Corn', 'Olive Oil', 'Detergent', Cereal, 'Ketchup']]
我想要的結果:
[['Apples', 'Cereal', 'Oats', 'Corn'], ['Cereal', 'Detergent', 'Cereal', 'Apples'], ['Cereal', 'Detergent', 'Ketchup', 'Apples'], ['Ketchup', 'Detergent', 'Cereal', 'Apples'], ['Ketchup', 'Detergent', 'Ketchup', 'Apples'], ['Corn', 'Olive Oil', 'Detergent', 'Cereal'], ['Corn', 'Olive Oil', 'Detergent', 'Ketchup']]
uj5u.com熱心網友回復:
itertools.product使用and的一種方法chain:
from itertools import product, chain
prices = df.groupby("Price")["Item"].apply(list)
list(chain.from_iterable(product(*prices.loc[c]) for c in combos))
輸出:
[('Apples', 'Cereal', 'Oats', 'Corn'),
('Apples', 'Ketchup', 'Oats', 'Corn'),
('Cereal', 'Detergent', 'Cereal', 'Apples'),
('Cereal', 'Detergent', 'Ketchup', 'Apples'),
('Ketchup', 'Detergent', 'Cereal', 'Apples'),
('Ketchup', 'Detergent', 'Ketchup', 'Apples'),
('Corn', 'Olive Oil', 'Detergent', 'Cereal'),
('Corn', 'Olive Oil', 'Detergent', 'Ketchup')]
uj5u.com熱心網友回復:
您還可以使用pd.MultiIndex.from_product生成笛卡爾積:
prices = df.groupby("Price")["Item"].apply(list)
out = []
for combo in combos:
product = pd.MultiIndex.from_product(prices.loc[combo]).tolist()
out.extend(map(list, product))
輸出:
[['Apples', 'Cereal', 'Oats', 'Corn'],
['Apples', 'Ketchup', 'Oats', 'Corn'],
['Cereal', 'Detergent', 'Cereal', 'Apples'],
['Cereal', 'Detergent', 'Ketchup', 'Apples'],
['Ketchup', 'Detergent', 'Cereal', 'Apples'],
['Ketchup', 'Detergent', 'Ketchup', 'Apples'],
['Corn', 'Olive Oil', 'Detergent', 'Cereal'],
['Corn', 'Olive Oil', 'Detergent', 'Ketchup']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416477.html
標籤:
