4

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?

2 Answers 2

4

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")
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much. Could you also describe to me what was the problem and whether writing things this way is good programming practice?
@Kepasere Because when you do name = ... it assigns a variable called name, not DT, also may you accept it as well?
@Kepasere this is absolutely not a good practice, and it is considered an antipattern
@juanpa.arrivillaga Added a better one
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.