【问题标题】:How to change a String in Python to an Indexed List如何将 Python 中的字符串更改为索引列表
【发布时间】:2020-06-03 17:13:59
【问题描述】:

我通常使用 python-binance 库,但是对于我需要进行的特定调用,它不是最新的。

因此,我尝试使用标准的requests.get 函数,如下所示:

import requests

TakerRatio = requests.get('https://www.binance.com/futures/data/takerlongshortRatio','symbol=BTCUSDT&period=5m&limit=30')
TakerRatio = TakerRatio.text

这会返回我需要的所有数据,但是作为一个字符串:

[{"buySellRatio":"0.8314","sellVol":"418.6670","buyVol":"348.0720","timestamp":1591194900000},{"buySellRatio":"1.1938","sellVol":"284.8710","buyVol":"340.0660","timestamp":1591195200000},{"buySellRatio":"1.1901","sellVol":"377.4750","buyVol":"449.2250","timestamp":1591195500000}]

你们能帮我用最简单的方法把这个字符串变成索引列表吗?我需要能够像您通常那样引用 sellVol 和 buyVol 值,例如查询 TakerRatio[0]['sellVol'] 返回 418.6670。

【问题讨论】:

  • 请求模块也应该返回json,你可以像字典一样使用它。
  • 可能只是TakerRadio.json()
  • 这能回答你的问题吗? How to parse JSON in Python?

标签: python string list serialization binance


【解决方案1】:

似乎你得到的已经是你想要的,唯一的区别是你得到的数字是字符串。您需要做的就是将它们转换回数字。此外,时间戳看起来像POSIX timestamp,但以毫秒为单位。我们可以使用datetime.fromtimestamp 将其转换为合适的日期和时间。

import requests
import datetime

TakerRatio = requests.get('https://www.binance.com/futures/data/takerlongshortRatio','symbol=BTCUSDT&period=5m&limit=30')
data = TakerRatio.json()

for i in data:
    i["buySellRatio"] = float(i["buySellRatio"])
    i["sellVol"] = float(i["sellVol"])
    i["buyVol"] = float(i["sellVol"])
    # The timestamp looks like a POSIX timestamp, but POSIX timestamps are in
    # seconds and the one returned looks like it is in milliseconds
    i["timestamp"] = datetime.datetime.fromtimestamp(i["timestamp"]/1000)


# This will print a number and not a string representation of the number
print(data[0]['sellVol'])

额外

您还可以使用pandas 来更轻松地处理这些数据。之前转换的数据很容易变成熊猫DataFrame

import pandas as pd

df = pd.DataFrame(data)

# Print the first 5 rows in a nice tabular way
print(df.head(5))

这将显示类似

   buySellRatio  sellVol   buyVol           timestamp
0        1.6940  406.295  406.295 2020-06-03 11:55:00
1        1.0489  333.205  333.205 2020-06-03 12:00:00
2        1.0623  209.696  209.696 2020-06-03 12:05:00
3        1.3297  240.111  240.111 2020-06-03 12:10:00
4        2.1152  272.227  272.227 2020-06-03 12:15:00

由此,您可以非常轻松地进行各种操作。

【讨论】:

  • 完美!我知道这会很简单,除了 .json() 答案之外,数据中的 for i 实际上也对我有帮助。谢谢朋友
【解决方案2】:

如果您只想将数据转换为 json,那么您可以:

results = TakerRatio.json()

或者如果请求没有返回json,你可以手动转换:

results = json.loads(TakerRatio.text)

您可以查询数据。例如:

results[0]['sellVol'] # to return 418.6670

【讨论】:

    猜你喜欢
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 2011-10-29
    • 2015-10-24
    • 2014-11-05
    • 2023-03-06
    • 2012-02-15
    相关资源
    最近更新 更多