Konvertieren Sie eine Pandas-Serie von Listen in ein numpy-Array
Ich möchte eine Pandas-Reihe von Zeichenfolgen einer Liste von Zahlen in ein numpy-Array konvertieren. Was ich habe ist so etwas wie:
ds = pd.Series(['[1 -2 0 1.2 4.34]', '[3.3 4 0 -1 9.1]'])
Meine gewünschte Ausgabe:
arr = np.array([[1, -2, 0, 1.2, 4.34], [3.3, 4, 0, -1, 9.1]])
Was ich bisher getan habe, ist, die Pandas-Serie in eine Serie einer Liste von Zahlen umzuwandeln als:
ds1 = ds.apply(lambda x: [float(number) for number in x.strip('[]').split(' ')])
aber ich weiß nicht, wie ich von nach gehen ds1soll arr.
Antworten
Verwenden Sie Series.str.strip+ Series.str.splitund erstellen Sie ein neues np.arraymit dtype=float:
arr = np.array(ds.str.strip('[]').str.split().tolist(), dtype='float')
Ergebnis:
print(arr)
array([[ 1. , -2. , 0. , 1.2 , 4.34],
[ 3.3 , 4. , 0. , -1. , 9.1 ]])
Sie können zuerst versuchen, das "[]" aus dem Series-Objekt zu entfernen, dann wird die Sache einfacher,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)
Dann arrwird das richtige Format sein, das Sie wollen,
array([[ 1. , -2. , 0. , 1.2 , 4.34],
[ 3.3 , 4. , 0. , -1. , 9.1 ]])
Dann habe ich ein wenig Profiling im Vergleich zu Shubhams Colution gemacht.
# 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)
Offensichtlich ist seine Lösung viel schneller! Beifall!