【问题标题】:Timeseries from CSV data (Timestamp and events)来自 CSV 数据的时间序列(时间戳和事件)
【发布时间】:2017-09-29 19:55:27
【问题描述】:

我想使用 python 的 pandas 模块(参见下面的链接)通过时间序列表示来可视化 CSV 数据,如下所示。

df1的样本数据:

             TIMESTAMP  eventid
0  2017-03-20 02:38:24        1
1  2017-03-21 05:59:41        1
2  2017-03-23 12:59:58        1
3  2017-03-24 01:00:07        1
4  2017-03-27 03:00:13        1

“eventid”列始终包含值 1,我试图显示数据集中每一天的事件总和。是

pandas.Series.cumsum() 

用于此目的的正确函数?

到目前为止的脚本:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df1 = pd.read_csv('timestamp01.csv')
print df1.columns # u'TIMESTAMP', u'eventid'

# I: ts = pd.Series(df1['eventid'], index=df1['TIMESTAMP']) 
# O: Blank plot

# I: ts = pd.Series(df1['eventid'], index=pd.date_range(df1['TIMESTAMP'], periods=1000)) 
# O: TypeError: Cannot convert input ... Name: TIMESTAMP, dtype: object] of type <class 'pandas.core.series.Series'> to Timestamp

# working test example:
# I: ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
# O: See first link below (first plot).

ts = ts.cumsum()
ts.plot()
plt.show()

我尝试过的链接:

http://pandas.pydata.org/pandas-docs/stable/visualization.html

Aggregating timeseries from sensors

(上面的例子有不同的值,而不是我的 'eventid' 数据)

d3: timeseries from data

非常感谢任何帮助。

【问题讨论】:

    标签: python pandas matplotlib dataframe time-series


    【解决方案1】:

    看来您需要通过read_csv 中的参数parse_datesTIMESTAMP 列转换为datetime

    import pandas as pd
    from pandas.compat import StringIO
    
    temp=u"""TIMESTAMP,eventid
    2017-03-20 02:38:24,1
    2017-03-20 05:38:24,1
    2017-03-21 05:59:41,1
    2017-03-23 12:59:58,1
    2017-03-24 01:00:07,1
    2017-03-27 03:00:13,1"""
    #after testing replace 'StringIO(temp)' to 'filename.csv'
    df = pd.read_csv(StringIO(temp),  parse_dates=True, index_col='TIMESTAMP')
    print (df)
                         eventid
    TIMESTAMP                   
    2017-03-20 02:38:24        1
    2017-03-20 05:38:24        1
    2017-03-21 05:59:41        1
    2017-03-23 12:59:58        1
    2017-03-24 01:00:07        1
    2017-03-27 03:00:13        1
    
    print (df.index)
    DatetimeIndex(['2017-03-20 02:38:24', '2017-03-20 05:38:24',
                   '2017-03-21 05:59:41', '2017-03-23 12:59:58',
                   '2017-03-24 01:00:07', '2017-03-27 03:00:13'],
                  dtype='datetime64[ns]', name='TIMESTAMP', freq=None)
    

    然后通过days 使用resample 并通过size 函数获取计数。最后Series.plot

    print (df.resample('D').size())
    TIMESTAMP
    2017-03-20    2
    2017-03-21    1
    2017-03-22    0
    2017-03-23    1
    2017-03-24    1
    2017-03-25    0
    2017-03-26    0
    2017-03-27    1
    Freq: D, dtype: int64
    
    df.resample('D').size().plot()
    

    如果需要更改tickers的格式:

    import matplotlib.ticker as ticker
    
    ax = df.resample('D').size().plot()
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(df.index.strftime('%Y-%m-%d')))
    

    【讨论】:

    • 感谢您的回答,帮助很大。样本数据一切正常:dropbox.com/s/bcm47bot2n7civo/timeseries_test.png?dl=0 但是对于真正的 csv 数据:dropbox.com/s/b1y8n862350vvuv/timeseries_from_csv.png?dl=0 y 值接近于零,最后在 x 轴的右端附近爆炸。代码中唯一改变的是StringIO(temp) into 'timestamp01.csv' .. 知道是什么导致了这个奇怪的情节吗?
    • 可能需要参数rotax=df.set_index('TIMESTAMP').resample('D').size().plot(rot=90)
    • 我添加了 rot=90,但情节保持不变..有什么想法吗?
    • x的值没有改变?也许最后需要添加plt.show()imports - import matplotlib.pyplot as plt
    • 不会改变情节。它与将索引更改为时间戳有关吗?我现在正在尝试: df = pd.read_csv('timestamp01.csv', parse_dates=True, index_col='TIMESTAMP') import matplotlib.ticker as ticker ax=df.set_index('TIMESTAMP').resample('D' ).size().plot(rot=9‌​0) ax.xaxis.set_major_formatter(ticker.FixedFormatter(df.index.strftime('%Y-%m-%d'))) ax.set_ylim([-1 , 1]) plt.show()
    【解决方案2】:

    另一种绘图方法是使用 groupby 并计算出现次数:

    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.read_csv('timestamp01.csv', parse_dates=[0], index_col=[0]) # set timestamp as index
    ts = df.groupby(df.index.date).count() # count occurrences
    ax = ts.plot() # plot
    plt.setp(ax.xaxis.get_majorticklabels(), rotation=10) # format x axis
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 1970-01-01
      • 2018-04-17
      • 2013-07-09
      • 2014-02-11
      • 2014-05-22
      • 1970-01-01
      • 2013-03-24
      • 2011-01-07
      相关资源
      最近更新 更多