[英]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)
我想做什么?
正如您在上面的文件中看到的,每個名稱都代表一個感染新冠病毒的城市。 對於每個城市,我需要為每個城市和 plot 保存一個時間序列圖,它使用 x 軸上的日期索引和 y 軸上的確認感染。 一個例子:
由於大數據文件給了我四列,我認為我在解析該文件和選擇正確的值時犯了一個錯誤。 這是我的代碼示例:
# 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()
我還沒有測試過這個特定的代碼。 我希望這對你有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.