Reputation: 23
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.
Upvotes: 2
Views: 1205
Reputation: 294488
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)
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))
%%timeit
pd.DataFrame(range(10)).transpose()
1000 loops, best of 3: 223 µs per loop
%%timeit
pd.DataFrame([np.arange(10)])
1000 loops, best of 3: 783 µs per loop
%%timeit
pd.DataFrame(np.arange(10).reshape(1, 10))
10000 loops, best of 3: 86.4 µs per loop
EdChum's is clearly more efficient.
Upvotes: 2