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?
A pandas Series is very similar to a 1-dimensional NumPy array, and we can create a pandas Series by using a 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.
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.
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.
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
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