我有一個python程序,其中我讀取一個csv文件到熊貓數據框上。然後我想用日期時間以乾淨的格式繪製我的傳感器值。我的代碼給出錯誤ValueError:時間數據'2017/02/17'與格式不匹配'%Y /%m /%d%H:%M:%S.%f。 我的代碼和數據幀從某些行低於:使用熊貓繪製日期時間
代碼:
import pandas as pd
from datetime import datetime
import csv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
headers = ['Sensor Value','Date','Time']
df = pd.read_csv('C:/Users\Lala Rushan\Downloads\DataLog.CSV', parse_dates= {'Datetime': [1,2]},names=headers)
print (df)
df['Datetime'] = df['Datetime'].map(lambda x: datetime.strptime(str(x), "%y/%m/%d , %H:%M:%S.%f"))
#datetime.strptime(df['Datetime'],"%Y/%m/%d %H:%M:%S.%f")
x = df['Datetime']
y = df['Sensor Value']
# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
plt.show()
數據框:
Datetime Sensor Value
0 2017/02/17 19:06:17.188 2
1 2017/02/17 19:06:22.360 72
2 2017/02/17 19:06:27.348 72
3 2017/02/17 19:06:32.482 72
4 2017/02/17 19:06:37.515 74
5 2017/02/17 19:06:42.580 70
6 2017/02/17 19:06:47.660 72
我怎樣才能解決這個問題?我是python的新手,所以請原諒任何基本的錯誤。
它告訴你,你的日期不符合格式字符串。問題是爲什麼錯誤表示日期字符串是「2017/02/17」',但是您發佈的數據框看起來應該是'「2017/02/17 19:06:17.188」'(也請注意無逗號)或類似。 –
是的,這就是我在想什麼,並堅持。你能修改代碼來工作嗎?我是python的新手。 – rushan
只需使用'pandas'的日期時間分析器:'df ['Datetime'] = pd.to_datetime(df ['Datetime'])'嘗試使用'map'解析每行值。如果整個格式一致,這應該將整個字段解析爲'datetime'。 – Abdou