如何在具有特定条件的数据帧中添加值



我有一个代码,它输出特定月份在所有商店购买产品的次数;然而,我想知道如何获得3个条件的总和,python将添加特定月份和特定商店的产品。

这是我迄今为止的代码:

df = df.groupby(['Month_Bought'])['Amount_Bought'].sum()
print(df)

输出:

01-2020    27
02-2020    26
03-2020    24
04-2020    23
05-2020    31
06-2020    33
07-2020    26
08-2020    30
09-2020    33
10-2020    26
11-2020    30
12-2020    30

需要分离数据以使数据帧看起来像这样:

Store1   Store2
01-2020    3        24
02-2020    4        22
03-2020    8        16
04-2020    4        19
05-2020    10       21
06-2020    11       21
07-2020    12       14
08-2020    10       20
09-2020    3        30
10-2020    14       12
11-2020    21       9
12-2020    9        21     

假设您的数据很长(一列包含购买产品的商店的值(,您可以按商店和月份进行分组:

import pandas as pd
records = [
{'Month_Bought':'01-2020', 'Amount_Bought':1, 'Store': 'Store1'},
{'Month_Bought':'01-2020', 'Amount_Bought':2, 'Store': 'Store2'},
{'Month_Bought':'02-2020', 'Amount_Bought':2, 'Store': 'Store1'},
{'Month_Bought':'02-2020', 'Amount_Bought':4, 'Store': 'Store2'}
]
df = pd.DataFrame.from_records(records)
# Initial dataframe
Month_Bought  Amount_Bought   Store
0      01-2020              1  Store1
1      01-2020              2  Store2
2      02-2020              2  Store1
3      02-2020              4  Store2
# Now groupby store and month
df_agg = df.groupby(['Store', 'Month_Bought'], as_index=False)['Amount_Bought'].sum()
# Convert from long to wide:
df_agg_pivot = df_agg.pivot(index='Month_Bought', columns='Store', values='Amount_Bought')
# Reformat
df_agg_pivot = df_agg_pivot.reset_index()
df_agg_pivot.columns.name = None
# Final result:
Month_Bought  Store1  Store2
0      01-2020       1       2
1      02-2020       2       4

最新更新