w3resource

How to convert a Pandas DataFrame with mixed data types to a NumPy array?


NumPy: Interoperability Exercise-18 with Solution


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.

Python-Numpy Code Editor: