jim jarnac
jim jarnac

Reputation: 5152

python pandas: create multiple empty dataframes

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?

Upvotes: 2

Views: 4272

Answers (3)

zipa
zipa

Reputation: 27869

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()')

Upvotes: 3

Ankit Seth
Ankit Seth

Reputation: 31

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]

Upvotes: 0

user508402
user508402

Reputation: 492

  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}

Upvotes: 2

Related Questions