亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何按年份和日期分組,并在 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 關注
  • 231 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號