[英]Pandas: groupby multiple columns for bar graph
I have a CSV of financial data that is listed by:我有一个 CSV 的财务数据,由以下人员列出:
The dataset looks like the following, with another hundred rows.数据集如下所示,还有一百行。 I am trying to use pandas to graph this data by month and then the total by each category.
我正在尝试使用 pandas 按月绘制此数据,然后按每个类别绘制总数。 An example would be a bar graph of each month (Jan - Dec) with a bar for the total of each Category type (Food & Drink, Shopping, Gas).
一个例子是每个月(1 月 - 12 月)的条形图,每个类别类型(食品和饮料、购物、加油站)的总数都有一个条形图。
Date Category Amount
0 12/29/2022 Food & Drink -28.35
1 12/30/2022 Shopping -12.12
2 11/30/2022 Food & Drink -12.30
3 11/30/2022 gas -12.31
4 10/30/2022 Food & Drink -6.98
....
My initial code worked, but totaled everything in the month and didn't separate by category type.我的初始代码有效,但汇总了当月的所有内容,并且没有按类别类型分开。
df['Transaction Date'] = pd.to_datetime(df['Transaction Date'], format='%m/%d/%Y') df = df.groupby(df['Transaction Date'].dt.month)['Amount'].sum()
My next try to separate the monthly information out by Category failed.我的下一次尝试按类别分离每月信息失败了。
df = df.groupby((df['Transaction Date'].dt.month),['Category'])['Amount'].sum()
How can I graph out each month by the sum of Category type?我如何根据类别类型的总和绘制出每个月的图表?
You can create a new column for months within the data frame and then groupby months and category columns您可以在数据框中为月份创建一个新列,然后按月份和类别列进行分组
df['Months'] = df['Transaction Date'].dt.month_name()
df = df.groupby(['Months', 'Category']).agg({'Amount':'sum'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.