2017-03-15 27 views
0

我的交易,其中有形式(爲簡單起見)的表:最後交易查找從熊貓數據框中

Ticker Timestamp price 
0 AAPL  9:30:00 139 
1 FB   11:33:14 110 

等。現在,我想提取每個股票的當天最後一筆交易,這當然是可能的(假設原始表格被稱爲trades)。

trades['Timestamp']=pd.to_datetime(trades['Timestamp']) 
aux = trades.groupby(['Ticker'])['Timestamp'].max() 
auxdf = aux.to_frame() 
auxdf = auxdf.reset_index() 
closing = pd.merge(left=trades,right=auxdf, left_on=['Ticker','Timestamp'],right_on=['Ticker', 'Timestamp']) 

現在,這可行,但我不確定它是最優雅還是最有效的方法。有什麼建議麼?

+0

trades.groupby([ '北京時間'])最後()將節省您的步驟 – Vaishali

+0

@ A-雜誌-Z啊休息,你的意思。如果交易已經排序(當然,這將是)。謝謝! –

回答

0

嘗試使用IX和idxmax:

trades['Timestamp']=pd.to_datetime(trades['Timestamp'] 
trades.ix[trades.groupby('Ticker').Timestamp.idxmax()]