我想更改以下代码的索引。我想从函数中得到相应的x,而不是用close作为索引。有时就像在这个例子中一样,即使我提供4个curr,也只有3个可用。这意味着我不能添加列表作为索引后,随着大小的变化循环。谢谢你的帮助。我应该补充一点,即使设置了索引(x),索引仍然是“接近的”。你知道吗
函数daily\u price\u historical从公共API检索价格。总共有7列,我从中选择了第一列(接近)。你知道吗
功能:
def daily_price_historical(symbol, comparison_symbol, all_data=False, limit=1, 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)
return df
代码:
curr = ['1WO', 'ABX','ADH', 'ALX']
d_price = []
for x in curr:
try:
close = daily_price_historical(x, 'JPY', exchange='CCCAGG').close
d_price.append(close).set_index(x)
except:
pass
d_price = pd.concat(d_price, axis=1)
d_price = d_price.transpose()
print(d_price)
输出:
0
close 2.6100
close 0.3360
close 0.4843
函数
daily_price_historical
返回一个数据帧,因此daily_price_historical(x, 'JPY', exchange='CCCAGG').close
是一个Series
。一个Series
的标题是它的名字,但是你可以用rename来改变它。所以你想:在原始代码中,
d_price.append(close).set_index(x)
引发了一个AttributeError: 'NoneType' object has no attribute 'set_index'
异常,因为列表上的append
返回None
,但该异常是在append
之后引发的,并且被catchallexcept: pass
默默地吞噬。你知道吗记住:不要使用非常危险的:
隐藏任何错误。你知道吗
试试这个小代码
输出
相关问题 更多 >
编程相关推荐