[英]How to just put Hours Minutes and seconds in data frame instead of Year , months and days?
I want to plot a line graph of ECG in mV and time in HH:MM:SS:MMM . 我想绘制心电图的线图,单位为mV ,时间为HH:MM:SS:MMM 。 its a 10 second ECG strip. 它是一个10秒的心电图带。
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 我已经提取了Time列,现在我想转换python数据帧中的时间列,然后在图上绘制它
but when I apply to_datetime() function it give me the following error 但是当我应用to_datetime()函数时,它会给我以下错误
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. 请帮我解决这个错误,我只想把%H:%M:%S.%f,因为我没有年,月和日。
See to_timedelta 见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 参考: https : //stackoverflow.com/a/46801500/1855988
You need to specify the format
you want to convert the time to. 您需要指定要将时间转换为的format
。 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. 然后,您可以转换为datetime并使用它们来绘制图形。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.