Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a numpy matrix to a pandas series?

I have the following numpy matrix:

array([[64, 22,],
   [58, 64],
   [42, 31])

And i want to get the following:

pd.DataFrame({'one':"64 22", 'two':"42 31"})

My purpose is to convert each row in the numpy.array to a string that will be used for a pandas dataframe. Is there some built in pandas function to the rescue?

like image 376
avicohen Avatar asked May 01 '16 16:05

avicohen


People also ask

Can you create a pandas series from NumPy array?

A pandas Series is very similar to a 1-dimensional NumPy array, and we can create a pandas Series by using a NumPy array.

Is pandas series same as NumPy array?

The essential difference is the presence of the index: while the Numpy Array has an implicitly defined integer index used to access the values, the Pandas Series has an explicitly defined index associated with the values.

How we can convert NumPy array into list in pandas?

With NumPy, [ np. array ] objects can be converted to a list with the tolist() function. The tolist() function doesn't accept any arguments. If the array is one-dimensional, a list with the array elements is returned.

Can you convert NumPy array to DataFrame?

To convert an array to a dataframe with Python you need to 1) have your NumPy array (e.g., np_array), and 2) use the pd. DataFrame() constructor like this: df = pd. DataFrame(np_array, columns=['Column1', 'Column2']) . Remember, that each column in your NumPy array needs to be named with columns.


1 Answers

IIUC you can use DataFrame constructor and apply join:

import pandas as pd
import numpy as np

arr = np.array([[64, 22,],   [58, 64],   [42, 31]])
print arr
[[64 22]
 [58 64]
 [42 31]]

li = ['one','two','three']
df = pd.DataFrame(arr, dtype='str', index=li)
print df
        0   1
one    64  22
two    58  64
three  42  31

print df.apply(lambda x: ' '.join(x), axis=1)
one      64 22
two      58 64
three    42 31
dtype: object
like image 198
jezrael Avatar answered Oct 23 '22 11:10

jezrael