简体   繁体   中英

How to use pandas to agg data with different condition for different columns?

Agg by sales

Original Data:

Sales Product Qty
James apple 10
Johnson apple 1
Jessie banana 2
Judy melon 5
James melon 5
Jessie apple 8

To:

Sales Apple Melon Banana Total
James 10 5 0 15
Judy 0 5 0 5
Jessie 8 0 2 10
Johnson 1 0 0 1

I'd like to calcuate the amount for each product and group by each sales with pandas, so how to do this by pandas?

With df as your dataframe name Try:

temp_df = df.pivot_table(index='Sales', columns='Product', aggfunc=sum)
cols = [ind[1] for ind in np.array(temp_df.columns)]
data = np.array(temp_df)
final_df = pd.DataFrame({'Sales':temp_df.index})
for i, col in enumerate(cols):
    final_df = pd.concat((final_df, pd.DataFrame({col:data[:, i]})), axis=1)
final_df = final_df.fillna(0)
final_df['total'] = final_df.iloc[:, 1:].sum(axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM