Converti una serie di liste panda in un array numpy

Aug 20 2020

Voglio convertire una serie di stringhe di elenchi di numeri panda in un array numpy. Quello che ho è qualcosa del tipo:

ds = pd.Series(['[1 -2 0 1.2 4.34]', '[3.3 4 0 -1 9.1]'])

Il mio risultato desiderato:

arr = np.array([[1, -2, 0, 1.2, 4.34], [3.3, 4, 0, -1, 9.1]])

Quello che ho fatto finora è convertire la serie dei panda in una serie di un elenco di numeri come:

ds1 = ds.apply(lambda x: [float(number) for number in x.strip('[]').split(' ')])

ma non so come andare da ds1a arr.

Risposte

5 ShubhamSharma Aug 20 2020 at 19:52

Usa Series.str.strip+ Series.str.splite creane uno nuovo np.arraycon dtype=float:

arr = np.array(ds.str.strip('[]').str.split().tolist(), dtype='float')

Risultato:

print(arr)

array([[ 1.  , -2.  ,  0.  ,  1.2 ,  4.34],
       [ 3.3 ,  4.  ,  0.  , -1.  ,  9.1 ]])
1 Snoopy Aug 20 2020 at 23:48

Puoi provare a rimuovere prima "[]" dall'oggetto Serie, quindi le cose diventeranno più facili,https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html.

ds1 = ds.str.strip("[]")
# split and exapand the data, conver to numpy array
arr = ds1.str.split(" ", expand=True).to_numpy(dtype=float)

Quindi arrsarà il formato giusto che desideri,

array([[ 1.  , -2.  ,  0.  ,  1.2 ,  4.34],
       [ 3.3 ,  4.  ,  0.  , -1.  ,  9.1 ]])

Poi ho fatto un piccolo profilo rispetto alla coluzione di Shubham.

# Shubham's way
%timeit arr = np.array(ds.str.strip('[]').str.split().tolist(), dtype='float')
332 µs ± 5.72 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# my way
%timeit ds.str.strip("[]").str.split(" ", expand=True).to_numpy(dtype=float)
741 µs ± 4.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Ovviamente, la sua soluzione è molto più veloce! Saluti!