2

I am trying to create multiple empty pandas dataframes in the following way:

dfnames = ['df0', 'df1', 'df2'] x = pd.Dataframes for x in dfnames

The above mentionned line returns error syntax. What would be the correct way to create the dataframes?

2
  • 2
    probably df = [ pd.DataFrame() for _ in range(3) ] and then you have list with df[0], df[1], df[2] Commented Dec 28, 2016 at 11:31
  • 1
    To obtain a dict use - {x:pd.DataFrame() for x in dfnames}. Note the extra-parenthesis when calling an empty dataframe. Commented Dec 28, 2016 at 11:55

3 Answers 3

3

If you want to create variables that contain empty DataFrames, this will do what you need:

dfnames = ['df0', 'df1', 'df2']

for x in dfnames: exec(x + ' = pd.DataFrame()')
Sign up to request clarification or add additional context in comments.

Comments

2
  1. the constructor pd.Dataframe must be called like a function, so followed by parentheses (). Now you are refering to the module pd.dataframes (also note the final 's').
  2. the for x-construction you're using creates a sequence. In this form you can't assign it to the variable x. Instead, enclose everything right of the equal sign '=' in () or []
  3. it's usually not a good idea to use the same variable x both at the left hand side and at the right hand side of the assignment, although it won't give you a language error (but possibly much confusion!).
  4. to connect the names in fdnames to the dataframes, use e.g. a dict:

    dataFrames = {(name, pd.DataFrame()) for name in dfnames}

Comments

0

You can't have many data frames within a single variable name, here you are trying to save all empty data frames in x. Plus, you are using wrong attribute name, it is pd.DataFrame and not pd.Dataframes.

I did this and it worked-

dfnames = ['df0', 'df1', 'df2'] x = [pd.DataFrame for x in dfnames]

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.