Python 循环并添加函数组件作为索引
我想更改以下代码的索引。我不想用“close”作为索引,而是想从函数中得到相应的x。有时就像在这个例子中一样,即使我提供4个curr,也只有3个可用。这意味着,随着大小的变化,在循环之后,我不能将列表添加为索引。谢谢你的帮助。我应该补充一点,即使使用set_索引(x),索引仍保持“关闭” 函数daily_price_history从公共API检索价格。总共有7列,我从中选择了第一列(关闭) 职能:Python 循环并添加函数组件作为索引,python,indexing,Python,Indexing,我想更改以下代码的索引。我不想用“close”作为索引,而是想从函数中得到相应的x。有时就像在这个例子中一样,即使我提供4个curr,也只有3个可用。这意味着,随着大小的变化,在循环之后,我不能将列表添加为索引。谢谢你的帮助。我应该补充一点,即使使用set_索引(x),索引仍保持“关闭” 函数daily_price_history从公共API检索价格。总共有7列,我从中选择了第一列(关闭) 职能: def daily_price_historical(symbol, comparison_sym
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_history
返回一个数据帧,因此daily_price_history(x,'JPY',exchange='CCCAGG')。close
是一个系列。系列
的标题是它的名称,但您可以通过重命名来更改它。所以你想要:
...
close = daily_price_historical(x, 'JPY', exchange='CCCAGG').close
d_price.append(close.rename(x))
...
在原始代码中,d_price.append(close).set_index(x)
引发了一个AttributeError:'NoneType'对象没有属性“set\u index”
异常,因为列表上的append
返回None
,但异常是在append
之后引发的,并且被catchall自动吞没,除了:pass
记住:永远不要使用非常危险的:
try:
...
except:
pass
这会隐藏任何错误。试试这个小代码
输出
0
1WO 2.6100
ADH 0.3360
ALX 0.4843
抱歉,“每日价格历史记录”未在我的系统中运行,这是预定义功能还是自定义功能。(NameError:name'daily_price_historical'未定义)我已添加该函数。这是自定义函数。此行错误:d\u price.append(close)。set\u index(x)
。如果d_price
是一个列表,d_price.append(…)
将返回无。你想做的是d_price.append(close.rename(x))
@SergeBallesta非常感谢。你做到了。它起作用了。我不明白为什么。“d_price.append(close).set_index(x)”不返回无。但索引保持不变。@maf:有关详细信息,请参阅下面的答案。
0
1WO 2.6100
ADH 0.3360
ALX 0.4843