Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pandas中的sum函数返回错误的值_Python_Database_Pandas_Dataframe - Fatal编程技术网

Python pandas中的sum函数返回错误的值

Python pandas中的sum函数返回错误的值,python,database,pandas,dataframe,Python,Database,Pandas,Dataframe,在添加带有注释的行之前,此代码应返回包含以下数据的数据帧: A TSLA KO abg 日期 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函数返回了错误的值: A我在测试TSLA KO abg

在添加带有注释的行之前,此代码应返回包含以下数据的数据帧:

A TSLA KO abg
日期
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函数返回了错误的值:

A我在测试TSLA KO abg
日期
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函数返回不需要的值。我想知道如何修复它,以及是什么导致了问题

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)

在for循环的每次迭代中,计算四次和。由于tickers.name列中的累积,总和是正确的(1+2+3+3=9)


只需将有问题的行移出for循环。

在for循环的每次迭代中,您要计算四次总和。由于tickers.name列中的累积,总和是正确的(1+2+3+3=9)

只需将有问题的行移出for循环