使用 Pandas 数据帧时,无法将存储为 excel 中的字符串的矩阵转换为 numpy 数组

Cha*_*own 4 numpy string-conversion dataframe python-3.x pandas

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

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

[[[ 0.        0.        0.107851]
  [ 0.        0.       -0.862809]]]
Run Code Online (Sandbox Code Playgroud)

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

我已经尝试过np.fromstringnp.asarray但无济于事。它会将字符串转换为一个 numpy 数组,但如果括号内仍为字符,这将是一个可怕的混乱。我试过使用 np.squeeze 去掉括号,但它说维度不是 1。

如果我使用np.asarray(item._coord, dtype=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`。

我被卡住了

jez*_*ael 5

使用自定义函数转换为numpy arrayafter read_excel

a= np.array([[[ 0.,        0.,        0.107851],
              [ 0.,        0.,       -0.862809]]])
print (a)
[[[ 0.        0.        0.107851]
  [ 0.        0.       -0.862809]]]

df = pd.DataFrame({'col':[a,a,a]})
print (df)
                                               col
0  [[[0.0, 0.0, 0.107851], [0.0, 0.0, -0.862809]]]
1  [[[0.0, 0.0, 0.107851], [0.0, 0.0, -0.862809]]]
2  [[[0.0, 0.0, 0.107851], [0.0, 0.0, -0.862809]]]

df.to_excel('test.xlsx', index=False)
Run Code Online (Sandbox Code Playgroud)
import re
import ast
import numpy as np

#/sf/answers/3102611501/
def str2array(s):
    # Remove space after [
    s=re.sub('\[ +', '[', s.strip())
    # Replace commas and spaces
    s=re.sub('[,\s]+', ', ', s)
    return np.array(ast.literal_eval(s))

df = pd.read_excel('test.xlsx')

df['col'] = df['col'].apply(str2array)
print (df)
                                               col
0  [[[0.0, 0.0, 0.107851], [0.0, 0.0, -0.862809]]]
1  [[[0.0, 0.0, 0.107851], [0.0, 0.0, -0.862809]]]
2  [[[0.0, 0.0, 0.107851], [0.0, 0.0, -0.862809]]]
Run Code Online (Sandbox Code Playgroud)