为了账号安全,请及时绑定邮箱和手机立即绑定

如何按年份和日期分组,并在 pandas 中汇总总和

如何按年份和日期分组,并在 pandas 中汇总总和

慕仙森 2023-08-22 17:42:32
有人可以告诉我如何找到每月收入,对其进行排序并可视化吗?  Month&Year  |   Monthly Revenue0   2016-11   |   261.96001   2016-11   |   731.94002   2016-06   |   14.62003   2015-10   |   957.57754   2015-10   |  22.36809989    2014-01  |  25.24809990    2017-02  |   91.96009991    2017-02  |  258.57609992    2017-02  |   29.60009993    2017-05  |   243.1600如何显示不同年份各个月份的收入总和
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

  • 查看内嵌评论

  • pandas.to_datetime

  • .dt存取器

    • pandas.Series.dt.year

    • pandas.Series.dt.month

  • pandas.DataFrame.groupby

    • 聚合

  • pandas.DataFrame.plot.barh

import pandas as pd

import matplotlib.pyplot as plt


# setup dataframe

data = {'Month&Year': ['2016-11', '2016-11', '2016-06', '2015-10', '2015-10', '2014-01', '2017-02', '2017-02', '2017-02', '2017-05'],

        'Monthly Revenue': [261.96, 731.94, 14.62, 957.5775, 22.368, 25.248, 91.96, 258.576, 29.6, 243.16]}


df = pd.DataFrame(data)


# convert the Month&Year column to a datetime column

df['Month&Year'] = pd.to_datetime(df['Month&Year'], format='%Y-%m')


# use the .dt accessor to groupby year and month and sum Monthly Revenue

dfg = df.groupby([df['Month&Year'].dt.year, df['Month&Year'].dt.month]).agg({'Monthly Revenue': sum})


# rename the index columns

dfg.index = dfg.index.set_names(['year', 'month'])


# display(dfg)

            Monthly Revenue

year month                 

2014 1              25.2480

2015 10            979.9455

2016 6              14.6200

     11            993.9000

2017 2             380.1360

     5             243.1600


# plot

dfg.plot.barh(figsize=(8, 5), legend=False)

plt.xlabel('Revenue')

plt.xscale('log')

plt.show()

https://img2.sycdn.imooc.com/64e48336000112f705350314.jpg

或者

不是按yearand分组month,而是 groupby date。

# groupby 

dfg = df.groupby(df['Month&Year'].dt.date).agg({'Monthly Revenue': sum})


# plot

dfg.plot.barh(figsize=(8, 5), legend=False)

plt.xlabel('Revenue')

plt.ylabel('Date')

plt.xscale('log')

plt.show()

https://img4.sycdn.imooc.com/64e483440001025505470315.jpg

查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信