1

我是 Python 新手,我可以在这里寻求专家的帮助吗?

我希望从https://api.cryptowat.ch/markets/summaries JSON 响应构建一个数据框。基于以下过滤条件

  1. Kraken 列出的货币对(请注意,有海妖期货我不想要那些)
  2. 仅与美元配对的货币,即 aaveusd、adausd....

我正在寻找的理想数据框是(不知何故,excel 完美地加载了下面的 json 截图) Dataframe_Excel_Screenshot

resp = requests.get(https://api.cryptowat.ch/markets/summaries) kraken_assets = resp.json() df = pd.json_normalize(kraken_assets) print(df)

输出:

result.binance-us:aaveusd.price.last result.binance-us:aaveusd.price.high ...
0 264.48 267.32 ...

[1 行 x 62688 列]

当我只是将链接粘贴到浏览器 JSON 响应中时使用双引号 ("),但是当我通过 python 代码获取它时。所有双引号 (") 都更改为单引号 (') 知道为什么吗?尽管我尝试使用 json_normalize 解决它,但随后响应更改为 [1 行 x 62688 列]。我不确定如何处理 1 行 62k 列。我不知道如何以我需要的数据框格式提取确切信息(请参阅 excel 屏幕截图)。

任何帮助深表感谢。谢谢你!

4

2 回答 2

1
  • 结果 JSON 是一个字典
  • 将其加载到数据框中
  • 将列解码为产品和度量
  • 过滤到需要的数据
import requests
import pandas as pd
import numpy as np

# load results into a data frame
df = pd.json_normalize(requests.get("https://api.cryptowat.ch/markets/summaries").json()["result"])

# columns are encoded as product and measure.  decode columns and transpose into rows that include product and measure
cols = np.array([c.split(".", 1) for c in df.columns]).T
df.columns = pd.MultiIndex.from_arrays(cols, names=["product","measure"])
df = df.T

# finally filter down to required data and structure measures as columns
df.loc[df.index.get_level_values("product").str[:7]=="kraken:"].unstack("measure").droplevel(0,1)

样本输出

产品 价格.最后 价格高 价格.低 价格变化百分比 price.change.absolute 体积 成交量报价
海妖:aaveaud 347.41 347.41 338.14 0.0274147 9.27 1.77707 613.281
海妖:aavebtc 0.008154 0.008289 0.007874 0.0219326 0.000175 403.506 3.2797
海妖:aaveeth 0.1327 0.1346 0.1327 -0.00673653 -0.0009 287.113 38.3549
海妖:aaveeur 219.87 226.46 209.07 0.0331751 7.06 1202.65 259205
海妖:aavegbp 191.55 191.55 179.43 0.030559 5.68 6.74476 1238.35
海妖:aaveusd 259.53 267.48 246.64 0.0339841 8.53 3623.66 929624
海妖:adaaud 1.61792 1.64602 1.563 0.0211692 0.03354 5183.61 8366.21
海妖:adabtc 3.757e-05 3.776e-05 3.673e-05 0.0110334 4.1e-07 252403 9.41614
海妖:阿达斯 0.0006108 0.00063 0.0006069 -0.0175326 -1.09e-05 590839 367.706
海妖:adaeur 1.01188 1.03087 0.977345 0.0209986 0.020811 1.99104e+06 1.98693e+06
于 2021-07-18T07:36:16.433 回答
0

你好试试下面的代码。我已经了解了数据集的结构并进行了修改以获得所需的输出。`

resp = requests.get("https://api.cryptowat.ch/markets/summaries")
a=resp.json()
a['result']
#creating Dataframe froom key=result
da=pd.DataFrame(a['result'])
#using Transpose to get required Columns and Index
da=da.transpose()
#price columns contains a dict which need to be seperate Columns on the data frame
db=da['price'].to_dict()
da.drop('price', axis=1, inplace=True)
#intialising seperate Data frame for price
z=pd.DataFrame({})
for i in db.keys():
    i=pd.DataFrame(db[i], index=[i])
    z=pd.concat([z,i], axis=0 )
da=pd.concat([z, da], axis=1)
da.to_excel('nex.xlsx')`
于 2021-07-18T07:30:36.570 回答