簡體   English   中英

用熊貓過濾和排序數據

[英]Filtering and sorting data with pandas

我想從API中獲取部分信息,但是我不知道如何過濾數據(我想僅獲取選擇的值,並且如果鍵不包含“ BTC”字符串則不獲取值),我正在嘗試做這樣的事情:

{"BTC_MINT":{"volume":11.00, "high24":0.002, "low24":0.001},
 "BTC_NOTE":{"volume":11.00, "high24":0.002, "low24":0.001}}

我從熊貓開始,但是我不知道這是否合適。

link = 'https://poloniex.com/public?command=returnTicker'
with urllib.request.urlopen(link) as rawdata:
    data = rawdata.readall().decode()
data = json.loads(data)
print(data.items())
data = pd.DataFrame([[cur, last, volume, high24, low24] 
                     for cur, d in data.items() 
                     for last, x, x, x, volume, x, x, high24, low24 in d.items()])

不幸的是,此代碼不起作用。 我收到以下錯誤:

[cur, last, volume, high24, low24] for cur, d, x, w, d, q in data.items() for last, x, x, x, volume, x, x, high24, low24 in d.items()
ValueError: need more than 2 values to unpack

有人可以幫我告訴我該怎么做嗎?

df = pd.DataFrame({symbol: {"baseVolume": data[symbol].get("baseVolume"), 
                            "high24hr": data[symbol].get("high24hr"), 
                            "low24hr": data[symbol].get("low24hr")} 
                   for symbol in data}).T
>>> df.head()
          baseVolume    high24hr     low24hr
BTC_1CR   0.00000000  0.00000000  0.00000000
BTC_ABY   0.01968682  0.00000020  0.00000019
BTC_ADN   0.00000000  0.00000000  0.00000000
BTC_ARCH  0.07205024  0.00004813  0.00004693
BTC_BBR   0.19846259  0.00002123  0.00002115

要只獲取以BTC開頭的索引中的名稱,請執行以下操作:

>>> df[df.index.str.startswith('BTC')].head()

          baseVolume    high24hr     low24hr
BTC_1CR   0.00000000  0.00000000  0.00000000
BTC_ABY   0.01968682  0.00000020  0.00000019
BTC_ADN   0.00000000  0.00000000  0.00000000
BTC_ARCH  0.07205024  0.00004813  0.00004693
BTC_BBR   0.19846259  0.00002123  0.00002115

您可以只將字典(數據)傳遞到pd.Dataframe來創建pandas數據框。 如果要對其進行子集化,使其僅包含其中包含字符串BTC的列,則可以執行以下操作:

df = pd.DataFrame(data)
new_cols = [x for x in df.columns if x.find('BTC') > -1]
new_df = df[new_cols]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM