How to convert numpy array to pandas dataframe

How to convert numpy array to pandas framework?

eg:

test = np.array([[1,2],[2,3]])
test2 = np.array([[2,4],[2,5]])

:

pd.DataFrame({'test':[[1,2],[2,3]],
              'test2':[[2,4],[2,5]]})

     test   test2
0  [1, 2]  [2, 4]
1  [2, 3]  [2, 5]
+4
source share
2 answers

Although you can use

In [85]: pd.DataFrame({'test':test.tolist(), 'test2':test2.tolist()})
Out[85]: 
     test   test2
0  [1, 2]  [2, 4]
1  [2, 3]  [2, 5]

computing on NumPy arrays is likely to be much faster than equivalent computing done on a Pandas DataFrame whose columns contain Python lists.

+4
source

If these numpy arrays are the same length, then Panel might be preferable:

In [11]: p = pd.Panel({"test": test, "test2": test2})

In [12]: p
Out[12]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 2 (minor_axis)
Items axis: test to test2
Major_axis axis: 0 to 1
Minor_axis axis: 0 to 1

In [13]: p["test"]  # a DataFrame
Out[13]:
   0  1
0  1  2
1  2  3
0
source

All Articles