Suchana Ghosh
Suchana Ghosh

Reputation: 11

Pandas adding multiple null data frames

I want to create about 10 data frames with same number of rows and columns that I want to specify. Currently I am creating a df with the specific rows and then using pd.concat to add column to the data frame. I am having to write 10 lines of code separately for each data frame. Is there a way to do it at one go together for all data frames. Say, all the data frames have 15 rows and 50 columns. Also I don't want to use a loop. All values in the data frame are NaN and I want to perform different function on each data frame so editing one data frame shouldn't change the values of the other data frames.

Upvotes: 0

Views: 283

Answers (3)

Debodeep Kar
Debodeep Kar

Reputation: 1

import pandas as pd

row_num = 15
col_num = 50
temp=[]

for col_name in range(0, col_num):
    temp.append(col_name)

Creation of Dataframe

df = pd.DataFrame(index=range(0,row_num), columns=temp)

this code creates a single data frame in pandas with specified row and column numbers. But without a loop or some form of iteration, multiple lines of same code must be written.

Note: this is a pure pandas implementation. github gist can be found here.

Upvotes: 0

heretolearn
heretolearn

Reputation: 6545

You could do something like this:

index_list = range(10)
column_list = ['a','b','c','d']
for i in range(5):
   locals()["df_" + str(i)] = pd.DataFrame(index=index_list, columns=column_list)

This will create 5 different dataframes (df_1 to df_5) each with 10 rows and 4 columns named a,b,c,d having all values as Nan

Upvotes: 0

Ayush Goel
Ayush Goel

Reputation: 375

You can simply create a numpy array of np.nan, and then create a dataframe:

df = pd.DataFrame(np.zeros([15, 50])*np.nan)

For creating 10 dataframes, you can just run this in a loop and add it to an array.

dfs = []
for i in range(10): 
    dfs.append(pd.DataFrame(np.zeros([15, 50])*np.nan))

Then you can index into dfs and change any value accordingly. It won't impact any other dataframe.

Upvotes: 2

Related Questions