pandasシリーズのリストをnumpy配列に変換します

Aug 20 2020

数字のリストのパンダシリーズの文字列をnumpy配列に変換したいと思います。私が持っているものは次のようなものです:

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

私の希望する出力:

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

私がこれまでに行ったことは、パンダシリーズを次のように数字のリストのシリーズに変換することです。

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

からds1への行き方がわかりませんarr

回答

5 ShubhamSharma Aug 20 2020 at 19:52

Series.str.strip+Series.str.splitを使用して、次のコマンドで新しいものnp.arrayを作成しますdtype=float

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

結果:

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

最初にSeriesオブジェクトから「[]」を削除してみると、作業が簡単になります。 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)

その後arr、あなたが望む正しいフォーマットになります、

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

それから私は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)

明らかに、彼の解決策ははるかに高速です!乾杯!