使用pandas数据框时,将在Excel中作为字符串存储的矩阵转换为numpy数组的麻烦

问题描述 投票:1回答:1

我很难用pandas DataFrame读取excel文件并将存储的矩阵转换为numpy array。我认为部分问题是矩阵存储不正确。我无法控制电子表格,但这是发送给我的方式。

例如,这是存储在单元格中的字符串

[[[ 0.        0.        0.107851]
  [ 0.        0.       -0.862809]]]

我用DataFrame读入行,并将每个单元格保存到一个变量。然后,我尝试将该特定变量转换为np.array,因为这些数字代表两组x,y,z坐标。

我尝试了np.fromstringnp.asarray无济于事。它将把字符串转换成一个numpy数组,但是里面的括号仍然是字符,这将是一团糟。我尝试使用np.squeeze摆脱括号,但它表示尺寸不是1。

如果我使用np.asarray(item._coord, dtype=float),则无法说明无法将字符串转换为float。

ValueError: could not convert string to float: '[[[ 0. 0. 0.107851] [ 0. 0. -0.862809]]]'

在两个列表之间的中间显示一个'\ n'。在进行数据转换之前,我使用df = df.replace(r'\n', ' ',regex=True)' to clean out the \ n`。

我被卡住了

python-3.x pandas numpy dataframe string-conversion
1个回答
1
投票

使用自定义功能在numpy array之后转换为read_excel

read_excel
© www.soinside.com 2019 - 2024. All rights reserved.