I have a dataframe X
. I want to convert it into 1D array with only 5 elements. One way of doing it is converting the inner arrays to lists. How can I do that?
0 1 2 3 4 5 0 1622 95 1717 85.278544 1138.964373 1053.685830 1 62 328 390 75.613900 722.588235 646.974336 2 102 708 810 75.613900 800.916667 725.302767 3 102 862 964 75.613900 725.870370 650.256471 4 129 1380 1509 75.613900 783.711111 708.097211
val = X.values
will give a numpy array. I want to convert the inner elements of the array to list. How can I do that?
I tried this but failed
M = val.values.tolist()
A = np.array(M,dtype=list)
N = np.array(M,dtype=object)
Steps to Convert Pandas DataFrame to a NumPy Array 1 Step 1: Create a DataFrame#N#To start with a simple example, let’s create a DataFrame with 3 columns. The 3 columns will... 2 Step 2: Convert the DataFrame to a NumPy Array More ...
For example, it is possible to create a Pandas dataframe from a dictionary . As Pandas dataframe objects already are 2-dimensional data structures, it is of course quite easy to create a dataframe from a 2-dimensional array. Much like when converting a dictionary, to convert a NumPy array we use the pd.DataFrame () constructor:
If you want to convert an array to a dataframe and create column names you’ll just do as follows: df = pd.DataFrame (numpy_array, columns= [ 'digits', 'words' ]) Code language: JavaScript (javascript) In the image below, you will see the resulting dataframe.
They are the 1d array of the columns you split You can first convert the DataFrame to NumPy format by calling .values, after which the resulting numpy.ndarray has the same dimensions as your original DataFrame. Then, run .flatten () to collapse it into one dimension.
Here's one approach to have each row as one list to give us a 1D
array of lists -
In [231]: df
Out[231]:
0 1 2 3 4 5
0 1622 95 1717 85.278544 1138.964373 1053.685830
1 62 328 390 75.613900 722.588235 646.974336
2 102 708 810 75.613900 800.916667 725.302767
3 102 862 964 75.613900 725.870370 650.256471
4 129 1380 1509 75.613900 783.711111 708.097211
In [232]: out = np.empty(df.shape[0], dtype=object)
In [233]: out[:] = df.values.tolist()
In [234]: out
Out[234]:
array([list([1622.0, 95.0, 1717.0, 85.278544, 1138.964373, 1053.6858300000001]),
list([62.0, 328.0, 390.0, 75.6139, 722.5882349999999, 646.974336]),
list([102.0, 708.0, 810.0, 75.6139, 800.916667, 725.302767]),
list([102.0, 862.0, 964.0, 75.6139, 725.87037, 650.256471]),
list([129.0, 1380.0, 1509.0, 75.6139, 783.7111110000001, 708.097211])], dtype=object)
In [235]: out.shape
Out[235]: (5,)
In [236]: out.ndim
Out[236]: 1
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