收到“ValueError:如果使用所有标量值,则必须在Python

时间:2017-11-07 17:16:15

标签: python json

我在python上运行了以下代码,以便从一开始就检索各种加密货币收盘价。我使用以下代码成功运行它:

tickers = ['USDT_BTC','USDT_BCH','USDT_ETC','USDT_XMR','USDT_ETH','USDT_DASH',
 'USDT_XRP','USDT_LTC','USDT_NXT','USDT_STR','USDT_REP','USDT_ZEC']

我现在已将其更改为如下(包括完整代码)并获得ValueError。

[LN1]

 def CryptoDataCSV(symbol, frequency):

        #Params: String symbol, int frequency = 300,900,1800,7200,14400,86400

        #Returns: df from first available date

        url ='https://poloniex.com/public?command=returnChartData&currencyPair='+symbol+'&end=9999999999&period='+str(frequency)+'&start=0'

        df = pd.read_json(url)

        df.set_index('date',inplace=True)

        df.to_csv(symbol + '.csv')

        print('Processed: ' + symbol)

[LN2]

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

[LN3]

    tickers = 'ETH_BTC','STR_BTC','XMR_BTC','XRP_BTC','LTC_BTC','DASH_BTC',
'ETC_BTC','POT_BTC','OMG_BTC','FCT_BTC','ZEC_BTC','BTS_BTC','VTC_BTC',
'XEM_BTC','MAID_BTC','DGB_BTC','STRAT_BTC','LSK_BTC','XVC_BTC','SC_BTC',
'DOGE_BTC','XBC_BTC','GNT_BTC','EMC2_BTC','CLAM_BTC','RIC_BTC','SYS_BTC',
'DCR_BTC','STEEM_BTC','ZRX_BTC','GAME_BTC','VIA_BTC','NXC_BTC','NXT_BTC'
,'VRC_BTC','NAV_BTC','PINK_BTC','STORJ_BTC','ARDR_BTC','BCN_BTC','CVC_BTC',
'EXP_BTC','LBC_BTC','GNO_BTC','GAS_BTC','OMNI_BTC','XCP_BTC','NEOS_BTC',
'BURST_BTC','AMP_BTC','FLDC_BTC','FLO_BTC','SBD_BTC','BLK_BTC','BTCD_BTC',
'NOTE_BTC','GRC_BTC','PPC_BTC','BTM_BTC','XPM_BTC','NMC_BTC','PASC_BTC',
'NAUT_BTC','BELA_BTC','SJCX_BTC','HUC_BTC','RADS_BTC']

[LN4]

for ticker in tickers:
        CryptoDataCSV(ticker, 86400)
  

我现在收到以下错误:

     

----------------------------------------------- ---------------------------- ValueError Traceback(最近一次调用   最后)in()         1代表股票代码:   ----> 2 CryptoDataCSV(自动收报机,86400)

     CryptoDataCSV中的

(符号,频率)         7 url ='https://poloniex.com/public?command=returnChartData&currencyPair='+ symbol +'& end = 9999999999& period ='+ str(frequency)+'& start = 0'         8   ----> 9 df = pd.read_json(url)        10        11 df.set_index('date',inplace = True)

     

〜\ Anaconda3 \ lib \ site-packages \ pandas \ io \ json \ json.py in   read_json(path_or_buf,orient,typ,dtype,convert_axes,   convert_dates,keep_default_dates,numpy,precise_float,date_unit,   编码,线)       352 obj = FrameParser(json,orient,dtype,convert_axes,convert_dates,       353 keep_default_dates,numpy,precise_float,    - > 354 date_unit).parse()       355       356如果typ =='series'或obj是None:

     解析中的

〜\ Anaconda3 \ lib \ site-packages \ pandas \ io \ json \ json.py(个体经营)       420       421其他:    - > 422 self._parse_no_numpy()       423       424如果self.obj为None:

     

〜\ Anaconda3 \ lib \ site-packages \ pandas \ io \ json \ json.py in   _parse_no_numpy(个体经营)       637如果orient ==“columns”:       638 self.obj = DataFrame(    - > 639次加载(json,precise_float = self.precise_float),dtype = None)       640 elif orient ==“split”:       641 decoding = dict((str(k),v)

      init 中的

〜\ Anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py(自我,   数据,索引,列,dtype,副本)       273 dtype = dtype,copy = copy)       274 elif isinstance(data,dict):    - > 275 mgr = self._init_dict(data,index,columns,dtype = dtype)       276 elif isinstance(data,ma.MaskedArray):       277将numpy.ma.mrecords导入为mrecords

     _init_dict中的

〜\ Anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py(self,   数据,索引,列,dtype)       409个数组= [键中k的数据[k]]       410    - > 411 return _arrays_to_mgr(arrays,data_names,index,columns,dtype = dtype)       412       413 def _init_ndarray(self,values,index,columns,dtype = None,copy = False):

     

〜\ Anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py in   _arrays_to_mgr(arrays,arr_names,index,columns,dtype)5494#计算索引,如果需要5495,如果index为None:    - > 5496 index = extract_index(arrays)5497 else:5498 index = _ensure_index(index)

     

〜\ Anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py in   extract_index(data)5533 5534如果不是索引而不是   raw_lengths:    - > 5535引发ValueError('如果使用所有标量值,则必须传递'5536'一个索引')5537

     

ValueError:如果使用所有标量值,则必须传递索引

1 个答案:

答案 0 :(得分:2)

我刚测试了你的数据,看来你的一些货币对根本不起作用,返回一个形式的json:

{"error":"Invalid currency pair."}

如果返回此内容,pd.read_json会抛出错误,因为它无法将其转换为数据框。

最简单的解决方法是使用try-except大括号并处理任何非工作代码。

broken_tickers = []

for t in tickers:
    url ='https://poloniex.com/public?command=returnChartData&currencyPair={}&end=9999999999&period={}&start=0'.format(t, 86400)

    try:
        df = pd.read_json(url)
    except ValueError:
        broken_tickers.append(t)
        continue

    df.set_index('date')
    df.to_csv('{}.csv'.format(t))

我已经摆脱了这个功能,我觉得这里没有必要,但你可以把它重新加入。