How to convert a Pandas DataFrame with mixed data types to a NumPy array?
18. Mixed DataFrame to Array Conversion
Write a NumPy program to convert a Pandas DataFrame with mixed data types (numerics and strings) to a NumPy array.
Sample Solution:
Python Code:
import pandas as pd
import numpy as np
# Create a Pandas DataFrame with mixed data types
data = {
'A': [1, 2, 3, 4],
'B': ['a', 'b', 'c', 'd'],
'C': [5.0, 6.1, 7.2, 8.3]
}
df = pd.DataFrame(data)
print("Original Pandas DataFrame with mixed data types:",df)
print(type(df))
# Convert the DataFrame to a NumPy array
array = df.to_numpy()
print("\nDataFrame to a NumPy array:")
# Print the NumPy array
print(array)
print(type(array))
Output:
Original Pandas DataFrame with mixed data types: A B C 0 1 a 5.0 1 2 b 6.1 2 3 c 7.2 3 4 d 8.3 <class 'pandas.core.frame.DataFrame'> DataFrame to a NumPy array: [[1 'a' 5.0] [2 'b' 6.1] [3 'c' 7.2] [4 'd' 8.3]] <class 'numpy.ndarray'>
Explanation:
- Import Pandas and NumPy Libraries: Import the Pandas and NumPy libraries to handle DataFrames and arrays.
- Create Pandas DataFrame: Define a Pandas DataFrame with columns containing mixed data types (integers, strings, and floats).
- Convert DataFrame to NumPy Array: Use the to_numpy() method of the DataFrame to convert it into a NumPy array.
- Print NumPy Array: Output the resulting NumPy array to verify the conversion.
For more Practice: Solve these Related Problems:
- Write a Numpy program to convert a Pandas DataFrame with mixed numeric and string data to a NumPy array and then separate the columns by type.
- Write a Numpy program to convert a mixed-type DataFrame to a NumPy array and then perform vectorized string operations on the non-numeric columns.
- Write a Numpy program to handle a DataFrame with missing mixed-type data during conversion to a NumPy array using conditional logic.
- Write a Numpy program to convert a DataFrame with mixed data types to an array, enforce a homogeneous dtype, and then revert back while preserving original types.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: How to convert a list of lists of lists to a 3D NumPy array and print it?
Next: How to combine a NumPy array and a Pandas DataFrame into one DataFrame?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.