Reputation: 363
I have one Excel which is having 10sec frequent data with timestamp ,In that I want where ever 10Sec frequency data is there it should show as On(1) and where frequency timestamp is not matched there it should show as OFF(0) as in Plot.
Sample Data:
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
So,
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
Code:Below is my code;in this I want to plot a graph.
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'))
This On Off should come in plot like On means up and Off means Down.
Thanks in advance.I am new in that Please help.
Upvotes: 0
Views: 307
Reputation: 339775
You are very close. The main point here is that there is only one column in the DataFrame and if you set this column as index df.set_index('timestamp')
, there is not data left to show. So you would first create another column with "on" values (or 1
s) and then reindex the dataframe. Using fill_values
allows you to set the newly created dates to 0
.
Finally just plot
the data.
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()
Upvotes: 1