简体   繁体   English

当我尝试在 python 中将 pandas 保存为 excel 文件时出错

[英]Error when I try to save pandas as excel file in python

I´m using the following code to get data from websocket and save as excel file, but when I try to open the file, the data is unorganized我正在使用以下代码从 websocket 获取数据并保存为 excel 文件,但是当我尝试打开文件时,数据是杂乱无章的

import websocket
import json
import pandas as pd

df = pd.DataFrame(columns=['timestamp', 'symbol',  'side','size', 'price', 'tickDirection', 'trdMatchID', 'grossValue', 'homeNotional', 'foreignNotional'])

def on_open(ws):
    print("opened")

    auth_data = {
        'op': 'subscribe',
        'args': ['trade:XBTUSD']
    }
    ws.send(json.dumps(auth_data))

def on_message(ws, message):
    message = json.loads(message)
    print('\n',message)
    global df
    df = df.append(message, ignore_index=True)
    df.to_excel (r'D:\python\00trace.xlsx', header=True)
def on_close(ws):
    print("closed connection")

socket = "wss://www.bitmex.com/realtime"                 
ws = websocket.WebSocketApp(socket, 
                        on_open=on_open, 
                        on_message=on_message,
                        on_close=on_close)     
ws.run_forever()

and the excel that I get is:我得到的 excel 是:

在此处输入图像描述

It seems like your message does not have the same columns as your df .您的message似乎与您的df没有相同的列。 You probably need to cast the message JSON object into a DataFrame then rename the columns such that it matches the columns in df .您可能需要将message JSON object 转换为 DataFrame 然后重命名列,使其与df中的列匹配。

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

相关问题 错误:当我尝试读取 excel 文件时,文件不是可识别的 excel 文件 - pandas - Error: File is not a recognized excel file when I try to read an excel file - pandas 当我尝试使用Python在Excel文件中添加日期时出错 - Error when I try to add date in an Excel file using Python 每次在 Python Pandas 中保存 DataFrame 时如何创建新的 excel 文件? - How to create new excel file each time when I save DataFrame in Python Pandas? 当我尝试保存文件时 Python win32com SaveAs2 错误 - Python win32com SaveAs2 error when I try to save file 当我尝试保存文件时 Python 3.2 崩溃 - Python 3.2 crashing when I try to save file Python / Tkinter - 当我尝试保存更改时出现错误消息 - Python / Tkinter - Error message when I try to save changes 当我尝试将 JSON 文件读取为 Pandas 时出错 - Error when I try to read a JSON file as Pandas Django/Pandas - 当我尝试将文件保存到表单时,上传的文件在 / 处出现“MultiValueDictKeyError 错误”,然后是整个数据库 - Django/Pandas - uploaded file gets 'MultiValueDictKeyError at /' followed by the entire database when I try to save the file to a form 如何将Python pandas数据保存到excel文件中? - how to save Python pandas data into excel file? 当我将它保存为 Excel 文件时,如何使用 Pandas 插入一个 Excel 公式? - How can I insert an excel formula using pandas when I save it as an excel file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM