How to create a pandas DataFrame with specified number of rows and columns

Viewed 34529

I'm new to pandas concept, Is it possible to create a DataFrame of size 1 row and column-length of 8.

I tried:

import pandas as pd
df = pd.DataFrame({'Data':[]})

but this only creates one row and one column.

2 Answers

You can specify both index and columns to determine the shape. Values will default to NaN.

pd.DataFrame(index=np.arange(1), columns=np.arange(8))

     0    1    2    3    4    5    6    7
0  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN

Yes, it is possible to create a dataframe of any shape. For example:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,10, size=(1,8)))

Yields:

   0  1  2  3  4  5  6  7
0  1  5  2  3  4  8  7  1

Then we can return the shape of this dataframe using df.shape:

(1, 8)
Related