dk213 dk213 - 2 months ago 27
Python Question

Create 1 x n pandas DataFrame

Is there a way to create a 1 x n data frame using pandas? It appears that pandas fills dataframes by column, whereas it would be easier to create dataframes by row with my data.

For example, I currently use pd.DataFrame(range(10)).transpose() to create a one row dataframe, but I'm worried that calling the transpose method is somewhat slowing down my code as I'm working with more data.


Easiest way to do this is to:

import pandas as pd

df = pd.DataFrame([range(10)])


range(10) is inherently 1 dimensional (, 10). It's a mistake to think it is (1, 10). To fix this you specify it as [range(10)]. This is now (1, 10)

Edit to add EdChum's answer and for posterity.

And because @EdChum enjoys answering questions in comments for the time being. Upvote his comment if you like this answer.

import pandas as pd

df = pd.DataFrame(np.arange(10).reshape(1, 10))

I tested these all out for speed.

OP's solution


1000 loops, best of 3: 223 µs per loop

My solution


1000 loops, best of 3: 783 µs per loop

EdChum's solution

pd.DataFrame(np.arange(10).reshape(1, 10))

10000 loops, best of 3: 86.4 µs per loop

EdChum's is clearly more efficient.