Home > Software engineering >  Naming dataframe passing it as argument in a function
Naming dataframe passing it as argument in a function

Time:12-23

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.

CodePudding user response:

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)
  • Related