为什么DataFrame不会更新?

时间:2017-12-05 00:57:45

标签: python pandas class dataframe

我有这个投资组合类,我想创建一个函数AddStockShares来检查股票是否存在,如果存在,它会将股票数量增加到现有股票,否则就会抛出一个优先股。我用iloc写了一个查询,以便根据给定的stock_ticker获得我想要的股票价值但是当我添加新股票时,股票dataFrame不会更新,即使我在函数中打印结果它是正确的。有什么建议?

import numpy as np
import pandas as pd

class Portfolio(object):
"""description of class"""



array_of_stock_prices = []
array_of_stock_names = []
array_of_shares=[]
stocks = pd.DataFrame(np.column_stack([array_of_stock_prices, array_of_stock_names,array_of_shares]))

def __init__(self):
    print()

def AddStock(self, stock_ticker, stock_price,num_shares):
    if stock_ticker in self.array_of_stock_names:
        raise ValueError('Ticker already exists')
    else:
        self.array_of_stock_names.append(stock_ticker)

    self.array_of_stock_prices.append(stock_price)

    if(num_shares<0):
        raise ValueError('Number of shares cannot be negative,Check again')
    else:
        self.array_of_shares.append(num_shares)

    self.stocks = pd.DataFrame(np.column_stack([self.array_of_stock_names, self.array_of_stock_prices,self.array_of_shares]),
                          columns=['Ticker', 'Price','Shares'])

def BuyStockShares(self, stock_ticker, num_shares):
    if stock_ticker in self.array_of_stock_names:
        x=int(self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares'])+num_shares
        print(x)
     else:
        raise ValueError('Stock does not exist.Add stock first')





por=Portfolio()
por.AddStock('AAPLE',100,200)
por.AddStock('SASA',500,10)
por.AddStock('xv',500,50)
por.BuyStockShares('xv',1000)
print(por.stocks)

1 个答案:

答案 0 :(得分:1)

您需要更新该行。

def BuyStockShares(self, stock_ticker, num_shares):
  if stock_ticker in self.array_of_stock_names:
    self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares']=int(self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares'])+num_shares
  else:
    raise ValueError('Stock does not exist.Add stock first')