循环多个变量的所有组合

时间:2019-06-04 03:07:13

标签: python pandas

我想查看一个具有多个变量的函数的所有可能输出。要创建所有可能的组合,我将迭代创建元组的组合。但是我不确定如何在循环内的函数中使用这些元组。下面的代码将引发错误。

功能:

def daily_volume_historical(symbol, comparison_symbol, all_data=False, limit=7, aggregate=1, exchange=''):
    url = 'https://min-api.cryptocompare.com/data/histoday?fsym={}&tsym={}&limit={}&aggregate={}'\
            .format(symbol.upper(), comparison_symbol.upper(), limit, aggregate)
    if exchange:
        url += '&e={}'.format(exchange)
    if all_data:
        url += '&allData=true'
    page = requests.get(url)
    data = page.json()['Data']
    df = pd.DataFrame(data)
    df.drop(df.index[-1], inplace=True)
    df['timestamp'] = [datetime.fromtimestamp(d) for d in df.time]
    df.set_index('timestamp')
    return df

代码:

quoted = 'USD', 'EUR',  'JPY',  'SGD',  'HKD',  'IDR',  'AUD',  'PHP',  'CNY',  'INR',  'BTC',  'ETH',  'QASH', 'BCH',  'GUSD', 'USDC', 'GBP'
liqud_mar = 'Bitbank', 'Bitfinex', 'Bithumb', 'BitMEX', 'Bitstamp', 'Cexio', 'Coinbase', 'Coincheck', 'Gemini', 'itBit', 'Kraken', 'OKCoin'
p = list(itertools.product(quoted, liqud_mar))

d_volu = [] 
for x in p:
    volu = daily_volume_historical('QTUM', x[0], exchange= x[1]).volumefrom
    d_volu.append
d_volu = pd.concat(d_volu, axis=1)

错误:

Traceback (most recent call last):
  File "./urlcombin5.py", line 26, in <module>
    volu = daily_volume_historical('QTUM', x[0], exchange= x[1]).volumefrom
  File "./urlcombin5.py", line 15, in daily_volume_historical
    df.drop(df.index[-1], inplace=True)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py", line 2084, in __getitem__
    return getitem(key)
IndexError: index -1 is out of bounds for axis 0 with size 0

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

for a,b in [(a,b) for a in quoted for b in liqud_mar]:
    volu = daily_volume_historical('QTUM', a, exchange= b).volumefrom
    d_volu.append

答案 1 :(得分:0)

答案如下:

combinations = list(itertools.product(base, quoted))
d_volu = []
for a,b in combinations:
try:
    volu = daily_volume_historical(a, b, exchange= 'CCCAGG').set_index('timestamp').volumefrom
    d_volu.append(volu.rename(a))
except:
    pass
d_volu = pd.concat(d_volu, axis=1)
d_volu = d_volu.groupby(d_volu.columns.values, axis=1).sum()