I want to plot a line graph of ECG in mV and time in HH:MM:SS:MMM . its a 10 second ECG strip.
I Have extract the Time column and now i want to convert the time column in dataframe of python and then plot it on graph
but when I apply to_datetime() function it give me the following error
to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing
please Help me to resolve this error , I only want to put %H:%M:%S.%f because i don not have the year , months and days.
See to_timedelta
Date :
df1 = {'Time':['11:20:15.333','10:00:00.444'],'P1':['102','102'],'P2':['240','247']}
df1 = pd.DataFrame(data=df1)
df1
Code :
df1['Time'] = pd.to_timedelta(df1['Time'])
df1
Result :
Time P1 P2
0 11:20:15.333000 102 240
1 10:00:00.444000 102 247
Reference : https://stackoverflow.com/a/46801500/1855988
You need to specify the format
you want to convert the time to. You can find out more information here about what each symbol means.
# before it is object
df['column_name'] = pd.to_datetime(df['column_name'], format="%H:%M:%S,%f")
df = df.astype('datetime64')
df['column_name'] = pd.to_datetime(df['column_name'], format='%H:%M:%S', errors='coerce').dt.time
# coming back to object
print(df.head())
# print(df.info())
As commented you can add a date to those times. The date can be arbitrary. Then you can convert to datetime and use them to plot your graph.
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
data = {'Time':['11:20:15.333','12:00:00.444', '13:46:00.100'],
'A':[1,3,2],'B':[5,5,4]}
df = pd.DataFrame(data=data)
df["Date"] = "2019-09-09"
df['Datetime'] = pd.to_datetime(df['Date']) + pd.to_timedelta(df['Time'])
df = df[["Datetime", "A", "B"]].set_index("Datetime")
ax = df.plot(x_compat=True)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S.%f"))
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.