Python 使用pandas中的DataFrame从JSON数据制作电子表格
现在已经有一些类似的帖子了,但是在关注它们之后,我仍然会遇到一些问题Python 使用pandas中的DataFrame从JSON数据制作电子表格,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,现在已经有一些类似的帖子了,但是在关注它们之后,我仍然会遇到一些问题 trade = client.get_my_trades(symbol=ticker) # fetching all trades made on the ticker IOSTBTC print(trade) json_trade = json.dumps(trade, indent=4) # converting and indenting for easier readability. print(json_trad
trade = client.get_my_trades(symbol=ticker) # fetching all trades made on the ticker IOSTBTC
print(trade)
json_trade = json.dumps(trade, indent=4) # converting and indenting for easier readability.
print(json_trade+"\n")
json_normalised = json_normalize(trade) # normalising with pandas for spreadsheet use
print("Normalised JSON\n", json_normalised)
json_normalised = DataFrame(pandas.read_json("logs.xlsx"))
json_normalised_str = str(json_normalised)
logs = open("logs.xlsx", "w") # creating file to write to
logs.write(json_normalised_str) # writing data to file, oldest first
这段代码运行良好,没有错误。但是,当我检查logs.xlsx时,所有数据都在一列中,它们之间有空格,应该用列分隔
例如,以下是一些JSON数据:
[{'id': 3084149, 'orderId': 7071890, 'price': '0.00000312', 'qty': '400.00000000', 'commission': '0.00041327', 'commissionAsset': 'BNB', 'time': 1522223234240, 'isBuyer': True, 'isMaker': True, 'isBestMatch': True}, {'id': 3084468, 'orderId': 7073272, 'price': '0.00000314', 'qty': '400.00000000', 'commission': '0.00041694', 'commissionAsset': 'BNB', 'time': 1522223910252, 'isBuyer': False, 'isMaker': True, 'isBestMatch': True}]
我想要的是'id'和'orderId'以及'price'(等等)有自己的专栏。有了上面的数据,我将有两行信息。但是,当我使用这些数据时,我得到的是:
我能做什么?您不能使用open(“logs.xlsx”,“w”)
来创建正确的xlsx
文件,因为它会将原始文本(或字节,如果使用wb
)写入文件xlsx
比这更复杂
相反,只需使用pandas.DataFrame.from\u dict
:
data = [{'id': 3084149, 'orderId': 7071890, 'price': '0.00000312', 'qty': '400.00000000', 'commission': '0.00041327', 'commissionAsset': 'BNB', 'time': 1522223234240, 'isBuyer': True, 'isMaker': True, 'isBestMatch': True}, {'id': 3084468, 'orderId': 7073272, 'price': '0.00000314', 'qty': '400.00000000', 'commission': '0.00041694', 'commissionAsset': 'BNB', 'time': 1522223910252, 'isBuyer': False, 'isMaker': True, 'isBestMatch': True}]
df = pd.DataFrame.from_dict(data)
print(df)
# commission commissionAsset id isBestMatch isBuyer isMaker \
# 0 0.00041327 BNB 3084149 True True True
# 1 0.00041694 BNB 3084468 True False True
# orderId price qty time
# 0 7071890 0.00000312 400.00000000 1522223234240
# 1 7073272 0.00000314 400.00000000 1522223910252
然后导出到电子表格就像调用excel
一样简单:
df.to_excel('logs.xlsx')
如果您不喜欢将索引导出到电子表格中,可以使用index=False
:df.to_excel('logs.xlsx',index=False)
。有关更多信息,请参阅。第一部分非常有效,但我似乎无法使用df.to\u excel
写入excel文档。我得到了这个错误:modulenofounderror:No module name'openpyxl'
@decador您要么需要使用pip安装openpyxl
,要么尝试使用另一个引擎,即df.to_excel('logs.xlsx',engine='xlsxwriter')
安装openpyxl
成功!非常感谢你。电子表格现在看起来像你的了。再次,干杯。