我被困在一个查询中,请从中退出。
查询:我有一个函数,每1分钟运行一次,它输出一个数据帧。我想每分钟后将此数据帧转换为excel .xlsx文件。换句话说,我想更新或重写该Excel文件。
def BANK_NIFTY_LIVE_DATA():
import threading
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
writer = pd.ExcelWriter('try_try_try.xlsx')
Base_url = "https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17&segmentLink=17"
page = requests.get(Base_url)
soup = BeautifulSoup(page.content, "lxml")
stock_table=soup.find_all('table', id = 'octable')
stock_table=stock_table[0]
list=[]
for row in stock_table.find_all('tr'):
for cell in row.find_all('td'):
list.append(cell.text)
final_list = [l.replace('\t','').replace('\n','').replace('\r','').replace(',','').replace(' ','') for l in list]
while("" in final_list):
final_list.remove("")
del final_list[924:]
f_final_list=[]
for i in final_list:
if i=='-':
f_final_list.append(i)
else:
f_final_list.append(float(i))
new_list = [f_final_list[i:i+21] for i in range(0, len(f_final_list), 21)]
df=pd.DataFrame.from_dict(new_list)
colnames=['CALLS OI','CALLS CHNG IN OI','CALLS VOLUME','CALLS IV','CALLS LTP','CALLS NET CHNG','CALLS BID QTY','CALLS BID PRICE','CALLS ASK PRICE','CALLS ASK QTY','STRIKE PRICE','PUTS BID QTY','PUTS BID PRICE','PUTS ASK PRICE','PUTS ASK QTY','PUTS NET CHNG','PUTS LTP','PUTS IV','PUTS VOLUME','PUTS CHNG IN OI','PUTS OI']
df.columns=colnames
df.to_excel(writer, sheet_name="sheet1")
writer.save()
writer.close()
print("working good")
timer=threading.Timer(20.0,BANK_NIFTY_LIVE_DATA)
timer.start()
答案 0 :(得分:0)
鉴于您要问的是:
import pandas as pd
def output(df1):
df1.to_excel("d:\\output.xlsx")
def fun(i):
df1 = pd.DataFrame([[i, 'b'], [i, 'd']],index=['row 1', 'row 2'],columns=['col 1', 'col 2'])
output(df1)
for i in range(4):
fun(i)
输出将是:
col 1 col 2
row 1 3 b
row 2 3 d
文件被覆盖。
使用.to_excel
它是将df保存为excel格式的简单功能。
例如检查:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html
希望有帮助。