Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reshape pandas columns into numpy arrays

I have a very long dataframe with many columns of the form k1, p1, k2, p2,...,kn, pn such as

       k1         p1           k2             p2           k3         p3 ...    
-0.001870   0.000659    -0.005000       0.000795    -0.003889   0.000795 ...
-0.002778   0.000556     0.000795       0.001667     0.000795   0.002778 ...

How could I build, in the most pythonic way, a numpy array with the k’s and p’s separated into arrays, like [[[-0.001870,-0.005000,-0.003889,...],[0.000659,0.000795,0.000795...]],[[-0.002778, 0.000795, 0.000795...],[0.000556, 0.001667, 0.002778...]], ...[[...],[...]]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Convert to_numpy and reshape:

out = df.to_numpy().reshape((len(df), 2, -1), order='F')

Output:

array([[[-0.00187 , -0.005   , -0.003889],
        [ 0.000659,  0.000795,  0.000795]],

       [[-0.002778,  0.000795,  0.000795],
        [ 0.000556,  0.001667,  0.002778]]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading