简体   繁体   中英

how do i convert a numpy array to pandas dataframe

How do i convert a numpy array to a pandas dataframe?

for example:

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

to this:

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

     test   test2
0  [1, 2]  [2, 4]
1  [2, 3]  [2, 5]

Although you could 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]

computation on the NumPy arrays would probably be much faster than an equivalent computation done on a Pandas DataFrame whose columns contain Python lists.

If these numpy arrays have the same length, then Panel may be a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM