Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a vector as a Pandas data frame element

Is it possible to put a vector as an element of dataframe of Pandas?

Let's say I have two np vectors:

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.array([6, 15, 24])

Then, I wonder if I can make some 2x3 table like below.

[1,2,3] | [4,5,6] | [7,8,9]
   6    |    15   |   24 
like image 273
noclew Avatar asked Oct 16 '16 23:10

noclew


2 Answers

you need to use the tolist method on np.array to get pandas to put it how you'd like.

pd.DataFrame(dict(a=a.tolist(), b=b)).T

enter image description here

like image 130
piRSquared Avatar answered Nov 03 '22 01:11

piRSquared


You could pass the a and b as a list of lists, without needing to transpose.

In [2188]: pd.DataFrame([a.tolist(), b.tolist()])
Out[2188]:
           0          1          2
0  [1, 2, 3]  [4, 5, 6]  [7, 8, 9]
1          6         15         24

and, more generically,

In [2202]: pd.DataFrame(x.tolist() for x in [a, b])
Out[2202]:
           0          1          2
0  [1, 2, 3]  [4, 5, 6]  [7, 8, 9]
1          6         15         24
like image 45
Zero Avatar answered Nov 03 '22 00:11

Zero