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

标签 python 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]])
到目前为止,我所做的是将 Pandas 系列转换为一系列数字列表:
ds1 = ds.apply(lambda x: [float(number) for number in x.strip('[]').split(' ')])
但我不知道怎么走 ds1arr .

最佳答案

使用 Series.str.strip + Series.str.split 并创建一个新的 np.arraydtype=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/

相关文章:

python - 数字是 float64 吗?

python - 将每行的第一个单词分配给字典中的关键字

python - 监控 ZIP 文件提取 Python

python - 如何使用 pycurl 很好地处理 KeyboardInterrupt (Ctrl-c)?

python - 将行追加到现有的 pandas 数据框

python - 当每列都是数组时如何应用数据框

python - 用零替换python数组中的Nones

python - 如何从外部 python 脚本调用 django View 函数

python - 如何从命令行运行python函数

python - 将 PyArrow Parquet 加速到 Pandas 以获取具有大量字符串的数据帧