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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/convert-a-pandas-dataFrame-with-mixed-data-types-to-a-numpy-array.php