我想将一个 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]])
到目前为止,我所做的是将 Pandas 系列转换为一系列数字列表:ds1 = ds.apply(lambda x: [float(number) for number in x.strip('[]').split(' ')])
但我不知道怎么走 ds1
至 arr
.
最佳答案
使用 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 ]])
关于python - 将 Pandas 系列列表转换为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63505439/