我有如下所示的 DateFrame。我需要向 dft(樞軸輸出)添加幾列。第一個計算每天銷售的產品總和,這就像marine,但僅適用于總和列而不是len。我試過 dft['Fruit Total']=df.iloc[:,0:3].sum(axis=1) 但沒有用。我還想為列總和中的每一行添加大于 2 的列計數值。就像在圖片中
df = pd.DataFrame({
'date': ["22.10.2021", "22.10.2021", "22.10.2021", "23.10.2021", "23.10.2021", "25.10.2021", "22.10.2021", "23.10.2021", "22.10.2021", "25.10.2021"],
'Product': ["apple", "apple", "orange", "orange", "apple","apple", "apple", "orange", "orange", "orange"],
'sold_kg': [2, 3, 1, 6, 2,2, 3, 1, 6, 2,]})
df['day']=pd.to_datetime(df['date']).dt.day
dft=df.pivot_table(values='sold_kg', columns ='day', index='Product', aggfunc=[np.sum,len])
dft

uj5u.com熱心網友回復:
采用:
dft=df.pivot_table(values='sold_kg',columns='day', index='Product', aggfunc=['sum','size'])
首先MultiIndex in columns用映射展平:
dft.columns = dft.columns.map(lambda x: f'{x[0]}_{x[1]}')
DataFrame.filter然后按和選擇列sum,對于大于或等于的計數值,使用DataFrame.ge和計數Trues sum:
dft['Fruit Total'] = dft.filter(like='sum').sum(axis=1)
dft['Count >= 2'] = dft.filter(like='size').ge(2).sum(axis=1)
print (dft)
sum_22 sum_23 sum_25 size_22 size_23 size_25 Fruit Total \
Product
apple 8 2 2 3 1 1 12
orange 7 7 2 2 2 1 16
Count >= 2
Product
apple 1
orange 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/478509.html
上一篇:在R中重塑和求和資料幀值
