2014-10-08 7 views
0

그래서 나는 pandas 데이터 프레임의 일부를 선택하는 방법을 마침내 알아 냈습니다. 그러나 이제는 그 안에 데이터를 사용하는 방법에 대해 분실했습니다. 1 분 안에 모든 항목을 함께 추가 할 수 있기를 원합니다.Python with pandas

for minute in rrule.rrule(rrule.MINUTELY, dtstart=pd.datetime.strptime(dateToday+"T15:30","%Y-%m-%dT%H:%M"), until=pd.datetime.strptime(dateToday+"T22:00","%Y-%m-%dT%H:%M")): 
      temp = pageData[(pageData['time']>=minute)&(pageData['time']<minute+timedelta(seconds=60))] 
      print(temp) 
+0

전체 예제 코드를 사용하여 입력 및 출력 예제를 보여줍니다. –

답변

0

알아 냈어. 내가 필요한 것은 생성 된 서브 팬더를 순환시키는 반복 (당신이 무엇이라고 부르는)이었습니다.

#Refrences 
from time import * 
from dateutil import rrule 
from datetime import timedelta 
import urllib.request as web 
import pandas as pd 
import os 

forToday = 'http://netfonds.no/quotes/tradedump.php?csv_format=csv&paper=' 
dateToday = strftime("%Y-%m-%d", localtime()) 
#dateToday = "2014-10-07" 

def pullToday(exchange,stock): 
    hold=[] 
    fileName=('data/'+exchange+'/'+stock+'/'+dateToday+'.txt') 
    try: 
     if not os.path.isdir(os.path.dirname(fileName)): 
      os.makedirs(os.path.dirname(fileName)) 
    except OSError: 
     print("Something went very wrong. Review the dir creation section") 

    pageBuffer=web.urlopen(forToday+stock+'.'+exchange) 
    pageData=pd.read_csv(pageBuffer,usecols=['time','price','quantity']) 
    for i in pageData.index: 
     pageData['time'][i]=pd.datetime.strptime(pageData['time'][i],'%Y%m%dT%H%M%S') 

    print(hold)     
    #pageData = pageData.set_index('time',drop=False) 
    for minute in rrule.rrule(rrule.MINUTELY, dtstart=pd.datetime.strptime(dateToday+"T15:30","%Y-%m-%dT%H:%M"), until=pd.datetime.strptime(dateToday+"T21:58","%Y-%m-%dT%H:%M")): 
     temp = pageData[(pageData['time']>=minute)&(pageData['time']<minute+timedelta(seconds=60))] 
     volume=0 
     priceSum=0 
     low=123456 
     high=0 
     for i in temp.index: 
      volume+=temp['quantity'][i] 
      priceSum+=temp['quantity'][i]*temp['price'][i] 
      if temp['price'][i]>high: 
       high=temp['price'][i] 
      if temp['price'][i]<low: 
       low=temp['price'][i] 
     priceSum/=volume 
     hold.append([minute,volume,low,high,round(priceSum,4)]) 

    minute=pd.datetime.strptime(dateToday+"T21:59","%Y-%m-%dT%H:%M") 
    temp = pageData[(pageData['time']>=minute)&(pageData['time']<minute+timedelta(seconds=180))] 
    volume=0 
    priceSum=0 
    low=123456 
    high=0 
    for i in temp.index: 
     volume+=temp['quantity'][i] 
     priceSum+=temp['quantity'][i]*temp['price'][i] 
     if temp['price'][i]>high: 
      high=temp['price'][i] 
     if temp['price'][i]<low: 
      low=temp['price'][i] 
    priceSum/=volume 
    hold.append([minute,volume,low,high,round(priceSum,4)]) 

    compiledData=pd.DataFrame(hold ,columns=['TimeStamp', 'Volume', 'Low', 'High', 'Average']) 
    #for i in compiledData.index: 
     #compiledData['TimeStamp'][i]-=pd.datetime.strptime(dateToday+"TZ06","%Y-%m-%dTZ%H") 
    print(compiledData) 
    dataFile = open(fileName,'w') 
    dataFile.write('#Format: Timestamp;Volume;Low;High;Median\n') 
    dataFile.close() 
    pageData.to_csv(fileName,index=False,sep=';',mode='a',header=False) 

def getList(fileName): 
    stockList = [] 
    file = open(fileName+'.txt', 'r').read() 
    fileByLines = file.split('\n') 
    for eachLine in fileByLines: 
     if '#' not in eachLine: 
      lineByValues = eachLine.split('.') 
      stockList.append(lineByValues) 
    return stockList 

start_time = time() 

stockList = getList('stocks') 
#for eachEntry in stockList: 
# pullToday(eachEntry[0],eachEntry[1]) 

pullToday('O','AAPL') 

delay=str(round((time()-start_time))) 
print('Finished in ' + delay) 
+0

당신은 그 루프 (루핑은 거의 필요하지 않습니다/goog 아이디어)가 필요하지 않습니다. 예 : 'volume = temp [ 'quantitiy']. sum()' – joris

+0

또한 각 거래 가격에 볼륨을 곱해야했습니다. 내가 루프를 어떻게 사용하는지 알 수있는 유일한 방법. – Samuel

+0

'temp ['quantity '] * temp ['price ']'는 루프 외부에 있습니까? – joris