【问题标题】:Timestamp as On Off in plot using python时间戳在使用 python 的绘图中为 On Off
【发布时间】:2018-03-16 06:46:46
【问题描述】:

我有一个 Excel,它有 10 秒的频繁数据和时间戳,因为我希望那里有 10 秒的频率数据应该显示为 On(1),而频率时间戳不匹配的地方应该显示为 OFF(0 ) 和情节一样。

样本数据:

timestamp
1/6/2017 0:00:10
1/6/2017 0:00:20
1/6/2017 0:00:40
1/6/2017 0:00:50
1/6/2017 0:01:00

所以,

timestamp
    1/6/2017 0:00:39 timestamp is there ON
    1/6/2017 0:00:49 timestamp is not there Off
    1/6/2017 0:00:59 timestamp is there ON
    1/6/2017 0:01:09 timestamp is not there Off
    1/6/2017 0:01:19 timestamp is there ON
    1/6/2017 0:01:29 timestamp is there ON
    1/6/2017 0:01:39 timestamp is there ON

代码:下面是我的代码;在此我想绘制一个图表。

import matplotlib.pyplot as plt
import pandas as pd
import matplotlib
matplotlib.style.use('ggplot')
#reading CSv
df = pd.read_csv('test.csv', parse_dates=['timestamp'])
print (df)


#set Index
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.set_index('timestamp')
print (df)


#reindexing   
df.reindex(pd.date_range(start=df.index[0], end=df.index[-1], freq='30s'))

这个 On Off 应该出现在情节中,例如 On 表示向上,Off 表示向下。

提前谢谢。我是新来的,请帮忙。

【问题讨论】:

  • 什么时候需要帮助?问题出在哪里?你还试过什么?请参阅How to Askedit 相应的问题。
  • 抱歉以错误的方式写问题。请检查更新

标签: python matplotlib timestamp


【解决方案1】:

你很亲密。这里的要点是DataFrame中只有一列,如果将此列设置为索引df.set_index('timestamp'),则没有数据可显示。因此,您将首先使用“on”值(或1s)创建另一列,然后重新索引数据框。使用fill_values 可以将新创建​​的日期设置为0。 最后只是plot 数据。

u = u"""timestamp
1/6/2017 0:00:10
1/6/2017 0:00:20
1/6/2017 0:00:40
1/6/2017 0:00:50
1/6/2017 0:01:00
1/6/2017 0:01:30
"""

import io
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')

#reading CSv
df = pd.read_csv(io.StringIO(u), parse_dates=['timestamp'])
# create new column of `1`s
df["On"] = [1]*len(df)

df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.set_index('timestamp')

df = df.reindex(pd.date_range(start=df.index[0], end=df.index[-1], freq='10s'), 
                fill_value=0)

df.plot()

plt.show()

【讨论】:

  • 其显示错误如;ValueError: 'timestamp' is not in list
  • 它的工作,小错误。我们可以导出这个情节吗??正确显示哪个时间它会显示为 up 和missing 会显示为 down?
  • 情节已经显示了最初出现的时间和失踪的时间,对吧?要导出绘图,您可以使用plt.savefig
  • 在保存无花果时显示空白。我想保存所需的位置。
  • 如果我想给频率小于 1 分钟我们怎么给?
猜你喜欢
  • 2017-02-19
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 2021-05-28
相关资源
最近更新 更多