Given
data= [
(array([0,0,1]),1),
(array([0,1,1]),1),
(array([1,0,1]),0),
(array([1,1,1]),1)
]
How can you convert it to a Pandas DataFrame so that each column is separate?
A B C Z
0 0 1 1
0 1 1 1
1 0 1 0
1 1 1 1
I'd use np.append
in a list comprehension
pd.DataFrame([np.append(*row) for row in data], columns=list('ABCZ'))
A B C Z
0 0 0 1 1
1 0 1 1 1
2 1 0 1 0
3 1 1 1 1
Or more efficiently with np.column_stack
and zip
pd.DataFrame(np.column_stack(list(zip(*data))), columns=list('ABCZ'))
A B C Z
0 0 0 1 1
1 0 1 1 1
2 1 0 1 0
3 1 1 1 1
Timing
%timeit pd.DataFrame([np.append(*row) for row in data], columns=list('ABCZ'))
1000 loops, best of 3: 460 µs per loop
%timeit pd.DataFrame(np.column_stack(list(zip(*data))), columns=list('ABCZ'))
10000 loops, best of 3: 130 µs per loop
%timeit pd.DataFrame([e[0].tolist()+[e[1]] for e in data],columns=['A','B','C','Z'])
1000 loops, best of 3: 446 µs per loop
Convert your array to a list of lists and then put it into a Dataframe.
pd.DataFrame([e[0].tolist()+[e[1]] for e in data],columns=['A','B','C','Z'])
Out[265]:
A B C Z
0 0 0 1 1
1 0 1 1 1
2 1 0 1 0
3 1 1 1 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With