在添加带注释的行之前,此代码应返回一个包含数据的pandas数据帧:
代码语言:javascript复制 A TSLA KO abg
Date
2020-09-14 1 1 1 0
2020-09-11 0 0 0 0
2020-09-10 0 0 0 0
2020-09-09 0 0 0 0
2020-09-08 0 0 0 0 但是,在get_price函数中添加了带注释的行之后,sum函数返回了一个错误的值:
代码语言:javascript复制 A I am test TSLA KO abg
Date
2020-09-14 1 9 1 1 0
2020-09-11 0 0 0 0 0
2020-09-10 0 0 0 0 0
2020-09-09 0 0 0 0 0
2020-09-08 0 0 0 0 0 我尝试对数据帧中的所有行求和,但我不知道为什么sum函数返回不需要的值。我想知道如何修复它,是什么导致了这个问题?
代码语言:javascript复制from collections import OrderedDict
import pandas as pd
import datetime as dt
import pandas_datareader as web
#====================================================
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
cmaps=OrderedDict()
print(type(cmaps.items()))
#############
prev=10
endDate=dt.datetime.today().date()
sDate=endDate-pd.to_timedelta(prev,unit='d')
def get_price(tickers): #input is a list or Series
result=pd.DataFrame()
for i in tickers:
try:
df=pd.DataFrame()
df['Adj Close']=web.DataReader(i,'yahoo',sDate,endDate)['Adj Close']
df['MA']=df['Adj Close'].rolling(5).mean()
df.sort_values(ascending=False,inplace=True,by="Date")
df['Higher?']=df['Adj Close']>df['MA']
df['Higher?']=df['Higher?'].astype(int)
result['{}'.format(i)]=df['Higher?']
result[tickers.name]=result.sum(axis=1) #this line causes problem
except Exception as ex: # no date column
print('Ticker', i, 'ERROR', ex)
print(df)
return result
#--------------------------------------------------------------
test=pd.Series(['A','TSLA','KO','abg'])
test=test.str.replace('.','-')
test.name='I am test'
a=get_price(test)
print(a)