将 Pandas 系列列表转换为 numpy 数组

New*_*eAF 5 python numpy pandas

我想将一个熊猫系列的数字列表字符串转换为一个 numpy 数组。我所拥有的是这样的:

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

我想要的输出:

arr = np.array([[1, -2, 0, 1.2, 4.34], [3.3, 4, 0, -1, 9.1]])
Run Code Online (Sandbox Code Playgroud)

到目前为止,我所做的是将熊猫系列转换为一系列数字列表:

ds1 = ds.apply(lambda x: [float(number) for number in x.strip('[]').split(' ')])
Run Code Online (Sandbox Code Playgroud)

但我不知道如何从ds1arr

Shu*_*rma 5

使用Series.str.strip+Series.str.split并创建一个新np.arraydtype=float

arr = np.array(ds.str.strip('[]').str.split().tolist(), dtype='float')
Run Code Online (Sandbox Code Playgroud)

结果:

print(arr)

array([[ 1.  , -2.  ,  0.  ,  1.2 ,  4.34],
       [ 3.3 ,  4.  ,  0.  , -1.  ,  9.1 ]])
Run Code Online (Sandbox Code Playgroud)