Table of Contents
1. Basic data of numpy Type
Select fields and use ndarray to store data.
Home Backend Development Python Tutorial Introduction to Python data types - numpy

Introduction to Python data types - numpy

Jul 19, 2022 pm 01:55 PM
python

This article brings you relevant knowledge about Python, which mainly organizes issues related to numpy data types, including numpy's basic data types, numpy custom composite data types, usage ndarray saves the date data type and so on. Let’s take a look at it. I hope it will be helpful to everyone.

Introduction to Python data types - numpy

[Related recommendations: Python3 video tutorial ]


1. Basic data of numpy Type

##Character typestr, each character is represented by 32-bit Unicode encoding
import numpy as np

arr = np.array([1, 2, 3])
print(arr, arr.dtype)

arr = arr.astype('int64')
print(arr, arr.dtype)

arr = arr.astype('float32')
print(arr, arr.dtype)

arr = arr.astype('bool')
print(arr, arr.dtype)

arr = arr.astype('str')
print(arr, arr.dtype)
Copy after login
Type name Type indicator
Boolean bool
Signed integer type int8 / int16 / int32 / int64
Unsigned integer type uint8 / uint16 / uint32 / uint64
Float type float16 / float32 / float64
Complex type complex64 / complex128

Introduction to Python data types - numpy

2. numpy custom composite data type

If you want to store object types in ndarray, numpy recommends

Use tuples to store the object's attribute field values, and then add the tuples to ndarray. ndarray provides syntax to facilitate processing of these data.

import numpy as np

data = [
    ('zs', [99, 98, 90], 17),
    ('ls', [95, 95, 92], 16),
    ('ww', [97, 92, 91], 18)
]
# 姓名 2 个字符
# 3 个 int32 类型的成绩
# 1 个 int32 类型的年龄
arr = np.array(data, dtype='2str, 3int32, int32')
print(arr)
print(arr.dtype)
# 可以通过索引访问
print(arr[0], arr[0][2])
Copy after login

Introduction to Python data types - numpy

When the amount of data is large, the above method is not convenient for data access.

ndarray provides data types and column aliases that can be defined in the form of a

dictionary or list . When accessing data, you can access it through subscript indexes or through column names.

import numpy as np

data = [
    ('zs', [99, 98, 90], 17),
    ('ls', [95, 95, 92], 16),
    ('ww', [97, 92, 91], 18)]# 采用字典定义列名和元素的数据类型arr = np.array(data, dtype={
    # 设置每列的别名
    'names': ['name', 'scores', 'age'],
    # 设置每列数据元素的数据类型
    'formats': ['2str', '3int32', 'int32']})print(arr, arr[0]['age'])# 采用列表定义列名和元素的数据类型arr = np.array(data, dtype=[
    # 第一列
    ('name', 'str', 2),
    # 第二列
    ('scores', 'int32', 3),
    # 第三列
    ('age', 'int32', 1)])print(arr, arr[1]['scores'])# 直接访问数组的一列print(arr['scores'])
Copy after login

Introduction to Python data types - numpy

3. Use ndarray to save date data type

import numpy as np

dates = [
    '2011',
    '2011-02',
    '2011-02-03',
    '2011-04-01 10:10:10'
]

ndates = np.array(dates)
print(ndates, ndates.dtype)

# 数据类型为日期类型,采用 64 位二进制进行存储,D 表示日期精确到天
ndates = ndates.astype('datetime64[D]')
print(ndates, ndates.dtype)

# 日期运算
print(ndates[-1] - ndates[0])
Copy after login

Introduction to Python data types - numpy

1. The date string does not support

2011/11/11, and the use of spaces to separate dates does not support 2011 11 11, but 2011-11 is supported. -11 2. There needs to be a space to separate the date and time.
2011-04-01 10:10:10 3. The writing format of time
10: 10:10

4. Type character code (abbreviation of data type)

numpy provides type character code to process data types more conveniently.

TypeType indicatorCharacter codeBoolean typebool?Signed integer typeint8 / int16 / int32 / int64i1 / i2 / i4 / i8Unsigned integer typeuint8 / uint16 / uint32 / uint64u1 / u2 / u4 / u8##Floating point type Complex type Character typeDate
import numpy as np

data = [
    ('zs', [99, 98, 90], 17),
    ('ls', [95, 95, 92], 16),
    ('ww', [97, 92, 91], 18)
]
# 采用字典定义列名和元素的数据类型
arr = np.array(data, dtype={
    # 设置每列的别名
    'names': ['name', 'scores', 'age'],
    # 设置每列数据元素的数据类型
    'formats': ['2U', '3i4', 'i4']
})

print(arr)
print(arr[1]['scores'])
print(arr['scores'])
print(arr.dtype)
Copy after login
float16 / float32 / float64 f2 / f4 / f8
complex64 / complex128 c8 / c16
str, each character is encoded with 32-bit Unicode Represents U
datatime64 M8[Y] / M8[M] / M8[D] / M8 [h] / M8[m] / M8[s]

Introduction to Python data types - numpy

5. Case

Select fields and use ndarray to store data.


import numpy as np

datas = [
    (0, '4室1厅', 298.79, 2598, 86951),
    (1, '3室2厅', 154.62, 1000, 64675),
    (2, '3室2厅', 177.36, 1200, 67659),]arr = np.array(datas, dtype={
    'names': ['index', 'housetype', 'square', 'totalPrice', 'unitPrice'],
    'formats': ['u1', '4U', 'f4', 'i4', 'i4']})print(arr)print(arr.dtype)# 计算 totalPrice 的均值sum_totalPrice = sum(arr['totalPrice'])print(sum_totalPrice/3)
Copy after login
Introduction to Python data types - numpy

Introduction to Python data types - numpy[Related recommendations:

Python3 video tutorial

]

The above is the detailed content of Introduction to Python data types - numpy. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles