![]() |
NumPy and Pandas are two powerful libraries in the Python ecosystem for data manipulation and analysis. Converting a DataFrame column to a NumPy array is a common operation when you need to perform array-based operations on the data. In this section, we will explore various methods to achieve this task. Prerequisites
Step 1: Creating a sample dataset for demonstration:Python
Output: Original DataFrame: Step 2: Using methods and examplesa. Using the values Attribute:The values attribute in Pandas returns the underlying data as a NumPy array. This is a simple and direct way to convert a DataFrame column to a NumPy array. Python
Output: The output [51 92 14 71 60] b. to_numpy() method:The to_numpy() method in Pandas converts the DataFrame or Series to a NumPy array. It provides flexibility and options for handling different data types. Python
Output: The output shows numpy_array_to_numpy now holds the NumPy array representation of the ‘Numeric_Column’. [51 92 14 71 60] c. asarray() method:The asarray() function in NumPy converts the input to an array. It can be applied to a Pandas Series to convert it into a NumPy array. Python
Output: numpy_array_asarray shows the NumPy array representation of the ‘Numeric_Column’ obtained through the NumPy Array using asarray() function: |
Reffered: https://www.geeksforgeeks.org
AI ML DS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |