【问题标题】:How to use pandas to agg data with different condition for different columns?如何使用 pandas 为不同列聚合具有不同条件的数据?
【发布时间】:2021-07-30 02:52:19
【问题描述】:

Agg by sales

原始数据:

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

收件人:

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

我想用 pandas 计算每个产品和每个销售额的数量,那么 pandas 怎么做呢?

【问题讨论】:

  • 我刚刚使用了 pivot_table 来完成这项工作

标签: python pandas


【解决方案1】:

使用 df 作为您的数据框名称尝试:

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)

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 2022-11-26
    • 2020-01-14
    • 2021-10-31
    • 1970-01-01
    • 2021-11-21
    • 2019-03-04
    • 1970-01-01
    • 2015-08-20
    相关资源
    最近更新 更多