【发布时间】:2018-11-30 11:17:52
【问题描述】:
我很难用 numpy 学习 Python 数组处理。
我有一个 .csv 文件,其中包含一列无符号整数数据,表示来自模拟数字转换器的二进制值。 我想在 jupyter notebook 中使用 Python 将这个无符号整数值转换为 12 位二进制表示。
我尝试了几种实现它的方法,但我仍然失败......
这是我的代码:
import pandas as pd
df = pd.read_csv('my_adc_values.csv', delimiter ='\s+', header=None, usecols=[19])
decimalValues = df.values
print(decimalValues.shape)
到目前为止一切顺利...我的所有 adc 数据列值都在 decimalValues numpy 数组中。
现在,我想遍历数组并将数组中的整数转换为二进制表示:
import numpy as np
# destination array of shape of source array
binaryValues = np.zeros(decimalValues.shape)
for i in range(len(decimalValues)):
print(decimalValues[i])
binaryValues[i]=(bin(decimalValues[i]))
print(binaryValues)
使用此代码我收到错误消息
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-890444040b2e> in <module>()
6 for i in range(len(decimalValues)):
7 print(decimalValues[i])
----> 8 binaryValues[i]=(bin(decimalValues[i]))
9
10 print(binaryValues)
TypeError: only integer scalar arrays can be converted to a scalar index
我尝试了几种不同的解决方案,但都没有奏效。好像我对 numpy 数组有很大的误解。
我正在寻找有关如何解决我所描述的问题的提示。我找到了一些线程,描述了提到的错误消息。我怀疑,它与源/目标数组的形状有关。因此,我用与源相同的形状初始化了目标数组。它没有帮助......
谢谢你, 麦克
【问题讨论】:
-
“12 位二进制表示”究竟是什么意思?您是否希望输出为字符串,例如 23 ->
'000000010111'?或者你想要一个像b'\x00\x17'这样的bytes字符串,在Big Endian 中是23。 -
我需要一个字符串表示。我想, bin() 函数可能是我需要的工具。不幸的是,到目前为止,我的代码还没有做到这一点。当最初的问题解决后,也许会出现另一个问题。