gpt4 book ai didi

python - 如何绘制以时间序列为行的 Pandas 数据框?

转载 作者:行者123 更新时间:2023-12-02 19:36:58 25 4
gpt4 key购买 nike

我正在尝试绘制这个dataset of COVID-19 deaths作为每个国家死亡人数的时间序列。到目前为止,我已经尝试过这个脚本:

import requests
import pandas as pd
import matplotlib.pyplot as plt


def getdata():
response = requests.get("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv")
with open('data.csv', 'wb') as fp:
fp.write(response.content)


if __name__ == "__main__":
getdata()
df = pd.read_csv('data.csv')

dfg = df.groupby(by='Country/Region').sum()

dfg.drop(labels=['Lat', 'Long'], axis=1, inplace=True)

dfg.columns = pd.to_datetime(dfg.columns)

dfplot = dfg.plot()

plt.show()

它产生一个像这样的数据框:

                    2020-01-22  2020-01-23  2020-01-24  ...  2020-03-25  2020-03-26  2020-03-27
Country/Region ...
Afghanistan 0 0 0 ... 2 4 4
Albania 0 0 0 ... 5 6 8
Algeria 0 0 0 ... 21 25 26
Andorra 0 0 0 ... 1 3 3
Angola 0 0 0 ... 0 0 0
... ... ... ... ... ... ... ...
Venezuela 0 0 0 ... 0 0 1
Vietnam 0 0 0 ... 0 0 0
West Bank and Gaza 0 0 0 ... 0 1 1
Zambia 0 0 0 ... 0 0 0
Zimbabwe 0 0 0 ... 1 1 1

但是,生成的图并不显示时间序列,而是在 X 轴上显示了不同的国家/地区:

enter image description here

我尝试阅读 DataFrame.plot文档来了解如何改变这种行为,但它非常简洁。我有什么想法可以实现这一点吗?

最佳答案

要在 pandas 中实现时间序列图,您的索引应该是日期时间而不是列。而且由于它们的原始数据以日期作为列到达,因此需要进行一些数据 reshape :

  • melt 将原始数据从宽格式 reshape 为长格式,并将日期作为列;
  • pivot_table 聚合并 reshape 为全国范围内的列,并以日期为索引。

然后,按预期调用 DataFrame.plot:

df_deaths = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/"
"csse_covid_19_time_series/time_series_covid19_deaths_global.csv")

# MELT WIDE DATA TO LONG
df_deaths = (df_deaths.melt(id_vars = ['Province/State', 'Country/Region', 'Lat', 'Long'],
var_name = 'Date', value_name = 'Deaths')
.assign(Date = lambda x: pd.to_datetime(x['Date'])))

# PIVOT AGGREGATION TO GENERATE DATE INDEX BY COUNTRY COLUMNS
df_pvt = df_deaths.pivot_table(index='Date', columns='Country/Region',
values='Deaths', aggfunc='sum')

df_pvt.plot(kind='line')

plt.show()

由于上面的情节几乎涵盖了世界上所有国家,因此请考虑仅对少数几个国家进行切片,例如受影响的前 10 个国家并集成 matplotlib Axes更好地控制输出的对象:

top_countries = (df_deaths.groupby('Country/Region')['Deaths'].sum()
.sort_values(ascending=False))

fig, ax = plt.subplots(figsize=(15,6))

(df_pvt.reindex(top_countries.index.values[:10], axis = 'columns')
.plot(kind='line', ax = ax))

plt.show()

Plot Output

关于python - 如何绘制以时间序列为行的 Pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com