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

标签 python-3.x pandas numpy dataframe string-conversion

我很难用 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)然后它失败说它不能将字符串转换为浮点数。
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` 在数据转换尝试之前。

我被卡住了

最佳答案

使用自定义函数转换为 numpy array之后 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)
import re
import ast
import numpy as np

#https://stackoverflow.com/a/44323021
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]]]

关于python-3.x - 使用 Pandas 数据帧时,无法将存储为 excel 中的字符串的矩阵转换为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61906064/

相关文章:

python - 如何将网页中嵌入的视频链接名称与视频名称一起提取

Python:如何删除以某些字符结尾的行?

python - 为什么我的代码无法从 txt 文件中读取 3 位数字?

python - 无法用相应列中最后三行的平均值替换数据帧最后一行中的零,同时保留非零值

Python:如何将数字映射到列中的唯一项目(枚举唯一对象)?

python - 从列中选择的数值数量的平均值

python - 将矩形图像调整为正方形,保持比例并用黑色填充背景

python - NumPy 性能 : uint8 vs. float 和乘法与除法?

windows - 是否有任何指标、已知问题或说明可将大型 pickle 对象保存到 Windows 10 文件系统

python-3.x - 如何使用带有 Pytest 参数化副作用的补丁进行单元测试?