2017-04-04 53 views
0

我的數據是這樣的情節數據框:的Python:日期時間條目

900324492 900405679 900472531 
1 2017-04-03 08:04:09 2017-04-03 07:49:53 2017-04-03 07:52:39 
2 2017-04-03 08:05:36 2017-04-03 07:54:36 2017-04-03 07:52:19 
3 2017-04-03 08:05:28 2017-04-03 07:43:00 2017-04-03 07:50:52 
4 2017-04-03 08:06:05 2017-04-03 07:49:42 2017-04-03 07:53:55 

因此,對於每一列,我有一組時間戳(datetime對象,要準確)。我想做一個散點圖,其中x是df索引或行號(即x=[1,2,3,4,...]),y是一個時間點,例如,如果df中有4行和10列,則x軸應該是1, 2, 3, 4和 爲x=1應該有每個條目一個點的第一排

這似乎是一個簡單的任務,但我掙扎了一下到目前爲止我的代碼:。

df = pd.read_csv('test.csv') 
df2 = df.apply(lambda x : pd.to_datetime(x)) 

fig = plt.figure()                                                                
ax = fig.add_subplot(111)                                                              
y = df2.ix[:, 1]                                                           
x = df2.index.values 
# returns nonsense 
ax.plot(x,y) 
# TypeError: invalid type promotion 
ax.scatter(x=x, y = df2.ix[:,1]) 
# TypeError: Empty 'DataFrame': no numeric data to plot 
df2.ix[:,1].plot() 

測試文件鏈接:test.csv

回答

1

請檢查你的例子,你應該關注to_pydatetime()date2num()np.nan。 (你必須y軸的最後標記爲datetime格式。)

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib.dates as dates 


df = pd.read_csv('test.csv', header=None) 
df2 = df.apply(lambda x : pd.to_datetime(x)) 

fig = plt.figure()                                                                
ax = fig.add_subplot(111)                                                              
y = df2.ix[:, 1]                                                           
x = df2.index.values 

def fix(x): 
    try: 
     return dates.date2num(x.to_pydatetime()) 
    except: 
     return np.nan 

y_lab = [str(e) for e in y] 
y_ = [fix(e) for e in y] 

ax.scatter(x=x, y=y_) 

plt.yticks(y_, y_lab, rotation=0, size=6) 
plt.show() 

enter image description here

+0

謝謝!但你看到y軸?要解讀它並不容易,這有點違背了做它的動機。有沒有辦法解決它,以便它顯示時間,而不是小數? – Pep

+0

你可以使用'num2date()'函數來實現ylabel。 – su79eu7k

+0

這又一次證明對我來說很棘手...... – Pep