Reputation: 243
If I have this list:
list = ['a', 'b', 'c', 'd']
and I convert to a dataframe using:
record = pd.DataFrame(list)
I get this:
0
0 a
1 b
2 c
3 d
How do I get this instead, thanks??
0 1 2 3
0 a b c d
Upvotes: 0
Views: 265
Reputation: 3830
You can transpose it into that format with T
record = pd.DataFrame(data).T
I liked the look of the other ([data])
solution posted, so I thought I'd check which was fastest for interest:
%timeit record = pd.DataFrame(data).T
820 µs ± 181 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit record = pd.DataFrame([data])
981 µs ± 323 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
So it appears that Pandas T does have a performance advantage over building the list within a list first. This held true with 400 entries in the list as well.
And as noted elsewhere - it's not good practice to redefine list as it's a system keyword.
Upvotes: 1
Reputation: 75
This should work:
import pandas as pd
L = ['a','b','c','d']
df = pd.DataFrame([L])
print(df)
Output:
0 1 2 3
0 a b c d
I recommend you don't use the word "list" to name your list.
Upvotes: 1
Reputation: 123
You can just pass in list as [list]
list = ['a', 'b', 'c', 'd']
record = pd.DataFrame([list])
Upvotes: 2
Reputation: 2829
Use transpose()
record = pd.DataFrame(list).transpose()
record
Out[3]:
0 1 2 3
0 a b c d
Additionally, you can use:
pd.DataFrame(list).T
Upvotes: 1