2014-05-01 59 views
2

我經常發現自己想要在另一列中繪製數據,但很難將它們按第3列分組/分列。如何按日期繪製熊貓數據並同時進行分組

假設我有這樣的

enter image description here

片我將如何創造的熊貓一樣的情節?

順便說一句:我喜歡x軸是線性的,而不僅僅是一組彼此相鄰的日期,因爲它給出了關於組內測量彼此接近的想法 - 但是對於在距離太遠的情況下知道如何做到這一點。

UPDATE

從@Ffisegydd答案是非常有益的。然而,我接受答案的速度太快了 - 我發現在實際的Excel表格上試用代碼時,這個問題完全是我的錯,因爲我沒有提供Excel工作表。 @Ffisegydd非常友好,可以根據我的問題手動創建數據框,但使用excel文件有點不同。

我做apoligize。下面是一個Excel文件: https://dl.dropboxusercontent.com/u/3216968/Example.xlsx

這是多遠我得到了(在IPython的筆記本)

import pandas as pd 
import datetime as dt 

path2file = r"C:\Example.xlsx" 
_xl = pd.ExcelFile(path2file) 
df = pd.read_excel(path2file, _xl.sheet_names[0], header=0) 
df 

enter image description here

df.Date = df.Date.apply(lambda x: dt.datetime.strptime(x, '%Y.%m.%d').date()) 
df 

enter image description here

這裏是哪裏出了問題:

pd.DataFrame(data= [df.Data, df.Group], columns = ['Data', 'Group'], index=df.Date) 

給予此錯誤

--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-9-231baa928f67> in <module>() 
----> 1 pd.DataFrame(data= [df.Data, df.Group], columns = ['Data', 'Group'], index=df.Date) 

C:\Python27\lib\site-packages\pandas\core\frame.pyc in __init__(self, data, index, columns, dtype, copy) 
    245       index = _default_index(len(data)) 
    246      mgr = _arrays_to_mgr(arrays, columns, index, columns, 
--> 247           dtype=dtype) 
    248     else: 
    249      mgr = self._init_ndarray(data, index, columns, dtype=dtype, 

C:\Python27\lib\site-packages\pandas\core\frame.pyc in _arrays_to_mgr(arrays, arr_names, index, columns, dtype) 
    4471  axes = [_ensure_index(columns), _ensure_index(index)] 
    4472 
-> 4473  return create_block_manager_from_arrays(arrays, arr_names, axes) 
    4474 
    4475 

C:\Python27\lib\site-packages\pandas\core\internals.pyc in create_block_manager_from_arrays(arrays, names, axes) 
    3757   return mgr 
    3758  except (ValueError) as e: 
-> 3759   construction_error(len(arrays), arrays[0].shape[1:], axes, e) 
    3760 
    3761 

C:\Python27\lib\site-packages\pandas\core\internals.pyc in construction_error(tot_items, block_shape, axes, e) 
    3729   raise e 
    3730  raise ValueError("Shape of passed values is {0}, indices imply {1}".format(
-> 3731   passed,implied)) 
    3732 
    3733 def create_block_manager_from_blocks(blocks, axes): 

ValueError: Shape of passed values is (2,), indices imply (2, 12) 

或做這個

pd.DataFrame({'data': df.Data, 'group': df.Group}, index=df.Date) 

enter image description here

+1

我已經編輯我的答案:)存在與實際的答案更詳細的評論。 – Ffisegydd

回答

3

您可以創建一個groupby對象,然後迭代組和圖。

下面是一些代碼,它將您的數據和繪製兩個「組」。還有一些額外的格式可以使圖形看起來很好。

import matplotlib.pyplot as plt 
import pandas as pd 
import datetime as dt 

path2file = r"Example.xlsx" 
_xl = pd.ExcelFile(path2file) 
df = pd.read_excel(path2file, _xl.sheet_names[0], header=0) 

df.Date = df.Date.apply(lambda x: dt.datetime.strptime(x, '%Y.%m.%d').date()) 
df.index = df.Date # Set the Date column as your index 
del df['Date'] # Remove the Date column from your data columns 

grouped = df.groupby('Group') # groupby object 

# Normally you would just iterate using "for k, g in grouped:" but the i 
# is necessary for selecting a color. 
colors = ['red', 'blue'] 
for i, (k, g) in enumerate(grouped): 
    plt.plot_date(g['Data'].index, g['Data'], linestyle='None', marker='o', mfc=colors[i], label=k) 

plt.legend() 
plt.gcf().autofmt_xdate() # Format the dates with a diagonal slant to make them fit. 

# Pad the data out so all markers can be seen. 
pad = dt.timedelta(days=7) 
plt.xlim((min(df.index)-pad, max(df.index)+pad)) 
plt.ylim(0,6) 

Plot

+0

非常感謝你。當試圖使您的答案在真正的Excel文件上工作時遇到一些問題。請參閱我的問題 – Norfeldt

+0

的更新部分謝謝!多麼好的做法 – Norfeldt

+0

爲什麼標籤(傳說)有2個點? – Norfeldt

1

這應該工作

df.pivot_table(rows=['Date'], cols=['Group'], values=['Data']).plot() 

但要知道,每一個數據點的將是一個在給定日期的特定組中的數據點的「平均值」

+0

@Ffisegydd我儘可能喜歡他的建議(因爲有些人在看這個問題可能需要這樣的解決方案),但你的答案正確的答案是我的問題。 – Norfeldt

+0

@Ffisegydd我同意你的評論。但是,它可能仍然有助於那些「所有」點都不是要求的人。如果事實並非如此,將刪除答案 – user1827356

+0

@ user1827356如果您有更多列,該怎麼辦?你會如何選擇數據列? – Norfeldt