【问题标题】:Parsing an csv file and plotting with Python解析 csv 文件并使用 Python 绘图
【发布时间】:2021-07-09 05:50:32
【问题描述】:

我是 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)

我要做什么?

正如您在上面的文件中看到的,每个名称都代表一个感染新冠病毒的城市。对于每个城市,我需要为每个城市保存一个数据框并绘制一个时间序列图,该图使用 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 和统计信息。

感谢您的宝贵时间。

【问题讨论】:

    标签: python pandas matplotlib data-analysis


    【解决方案1】:

    从 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()
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      • 2012-03-17
      相关资源
      最近更新 更多