【问题标题】:Plotting 2 variables in Python from an Excel file从 Excel 文件中用 Python 绘制 2 个变量
【发布时间】:2017-02-04 07:50:17
【问题描述】:

我是 Python 初学者。我想从绘图开始学习 Python。

如果有人能帮我写一个脚本来绘制一个 Excel 文件,下面有 2 个变量(速度和方向),我将不胜感激:

日期速度方向
2011 年 3 月 12 日 0:00 1.0964352 10
2011 年 3 月 12 日 0:30 1.1184975 15
2011 年 3 月 12 日 1:00 0.48979592 20
2011 年 3 月 12 日 1:30 0.13188942 45

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    准备数据

    import pandas as pd
    from io import StringIO
    
    data = '''\
    Date            Velocity    Direction 
    3/12/2011 0:00  1.0964352   10 
    3/12/2011 0:30  1.1184975   15 
    3/12/2011 1:00  0.48979592  20 
    3/12/2011 1:30  0.13188942  45
    '''
    df = pd.read_csv(StringIO(data), sep=r'\s{2,}', parse_dates=[0], dayfirst=True)
    

    我在这里使用了一个技巧。因为Date 列中的日期包含由单个空格分隔的时间元素,所以我用两个或多个空格分隔列。这就是我将分隔符作为正则表达式sep=r'\s{2,}' 的原因。但当然,在 CSV 中,列通常用逗号分隔,这使事情变得更容易(sep=',' 这是默认设置)。

    请注意,Date 列已被解析为日期。它的列类型是datetime64

    df.info()
    
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 4 entries, 0 to 3
    Data columns (total 3 columns):
    Date         4 non-null datetime64[ns]
    Velocity     4 non-null float64
    Direction    4 non-null int64
    dtypes: datetime64[ns](1), float64(1), int64(1)
    memory usage: 176.0 bytes
    

    通过将Date 列设置为绘制数据的索引很简单:

    df.set_index('Date').plot()
    

    这将产生一个线图,其中为每个时间戳绘制速度和方向。

    【讨论】:

    • 你可以添加导入,只是为了让它更明显。
    • @gregory 感谢您的提示。我添加了它们。
    • 非常感谢。但是,我得到一个错误: df = pd.read_csv(StringIO(data), sep=r'\s{2,}', parse_dates=[0], dayfirst=True) 你知道为什么吗? TypeError: initial_value 必须是 unicode 或 None,而不是 str
    • 我猜你使用的是 Python 2.7。见这里:stackoverflow.com/questions/22316333/…
    • 哦,顺便说一下,我使用StringIO 仅用于演示目的。无需将纯数据从 XLS 表复制到 python 并使用StringIO。您可以改用read_excel。请参阅 pandas 文件 IO 方法的文档。
    猜你喜欢
    • 2017-12-12
    • 2016-12-21
    • 2020-06-21
    • 1970-01-01
    • 2019-01-16
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多