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



我想将一个pandas系列的数字列表字符串转换为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(' ')])

但是我不知道如何从ds1arr

使用Series.str.strip+Series.str.split并使用dtype=float:创建新的np.array

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 ]])

您可以尝试删除;[]";首先从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的colution进行比较。

# 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)

显然,他的解决方案要快得多!干杯

最新更新