【问题标题】:Python - Using string array, pass them as input for dataframe name for a functionPython - 使用字符串数组,将它们作为函数的数据框名称的输入传递
【发布时间】:2017-10-12 23:30:14
【问题描述】:

我是 Python 新手,不确定这是否是一种愚蠢的做法(因为我可能有成千上万的股票代码)。我正在尝试传递一个股票代码列表,其中有一个我单独创建的数据框列表。我想根据数组将不同的数据帧传递给函数。对执行此操作的最佳方式有何建议?

    def ind (in_df):
    in_df['CHG']= in_df['Open'] / in_df['Close']
    return ;

STK = ['GOOG','TSLA','AAPL']

for index in range(len(STK)):
    print (STK[index])
    ind(pd.DataFrame[STK[index]])

【问题讨论】:

    标签: python arrays string pandas dataframe


    【解决方案1】:

    你可以像下面这样编写循环。这样您就不必单独调用 len 或单个列表元素。

    STK = ['GOOG','TSLA','AAPL']
    
    for stockCode in STK:
        print (stockCode)
        ind(pd.DataFrame[stockCode])
    

    【讨论】:

    • 为了扩展这个答案,花一些时间阅读有关迭代器和生成器以及可以创建和使用它们的所有方式的友好 Python 文档对您很有帮助。一旦您认为掌握了它们,请阅读 David Beazley 的 Generator Tricks for System Programmers 以及相关教程,让您大吃一惊。它写于 2008 年,我仍然至少每隔一年重读一次。
    • 非常感谢
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2020-12-14
    相关资源
    最近更新 更多