简体   繁体   中英

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.

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. 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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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