NumPy fromstring()

fromstring() 方法从字符串中的二进制或文本数据创建一维数组。

示例

import numpy as np

# create a string to read from
string1 = '1 2 3'

# create array from string array1 = np.fromstring(string1, sep =' ')
print(array1) # Output: [1. 2. 3.]

注意fromstring() 通常用于数值数据,因此已弃用字节支持。


fromstring() 语法

fromstring() 的语法是

numpy.fromstring(string, dtype=float, count=-1, sep, like=None)

fromstring() 参数

fromstring() 方法接受以下参数

  • string- 要读取的字符串 (str)
  • dtype(可选)- 输出数组的类型(dtype
  • count(可选)- 要读取的项目数 (int)
  • sep- 分隔字符串中元素的子字符串 (str)
  • like(可选)- 用于创建非NumPy数组的参考对象(array_like

注意: count 的默认值是 -1,表示缓冲区中的所有数据。


fromstring() 返回值

fromstring() 方法从字符串返回一个数组。


示例 1:使用 fromstring() 创建数组

import numpy as np

string1 = '12 13 14 15'
string2 = '12, 13, 14, 15'

# load from string with element separated by whitespace array1 = np.fromstring(string1, sep = ' ') # load from string with element separated by commas array2 = np.fromstring(string2, sep = ',')
print(array1) print(array2)

输出

[12. 13. 14. 15.]
[12. 13. 14. 15.]

示例 2:使用 dtype 参数指定数据类型

dtype 参数有助于指定创建的 numpy 数组所需的數據類型。

import numpy as np

string1 = '\x01\x02\x03\x04'

# load from the string as int8 array1 = np.fromstring(string1, dtype = np.uint8)
print(array1)
# load from the buffer as int16 array2 = np.fromstring(string1, dtype = np.uint16)
print(array2)

输出

<string>:7: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
[1 2 3 4]
<string>:11: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
[ 513 1027

注意:如上所述,fromstring() 应仅与数值输入一起使用,而不是字节字符串。

dtype = np.unit8 时,字节字符串中的每个字节都被解释为 **8** 位无符号整数。因此,array1 变为 [1 2 3 4]

dtype = np.unit16 时,字节字符串中的字节对被解释为 **16** 位无符号整数。

因此,array2 有 2 个元素 \x01\x02,即 2 * 256 + 1 = 513,和 \x03\x04,即 4 * 256 + 3 = 1027,并变为 [513 1027]


示例 3:使用 count 参数限制要读取的数据

count 参数有助于指定要从字符串中读取的项目数。

string1 = '1 2 3 4'

import numpy as np

# load the all items from the buffer array1 = np.fromstring(string1, sep = ' ')
print(array1)
# load the first 3 items from the buffer array2 = np.fromstring(string1,sep = ' ', count = 3)
print(array2)
# load the first 2 items from the buffer array3 = np.fromstring(string1,sep = ' ', count = 2)
print(array3)

输出

[1. 2. 3. 4.]
[1. 2. 3.]
[1. 2.]

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战