“This is the 10th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

Python Lists are well known for slicing indexes. Numpy arrays are also implemented using Python’s standard X [obj] objects.

In numpy index, we can know that numpy array index can be divided into basic index, advanced index, etc

  • Basic indexes are performed using single-element indexes, and the result is a copy returned
  • Basic slices follow the start:end:step format and the structure returns the view
  • Advanced index is mainly divided into integer array index, Boolean index and fancy index
  • Advanced indexes return a copy

A structured array is made up of a series of fields named itemSize. The data type is itemSize. Each field consists of name, datatype, and offset.

Numpy supports index slicing for normal arrays. Which structured arrays support indexes?

The answer is yes, numpy structured arrays also support index assignment.

Let’s go~~ Let’s go~~

1. Structured array assignment

For Python built-in data types such as list and tuple, we can assign values by indexing subscripts

Similarly, there are three ways to assign values to numpy structured arrays: from tuples, scalars, and from other structured arrays.

2. Assignment from tuples

Numpy is the easiest way to assign data values to structured arrays using the Python tuple method

  • The assigned tuple data value must be the same length as the number of fields in the array

  • During the assignment, numpy’s broadcast rules are triggered

  • The tuple’s data is assigned to the array fields in left-to-right order, and the memory space is contiguous

    >>> stu_type = np.dtype({"name": ("S6".0."nickname"),"age": ("i8".1)})
    >>> stu_list = np.array([("Tom".12), ("Anne".10),stu_type])
    >>> stu_list[0] = ("Tony".15)
    >>> stu_list
    array([('Tony'.15), ('Anne'.10),
           dtype({'names': ['name'.'age'].'formats': ['S6'.'<i8'].'offsets': [0.1].'titles': ['nickname'.None].'itemsize':9})],
          dtype=object) > > >Copy the code

We assign the tuple list (“Tony”,15) to the structured array stu_list[0]. We can see that stu_list[0] is changed from (“Tom”,12) to (“Tony”,15).

3. Scalar assignment

Numpy can use scalar methods to assign values from an array to all fields.

  • If the assigned shape is different from that of the original array, the system will report a Value Error

    >>> stu_list
    array([('Tony'.15), ('Anne'.10),
           dtype({'names': ['name'.'age'].'formats': ['S6'.'<i8'].'offsets': [0.1].'titles': ['nickname'.None].'itemsize':9})],
          dtype=object)
    >>> stu_list[:] = "Juejin"
    >>> stu_list
    array(['Juejin'.'Juejin'.'Juejin'], dtype=object) > > >Copy the code

    Structured arrays can also be assigned to unstructured arrays, requiring the structured array dTYPE to have only one field

    TypeError is reported if multiple dType structured array assignments exist

    >>> y1 = np.zeros(2,dtype=[('A'.'i8')])
    >>> y2 = np.zeros(2,dtype=[('A'."i8"), ("B"."i4")])
    >>> y = np.zeros(2,dtype="i4")
    >>> y[:]=y2
    Traceback (most recent call last):
      File "<stdin>", line 1.in <module>
    TypeError: Cannot cast scalar from dtype([('A'.'<i8'), ('B'.'<i4')]) to dtype('int32') according to the rule 'unsafe'
    >>>
    
    Copy the code

4. Assignment from other structured arrays

Assign two structured arrays with the same number of fields. Numpy internally assigns the value of the first field to the value of the first field in the original array, the value of the second new field to the value of the second field in the original array, and so on, from left to right.

  • The number of structured array fields should be the same
  • The original array bytes that do not contain any fields are not affected
```python
>>> x = np.array([("Thu",3),("Wen",4),("Fri",5)],dtype=[("name","U5"),("num","i8")])
>>> x1 = np.array([("Mon",1),("Sun",7),("Fri",5)],dtype=[("name","U5"),("num","i8")])
>>> x1[:] = x
>>> x1
array([('Thu', 3), ('Wen', 4), ('Fri', 5)],
      dtype=[('name', '<U5'), ('num', '<i8')])
>>>
```
Copy the code

conclusion

This installment, we numpy structured array assignment methods for the basic understanding and learning.

The value assignment uses tuple data, which is the easiest and most convenient way to assign values to structured arrays. The length of the tuple must be the same as the number of fields in the array, and must not be greater than or equal to. Otherwise, ValueError is reported.

That’s the content of this episode. Please give us your thumbs up and comments. See you next time