【问题标题】:Python: Use input of a function as part of the name of a data frame within the functionPython:使用函数的输入作为函数中数据框名称的一部分
【发布时间】:2020-12-14 14:27:38
【问题描述】:

我想定义一个可以通过更改输入来获取不同数据帧的函数。例如,与

def test (Source): 
    print('df'+ Source)

我想运行 test('A') 并获取数据帧 df_A,运行 test('B') 并获取数据帧 df_B 等。但它仅将 'df_A' 读取为字符串而不是表。 df_A 和 df_B 是预先定义好的。

谢谢!

【问题讨论】:

    标签: python function dataframe


    【解决方案1】:

    如果你使用 globals(),它将返回一个字典,其中以字符串格式的变量名作为键,变量值作为该键的对应值。

    所以,下面的代码解决了上面的问题

    import pandas as pd
    data = [['Alex',10],['Bob',12],['Clarke',13]]
    df_A = pd.DataFrame(data,columns=['Name','Age'])
    print(df_A)
    
    data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
    df_B = pd.DataFrame(data)
    print(df_B)
    
    def test (Source): 
        formatted_string = "df_"+Source
        if formatted_string in globals().keys():
            print(globals()[formatted_string])
    
    test("A")
    test("B")
    

    【讨论】:

      【解决方案2】:

      打印命令仅打印您使用“df”构建的连接字符串和输入变量源。
      要获取实际数据,需要使用eval()函数,如下:

      def test (Source): 
          return eval('df_' + Source)
      

      这将返回输出,就好像您在 Jupyter 单元格中有 df_a 一样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-21
        • 2017-10-12
        • 1970-01-01
        • 2018-05-11
        • 1970-01-01
        • 1970-01-01
        • 2021-01-08
        • 1970-01-01
        相关资源
        最近更新 更多