解析 csv 文件并使用 Python 绘图

Parsing an csv file and plotting with Python

我是 Python 开发的新手,我必须实施一个数据分析项目。我有一个具有以下值的 data.txt 文件:

ID,name,date,confirmedInfections
DE2,BAYERN,2020-02-24,19
.
.
DE2,BAYERN,2020-02-25,19
DE1,BADEN-WÜRTTEMBERG,2020-02-24,1
.
.
DE1,BADEN-WÜRTTEMBERG,2020-02-26,7
.
.(lot of other names and data)

我想做什么?

正如您在上面的文件中看到的,每个名称都代表一个感染了 covid 的城市。对于每个城市,我需要为每个城市保存一个数据框,并绘制一个时间序列图,该图使用 x 轴上的日期索引和 y 轴上的 confirmedInfections 索引。一个例子:

由于给我的大数据文件有四列,我认为我在解析该文件和选择正确值时犯了一个错误。这是我的代码示例:

# Getting the data fron Bayern city
data = pd.read_csv("data.txt", index_col="name")
first = data.loc["BAYERN"]
print(first)

# Plotting the timeseries
series = read_csv('data.txt' ,header=0, index_col=0, parse_dates=True, squeeze=True)
series.plot()
pyplot.show()

这是结果的照片:

正如您在 x 轴上看到的那样,我得到了 data.txt 中包含的所有不同 ID。从中排除每个城市的 ID 和统计信息。

感谢您的宝贵时间。

读取 CSV 后需要解析日期

import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
# You can limit the columns as below provided
headers = ['ID','name','date','confirmedInfections']
data = pd.read_csv('data.csv',names=headers)

data['Date'] = data['Date'].map(lambda x: datetime.strptime(str(x), '%Y/%m/%d'))
x = data['Date']
y = data['confirmedInfections']

# Plot using pyplotlib
plt.plot(x,y)
# display chart
plt.show()

我还没有测试过这个特定的代码。 我希望这对你有用