python - 如何使用 numpy 2d 字典(对象)数组加载 .txt?

标签 python python-3.x numpy

我尝试使用 numpy 加载 .txt 文件 numpy.loadtxt("grid_data.txt", dtype=object)函数,但没有返回预期的结果。 我正在开发一款类似网格的游戏,所以我想保存一些图 block 的数据。我想使用字典而不是列表,以便仅在需要时将数据保存到该图 block ,而不是让其他没有数据的图 block (如草、泥土等)包含不需要的数据。

(我对 Numpy 不太有经验,对于可能出现的错误代码深表歉意)

我有以下内容:

np.loadtxt('grid_data.txt',dtype=object)

使用 grid_data.txt 像这样(但然后是 500x500):

{} {} {}
{} {} {}
{} {} {}

等等

我生成并保存了文件 np.savetxt(f, grid_data, fmt="%s")其中 grid_data 变量是 np.array,其中:(np.array 的宽度和高度为 500) [[{}, {}, {}, ... {}, {}, {}], ... ,[{}, {}, {}, ... {}, {}, {}] ]

我尝试使用 numpy.loadtxt 函数以 dtype 作为对象加载此 .txt 文件,但它返回以下内容(我在 500x500 数组 txt 文件上尝试过):

[['{}' '{}' '{}' ... '{}' '{}' '{}'] ['{}' '{}' '{}' ... '{}' '{}' '{}'] ['{}' '{}' '{}' ... '{}' '{}' '{}']]

如何将数组转换为这种格式? [[{},{},{}...{},{},{}], [{},{},{}...{},{},{}] [{},{},{}...{},{},{}]] 这样我就可以真正“使用”字典而不是“{}”?

对于如何克服这个问题有什么帮助吗?如有任何帮助,我们将不胜感激。

最佳答案

这不是存储所需数据的好格式。如果您能够更改格式,您可以将字典保存为 json 文件,其中包含所有字典的列表以及所需的矩阵形状。例如,如果您的文件如下所示:

{
  "shape": [3, 3],
  "data": [{"foo": 0, "bar": 0},
           {"foo": 10, "bar": 1},
           {"foo": 20, "bar": 2},
           {"foo": 30, "bar": 3},
           {"foo": 40, "bar": 4},
           {"foo": 50, "bar": 5},
           {"foo": 60, "bar": 6},
           {"foo": 70, "bar": 7},
           {"foo": 80, "bar": 8}]
}

您可以使用标准 json 库读取它

file_data = json.load("filename.json")

然后从 file_data["data"] 创建 numpy 数组,并将其 reshape 为 file_data["shape"]:

my_arr = np.array(file_data["data"]).reshape(file_data["shape"])

这给出了所需的数组:

array([[{'foo': 0, 'bar': 0}, {'foo': 10, 'bar': 1},
        {'foo': 20, 'bar': 2}],
       [{'foo': 30, 'bar': 3}, {'foo': 40, 'bar': 4},
        {'foo': 50, 'bar': 5}],
       [{'foo': 60, 'bar': 6}, {'foo': 70, 'bar': 7},
        {'foo': 80, 'bar': 8}]], dtype=object)

要将此数组保存回 json 文件,只需执行相反的操作:

json_obj = {"shape": my_arr.shape, "data": my_arr.flatten().tolist()}

with open("filname.json", "w") as f:
    json.dump(json_obj, f, indent=2)

将其输出到您的文件:

{
  "shape": [
    3,
    3
  ],
  "data": [
    {
      "foo": 0,
      "bar": 0
    },
    {
      "foo": 10,
      "bar": 1
    },
    {
      "foo": 20,
      "bar": 2
    },
    {
      "foo": 30,
      "bar": 3
    },
    {
      "foo": 40,
      "bar": 4
    },
    {
      "foo": 50,
      "bar": 5
    },
    {
      "foo": 60,
      "bar": 6
    },
    {
      "foo": 70,
      "bar": 7
    },
    {
      "foo": 80,
      "bar": 8
    }
  ]
}

关于python - 如何使用 numpy 2d 字典(对象)数组加载 .txt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75567055/

相关文章:

python - 在 Python 3 中使用 urllib 检索文件(资源)的标题

Python 对数函数

python - 二维数组中索引对之间的 Numpy 总和

python - 给定间隔列表,对列表中的元素进行分组

python - 删除 Django admin 中的 "Add"功能

python-3.x - 如何格式化机器人 'send_message' 输出,使其像表格一样对齐?

python-3.x - python给视频opencv添加音频

python - 如何比较 numpy 数组和标量?

python - Python 中的二维数组

python - Django 中每个客户(通过迭代)的订单值(value)计数和总和