Pandas2.2 Series
Conversion
method | describe |
---|---|
Method for converting the data type of a Series object to a specified type | |
Series.convert_dtypes | Methods for intelligently converting the data type of a Series object to the best possible data type |
Series.infer_objects | The best data type used to try to infer the object data type column in Series |
Used to create an index and copy of the data of the object | |
Method for converting a Boolean-type Pandas Series object to a single Boolean value | |
Series.to_numpy | Used to convert Pandas' Series objects to NumPy arrays |
.to_numpy
.to_numpy
Method is used to convert Pandas' Series objects into NumPy arrays. This is very useful in data science, machine learning, and numerical calculations, because NumPy provides efficient multidimensional array objects and related operations.
grammar
Series.to_numpy(dtype=None, copy=False, na_value=None)
parameter
-
dtype
(Optional): The data type to be converted to. IfNone
, then the data type is inferred. -
copy
(Optional): Whether to return a copy of the data. IfFalse
And without converting the data type, it is possible to return a view of the original data to save memory. -
na_value
(Optional): Values used to replace missing values such as NaN/None/NaT. IfNone
, the missing value is retained.
Return value
- Returns a NumPy array.
Examples and results
Example 1: Basic usage
import pandas as pd import numpy as np # Create a Pandas Seriess = ([1, 2, 3, 4, 5]) # Convert Series to NumPy arrayarray = s.to_numpy() print(array)
result
[1 2 3 4 5]
Example 2: Specify the data type
# Create a Pandas Series containing floating point numberss = ([1.1, 2.2, 3.3, 4.4, 5.5]) # Convert Series to NumPy array and specify the data type as an integerarray = s.to_numpy(dtype=int) print(array)
result
[1 2 3 4 5]
Example 3: Copying data
# Create a Pandas Seriess = ([1, 2, 3, 4, 5]) # Convert Series to NumPy array and copy dataarray = s.to_numpy(copy=True) # Modify the original Seriess[0] = 10 # Print NumPy array and modified Seriesprint("NumPy Array:", array) print("Modified Series:", s)
result
NumPy Array: [1 2 3 4 5]
Modified Series: 0 10
1 2
2 3
3 4
4 5
dtype: int64
Example 4: Replace missing values
# Create a Pandas Series with missing valuess = ([1, 2, None, 4, 5]) # Convert Series to NumPy array and replace missing values with specific valuesarray = s.to_numpy(na_value=-1) print(array)
result
[ 1. 2. -1. 4. 5.]
Summarize
.to_numpy
Methods provide an easy way to convert Pandas Series to NumPy arrays, which is very useful in data processing and analysis. By specifying the data type, copying data and missing value replacement options, you can flexibly control the conversion process.
This is the end of this article about the summary of the use of the pandas Series to_numpy method. For more related pandas Series to_numpy content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!