python - C++ Boost Python numpy 数组初始化

标签 python c++ numpy boost

在 Python 中,我可以使用以下命令初始化 x 长度的负 inf numpy 数组

import numpy as np
...
foo = np.array([np.NINF] * x)

哪里x是一个 int 例如42. 我想用 Boost.Python 在 C++ 中做同样的事情。以下显然行不通:

namespace bnp = boost::python::numpy;
...
bnp::ndarray foo = bnp::array({-INFINITY} * x);

有哪些好的方法可以做到这一点?

是的,我知道 Boost.Numpy docs and tutorial -- 他们并不出色。

更一般地说,如何用值 -INFINITY 初始化长度为 x 的 std vector 或数组?

更新:

我正在尝试通过打印到控制台来验证方法(使用评论中建议的初始循环)

for (auto i=0; i<x; ++i) {
    std::cout << foo[i] << '\n';
}

但出现以下错误:error: use of overloaded operator '<<' is ambiguous (with operand types 'ostream' (aka 'basic_ostream<char>') and 'object_item' (aka 'proxy<boost::python::api::item_policies>')) 。为什么这不起作用?尝试按索引访问 boost numpy 数组是否存在问题?

最佳答案

这是一个解决方案(感谢@DanMašek 的最初想法)以及如何通过打印到控制台进行验证:

bpy::list temp_list;
temp_list.append(-INFINITY);
temp_list *= x;
bnp::ndarray foo = bnp::array(temp_list);

其中 x=9。验证w/

std::cout << std::endl << "Python ndarray : " << bpy::extract<char const *>(bpy::str(foo)) << std::endl;

您还可以使用相同的 temp_list 来初始化另一个 Python ndarray:

// after initializing bar the same as foo w/ temp_list
bar[0] = 0;
std::cout << std::endl << "Python ndarray : " << bpy::extract<char const *>(bpy::str(bar)) << std::endl;

打印结果:

Python ndarray : [-inf -inf -inf -inf -inf -inf -inf -inf -inf]

Python ndarray : [  0. -inf -inf -inf -inf -inf -inf -inf -inf]

关于python - C++ Boost Python numpy 数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42616020/

相关文章:

c++ - Qt 的.NET 属性表?有什么建议么?

python - 将数据从 hdf5 数据集传输到 numpy 数组时精度损失

python - 将图像转换为适当的尺寸 PyTorch

python - 从 lxml xpath 查询操作列表

python - PyAudio——如何在单个流中捕获麦克风和系统声音?

Python-gdal 用二进制颜色和 NaN 编写 GeoTiff

c++ - 为什么我的文件会出现损坏的输出?

c++ - 动态内存分配输出

python - 如何折叠/累积一个 numpy 矩阵乘积(点)?

python - 如何在约束规划中限制零的个数