简体   繁体   English

从 Python 将数据放入 excel 表

[英]Putting Data into excel sheet from Python

I am trying to put the outputs from the kwargs function into an excel sheet with one column of stock symbols, one with the current price.我正在尝试将 kwargs function 的输出放入带有一列股票代码的 excel 表中,其中一列具有当前价格。 The code works just fine with using only the stock names, but the moment I added the price it gives me back this error:该代码仅使用股票名称就可以正常工作,但是当我添加价格时,它给了我这个错误:

MMMTraceback (most recent call last):
  File "C:\Users\sss\Documents\Python Programs\Bot\Td\td4.py", line 52, in <module>

154.95
    get_ohlc(symbol=[row])
  File "C:\Users\sss\Documents\Python Programs\Bot\Td\td4.py", line 43, in get_ohlc
    for symbol, lastPrice in zip(data[symbol],data[lastPrice]):
KeyError: 154.95

Where 154.95 is the last price of that particular stock.其中 154.95 是该特定股票的最后价格。 I am very confused on why it is giving me the price back as the error.我很困惑为什么它把价格作为错误给我。 The relevant code is below and thank you in advance for any help!相关代码如下,提前感谢您的帮助!

import pandas as pd

data_sheet1 = pd.read_excel('C:\\Users\\sss\\Downloads\\companylist.xlsx', index_col=0)
data_impor = data_sheet1.head(10)

workbook = xlsxwriter.Workbook('c:\\Users\\sss\\Documents\\output.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Stock')
worksheet.write('B1', 'Price')

row_1 = 1
col = 0

def get_ohlc(**kwargs):
    data = get_quotes(symbol=kwargs.get('symbol'))
    for symbol in kwargs.get('symbol'):
        print(symbol)
        print(data[symbol]['lastPrice'])
        lastPrice = data[symbol]['lastPrice']
    for symbol, lastPrice in zip(data[symbol],data[lastPrice]):
        global row_1
        worksheet.write(row, col, symbol) 
        worksheet.write(row, col + 1, lastPrice) 
        row += 1
    workbook.close()


for row in data_impor.index:
    get_ohlc(symbol=[row])

I think the problem lies in the below for-loop ,我认为问题在于下面for-loop

for symbol, lastPrice in zip(data[symbol],data[lastPrice]): #on this line data[lastprice]
        global row_1
        worksheet.write(row, col, symbol) 
        worksheet.write(row, col + 1, lastPrice) 
        row += 1

If you want to access a element from a list you cant pass it a value other than index.如果要访问列表中的元素,则不能将索引以外的值传递给它。 And if you are using data[lastPrice] each time and if lastprice is not a index then there will be an error for each access using data[lastPrice]如果您每次都使用data[lastPrice]并且lastprice不是索引,那么使用data[lastPrice]的每次访问都会出错

hope this helps you!希望这对你有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM