Kepasere
Kepasere

Reputation: 87

Create variable from string in python

I have read a lot of posts about this subject but I haven't found an answer to my problem.

Wants to write a function that allows you to create DF with different names and columns.

So I try this:

def createDT(name,c1,c2,c3):
    name = pd.DataFrame(columns = [c1,c2,c3])
    print(type(name))
    return name
createDT(DT,"col1","col2","col3")

and I receive:

NameError: name 'DT' is not defined

when I change the "name" variable to String I receives the message:

<class 'pandas.core.frame.DataFrame'>
and the table below

Which confirms the creation of DF, but if I want to call the DT variable I get a

NameError: name 'DT' is not defined

I know I can do it this way

DT2 = createDT(DT,"col1","col2","col3")

But then I have to name the variables again and I would like to avoid that and I want it to be written as a function. Any ideas on how to solve it?

Upvotes: 4

Views: 264

Answers (2)

U13-Forward
U13-Forward

Reputation: 71570

It's not that easy unfortunately:

def createDT(name,c1,c2,c3):
    globals()[name] = pd.DataFrame(columns = [c1,c2,c3])
    print(type(globals()[name]))
    return globals()[name]
createDT("DT","col1","col2","col3")

But a preferred and efficient solution would be:

def createDT(name,c1,c2,c3):
    return pd.DataFrame(columns = [c1,c2,c3])
createDT("col1","col2","col3")

Upvotes: 4

julka
julka

Reputation: 1212

Wouldn't simple

def createDT(c1,c2,c3):
    temp = pd.DataFrame(columns = [c1,c2,c3])
    print(type(temp))
    return temp

DT = createDT("col1","col2","col3")

work?

In Python you (almost always) don't use function parameters as return value. And you don't need to worry about copying since in Python everything is (kind of like) pointers.

Upvotes: 1

Related Questions