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

How do you mix 1d and 2d variables in a pandas dataframe?

I am working with a bucketload of data that has the form:

import pandas as pd
import numpy as np

lat = np.array([80.589, 80.592, 80.595])
lon = np.array([50.268, 50.264, 50.260])
wav = np.array([[486, 605, 666, 821, 777,  719],
                [ 65,  60,  68,  67,  72,   64],
                [866, 946, 882, 855, 999, 1195]])
print("lat shape:",lat.shape)
print("lon shape:",lon.shape)
print("wav shape:",wav.shape)

# lat shape: (3,)
# lon shape: (3,)
# wav shape: (3, 6)

df = pd.DataFrame({
    'Lon': lon,
    'Lat': lat,
    'Wav': wav})

which gives the error "ValueError: Per-column arrays must each be 1-dimensional"

I can work around this by converting the guts of wav to a string and back again when I need it, but that is Ugly Gross, and I would like to find the proper way to handle mix dimension arrays in a pandas dataframe.

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

Desired result:

print(df.head(1))

      Lon     Lat    Wav
0  50.268  80.589    [486, 605, 666, 821, 777,  719]

>Solution :

How about using a list of lists ?

df = pd.DataFrame({
    'Lon': lon,
    'Lat': lat,
    'Wav': [list(wav_row) for wav_row in wav]
})

enter image description here

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