【问题标题】:How to add on to parameter names in functions?如何在函数中添加参数名称?
【发布时间】:2018-07-18 17:54:28
【问题描述】:
def priceusd(df):
    return df['closeprice'][-1]*btcusdtclose[-1]

此函数使用数据框作为参数,通过将其比特币价格乘以比特币美元价格,得出以美元计价的资产价格。

我想要做的只是让资产的名称成为参数,而不是价格数据来自的数据框。我所有的数据框都被命名为assetbtc。例如 ethbtc 或 neobtc。我希望能够将 eth 传递给函数并返回 ethbtc['closeprice'][-1]*btcusdtclose[-1]

例如,

def priceusd(eth):
    return ethbtc['close'][-1]*btcusdtclose[-1]

我试过了,但没用,但你可以看到我在做什么

def priceusd(assetname):  '{}btc'.format(assetname)['close'][-1]*btcusdtclose[-1].

非常感谢。

【问题讨论】:

标签: python pandas cryptocurrency


【解决方案1】:

在这种情况下没有必要使用eval。正如@wwii 所说,将 DataFrame 存储在字典中,以便您可以轻松地按名称检索它们。

例如

coins_to_btc = {
    'eth': ethbtc,
    'neo': neobtc,
}

那么,

def priceusd(name):
    df = coins_to_btc[name]

    return df['close'][-1]*btcusdtclose[-1]

【讨论】:

    【解决方案2】:

    您应该从包含它的任何内容中获取所需的数据框,而不是尝试使用 str 作为数据框。我的意思是你应该使用你形成的 str 从它所在的位置获取数据帧。

    例如,假设您已将 priceusd 函数放在包含您创建的所有数据框的同一模块中,例如:

    abtc = df1()
    bbtc = df2()
    cbtc = df3() 
    # and so on...
    
    def priceusd(asset):
        asset_container = priceusd.__module__
        asset_name = f'{asset}btc'
        df = getattr(asset_container, asset_name)
        # now do whatever you want with your df (dataframe) 
    

    如果您的代码结构与我假设的不同,您可以替换获取asset_container 的代码。但是你通常应该明白我的意思......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      相关资源
      最近更新 更多