简体   繁体   English

命名数据框将其作为函数中的参数传递

[英]Naming dataframe passing it as argument in a function

I want to know how I can build a function where I can pass the name of the dataframe that I will create as argument.我想知道如何构建一个函数,我可以在其中传递我将创建的数据框的名称作为参数。

Here I have an example:这里我有一个例子:

list1 = [1,2,3]
list2 = [4,5,6]

def say_hi(list1, list2):
    lists = zip(list1, list2)
    df = pd.DataFrame(lists, columns=('A', 'B'))
    return df

I created a dataframe called df with 3 rows and 2 columns.我创建了一个名为 df 的数据框,其中包含 3 行和 2 列。

My objective is that:我的目标是:

def say_hi(list1, list2, DATAFRAME_NAME):
    lists = zip(list1, list2)
    DATAFRAME_NAME = pd.DataFrame(lists, columns=('A', 'B'))
    return DATAFRAME_NAME

I created a dataframe called DATAFRAME_NAME with 3 rows and 2 columns.我创建了一个名为 DATAFRAME_NAME 的数据框,其中包含 3 行和 2 列。 Which I gave its name passing an argument.我通过一个论点给它起了名字。

Obviously you cannot apply in this way but I want to know how I could do that.显然你不能以这种方式申请,但我想知道我该怎么做。

use the globals() function instead:使用 globals() 函数代替:

import pandas as pd

def say_hi(list1, list2, df_name):
    lists = zip(list1, list2)
    df = pd.DataFrame(lists, columns=('A', 'B'))
    globals()[df_name] = df
    return df

list1 = [1,2,3]
list2 = [4,5,6]

say_hi(list1, list2, "my_df")
print(my_df)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM