[Python] NumPy Array (ndarray) Basic Operations: Creation, Access, and Type Specification

The core data structure of NumPy, ndarray (N-dimensional array), is faster and more memory-efficient than standard Python lists, and it comes equipped with abundant mathematical functions.

The code you provided contains important elements such as arange (sequential number generation), linspace (equal division), slicing, and type specification. Below, I have organized these points and provided executable code with corrections for typos (such as aragenarange, prntprint), along with an explanation.

目次

Executable Sample Code

import numpy as np

def ndarray_operations():
    print("=== 1. Creating ndarray ===")
    
    # Create from list
    x = np.array([1, 0, 1])
    print(f"From List: {x}")

    # Create by specifying a range (arange)
    # np.arange(start, stop, step) -> Stop value is NOT included
    x1 = np.arange(1, 10)
    print(f"arange(1, 10):    {x1}")
    
    x2 = np.arange(1, 10, 2)
    print(f"arange(step 2):   {x2}")

    # Create by specifying the number of elements (linspace)
    # np.linspace(start, stop, num) -> Stop value IS included (default)
    x_lin = np.linspace(1, 2, 5)
    print(f"linspace(1, 2, 5): {x_lin}")

    print("\n=== 2. Data Access and Modification ===")
    
    x_acc = np.array([1, 2, 3, 4, 5])

    # Indexing
    print(f"Index 0:   {x_acc[0]}")
    
    # Slicing [start:stop] -> Stop index is NOT included
    print(f"Slice 0:2: {x_acc[0:2]}")
    
    # Access from the end
    print(f"Index -1:  {x_acc[-1]}")

    # Modifying data
    x_mod = np.array([1, 2, 3])
    print(f"Before: {x_mod}")
    x_mod[0] = 100
    print(f"After:  {x_mod}")

    print("\n=== 3. Data Types (dtype) ===")
    
    # Automatic type inference
    # If integers only, it becomes int32 or int64
    x_int = np.array([1, 2, 3])
    print(f"Default: {x_int.dtype}")

    # Explicit type specification
    # Create as floating-point numbers with dtype=np.float64
    x_float = np.array([1, 2, 3], dtype=np.float64)
    print(f"Explicit: {x_float.dtype}")
    print(f"Values:   {x_float}") # Displayed as 1. 2. 3.

if __name__ == "__main__":
    ndarray_operations()

Explanation: Distinction Between Creation Functions

1. np.arange(start, stop, step)

This is the NumPy version of Python’s standard range() function.

  • Feature: You specify the “interval (step)” of the data.
  • Note: The stop value is not included.
  • Usage: When you want to retrieve data “skipping every other one” or “in increments of 0.1”.

2. np.linspace(start, stop, num)

Abbreviation for Linear Space.

  • Feature: You specify the “number of data points”. It divides the specified interval into equal parts.
  • Note: By default, the stop value is included.
  • Usage: When creating x-axis data for graphing, such as “wanting to divide this range smoothly into 50 parts”.

Explanation: Data Types (dtype)

Unlike Python lists, NumPy arrays require that “all elements have the same data type”.

  • int64 / int32: Integers.
  • float64 / float32: Floating-point numbers (decimals). float64 (double precision) is standard.
  • How to Specify: Use the dtype argument. Sometimes float32 or int8 is specified intentionally to save memory.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次