您如何放置具有相同 order_id 的行,以便它們所有對應的行加起來形成結果 Dataframe?(在這種情況下,數量和商品價格應在其前面添加相應的訂單ID,并且選擇描述和商品名稱也應以其“str”格式添加)

可重現的輸入:
d = {'order_id': [1, 1, 1, 1, 2], 'quantity': [1, 1, 1, 1, 2], 'item_name': ['Chips and Fresh Tomato Salsa', 'Izze', 'Nantucket Nectar', 'Chips and Tomatillo-Green Chili Salsa', 'Chicken Bowl'], 'choice_description': [nan, '[Clementine]', '[Apple]', nan, '[Tomatillo-Red Chili Salsa (Hot), [Black Beans, Rice, Cheese, Sour Cream]]'], 'item_price': ['$2.39 ', '$3.39 ', '$3.39 ', '$2.39 ', '$16.98 ']}
df = pd.DataFrame(d)
uj5u.com熱心網友回復:
您可以使用:
out = (df
.assign(price=pd.to_numeric(df['item_price'].str.strip('$'), errors='coerce')
.mul(df['quantity']),
choice_description=df['choice_description'].astype(str),
)
.groupby('order_id')
.agg({'item_name': ','.join,
'choice_description': ','.join,
'price': 'sum',
})
.assign(price=lambda d: '$' d['price'].round(2).astype(str))
)
輸出:
item_name choice_description price
order_id
1 Chips and Fresh Tomato Salsa,Izze,Nantucket Nectar,Chips and Tomatillo-Green Chili Salsa nan,[Clementine],[Apple],nan $11.56
2 Chicken Bowl [Tomatillo-Red Chili Salsa (Hot), [Black Beans, Rice, Cheese, Sour Cream]] $33.96
uj5u.com熱心網友回復:
我也是 Pandas 的新手,所以通過回答來學習。
測驗資料為:

你也可以這樣做:
import pandas as pd
df = pd.read_csv('./test-csv.csv')
df['item_price'] = df.item_price.str.replace('$', ' ', regex=True)
df['item_price'] = pd.to_numeric(df.item_price)
res_df = df.groupby('order_id').aggregate({'item_name': ', '.join, 'choice_description': ', '.join}, pd.Series.sum)
df = df.groupby('order_id').aggregate(pd.Series.sum)
res_df['item_price'] = df['item_price']
res_df_item_price = '$' df['item_price'].astype(str)
res_df['item_price'] = res_df_item_price
df = res_df
print(df)
解決方案輸出如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/479714.html
標籤:Python 熊猫 数据框 熊猫-groupby
