]> git.proxmox.com Git - ceph.git/blame - ceph/src/boost/libs/python/doc/numpy/tutorial/dtype.rst
bump version to 12.2.2-pve1
[ceph.git] / ceph / src / boost / libs / python / doc / numpy / tutorial / dtype.rst
CommitLineData
7c673cae
FG
1How to use dtypes
2=================
3
4Here is a brief tutorial to show how to create ndarrays with built-in python data types, and extract the types and values of member variables
5
6Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::
7
8 #include <boost/python/numpy.hpp>
9 #include <iostream>
10
11 namespace p = boost::python;
12 namespace np = boost::python::numpy;
13
14 int main(int argc, char **argv)
15 {
16 Py_Initialize();
17 np::initialize();
18
19Next, we create the shape and dtype. We use the get_builtin method to get the numpy dtype corresponding to the builtin C++ dtype
20Here, we will create a 3x3 array passing a tuple with (3,3) for the size, and double as the data type ::
21
22 p::tuple shape = p::make_tuple(3, 3);
23 np::dtype dtype = np::dtype::get_builtin<double>();
24 np::ndarray a = np::zeros(shape, dtype);
25
26Finally, we can print the array using the extract method in the python namespace.
27Here, we first convert the variable into a string, and then extract it as a C++ character array from the python string using the <char const \* > template ::
28
29 std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
30
31We can also print the dtypes of the data members of the ndarray by using the get_dtype method for the ndarray ::
32
33 std::cout << "Datatype is:\n" << p::extract<char const *>(p::str(a.get_dtype())) << std::endl ;
34
35We can also create custom dtypes and build ndarrays with the custom dtypes
36
37We use the dtype constructor to create a custom dtype. This constructor takes a list as an argument.
38
39The list should contain one or more tuples of the format (variable name, variable type)
40
41So first create a tuple with a variable name and its dtype, double, to create a custom dtype ::
42
43 p::tuple for_custom_dtype = p::make_tuple("ha",dtype) ;
44
45Next, create a list, and add this tuple to the list. Then use the list to create the custom dtype ::
46
47 p::list list_for_dtype ;
48 list_for_dtype.append(for_custom_dtype) ;
49 np::dtype custom_dtype = np::dtype(list_for_dtype) ;
50
51We are now ready to create an ndarray with dimensions specified by \*shape\* and of custom dtpye ::
52
53 np::ndarray new_array = np::zeros(shape,custom_dtype);
54 }