Creating a pandas data frame of a specific size

Viewed 56884

In R, I can do something like this:

myvec <- seq(from =  5, to = 10)^2
mydf <- data.frame(matrix(data = myvec, ncol = 3,byrow = TRUE))
> mydf
  X1 X2  X3
1 25 36  49
2 64 81 100

Notice I can specfiy the shape of the data frame by passing in an ncol parameter. I can then fill it either byrow or bycolumn (in this case by row).

If I were to replicate this in Python/Pandas, it's easy enough to create the sequence:

myData = [x**2 for x in range(5,11) ]

However, how do easily make a dataframe of the same size? I can do something like:

myDF = pd.DataFrame(data = myData)

But what would be the parameters to specify the column/row dimensions?

3 Answers

One way to make a pandas dataframe of the size you wish is to provide index and column values on the creation of the dataframe.

df = pd.DataFrame(index=range(numRows),columns=range(numCols))

This creates a dataframe full of nan's where all columns are of data type object.

Another way to create a data frame with specific number of columns and rows all filled with None or another value repeatly:

df = pd.DataFrame({"col1":["value"]*integer_number_of_rows,"col2":["value"]*integer_number_of_rows})

Then you can fill up the cells with any values you want later.

Related