保存int16时Python numpy-tofile和fromfile的行为



在将数据附加到一个空数组并验证其形状后,我使用tofile来保存它。当我用fromfile读回它时,形状要大得多(4x(。

# Create empty array
rx_data = np.empty((0), dtype='int16')
# File name to write data
file_name = "Test_file.bin"
# Generate two sinewaves and add to rx_data array in interleaved fashion
for i in range(100):
I = np.sin(2*3.14*(i/100))
rx_data = np.append(rx_data, I)
Q = np.cos(2*3.14*(i/100))
rx_data = np.append(rx_data, Q)
print(rx_data.shape)
# Write array to .bin file
rx_data.tofile(file_name)

# Read back data from the .file
s_interleaved = np.fromfile(file_name, dtype=np.int16)
print(s_interleaved.shape)

上面的代码在保存数组之前返回(200(,但在读取回数组时返回800。为什么会发生这种情况?

问题是rx_data在保存之前有一个float64数据类型。这是因为IQ是float64数组,所以当您使用np.append时,该类型将被提升为与float64值兼容。

此外,使用np.append填充数组是numpy中的反模式。在标准python中这样做很常见,但使用numpy,通常最好创建一个所需形状和数据类型的数组,然后在for循环中填充值。这更好,因为您只需要创建一次数组。使用np.append,每次调用它时都会创建一个新副本。

rx_data = np.empty(200, dtype="float64")
for i in range(200):
rx_data[i] = np.sin(...)

以下是有效的代码,因为它使用float64。但这种模式一般应该避免。首选预分配数组并替换for循环中的值。

# Create empty array
rx_data = np.empty((0), dtype='int16')
# File name to write data
file_name = "Test_file.bin"
# Generate two sinewaves and add to rx_data array in interleaved fashion
for i in range(100):
I = np.sin(2*3.14*(i/100))
rx_data = np.append(rx_data, I)
Q = np.cos(2*3.14*(i/100))
rx_data = np.append(rx_data, Q)
print(rx_data.shape)
# Write array to .bin file
print("rx_data data type:", rx_data.dtype)
rx_data.tofile(file_name)

# Read back data from the .file
s_interleaved = np.fromfile(file_name, dtype=np.float64)
print(s_interleaved.shape)
# Test that the arrays are equal.
np.allclose(rx_data, s_interleaved)  # True

最新更新