NumPy: Convert Pandas dataframe to Numpy array with headers
NumPy: Array Object Exercise-168 with Solution
Write a NumPy program to convert Pandas dataframe to Numpy array with headers.
Sample Solution:
Python Code:
# Importing necessary libraries
import numpy as np
import pandas as pd
# Generating a 12x3 NumPy array with random values
np_array = np.random.rand(12, 3)
# Printing the original NumPy array and its type
print("Original NumPy array:")
print(np_array)
print("Type: ", type(np_array))
# Creating a Pandas DataFrame from a 12x3 NumPy array with random values and labeled columns A, B, C
df = pd.DataFrame(np.random.rand(12, 3), columns=['A', 'B', 'C'])
# Printing the Pandas DataFrame and its type
print("\nPandas DataFrame:")
print(df)
print("Type: ", type(df))
Sample Output:
Original Numpy array: [[0.18308157 0.32258608 0.39644848] [0.31018507 0.08220454 0.40018982] [0.63639779 0.34908174 0.39878868] [0.74477532 0.4250794 0.12355822] [0.61842804 0.78525555 0.95617131] [0.17971402 0.03450462 0.3756935 ] [0.34533001 0.68281693 0.42670306] [0.90444404 0.96700828 0.87172799] [0.53261873 0.18419712 0.54780473] [0.50476661 0.82657057 0.06935023] [0.02482073 0.02318678 0.36032194] [0.69001834 0.04285817 0.31768865]] Type: <class 'numpy.ndarray'> Panda's DataFrame: A B C 0 0.015583 0.968431 0.943192 1 0.221607 0.704098 0.241200 2 0.466129 0.269226 0.450781 3 0.747222 0.674508 0.686070 4 0.908001 0.399580 0.124778 5 0.540362 0.024179 0.560710 6 0.572349 0.992342 0.347848 7 0.609707 0.786937 0.150088 8 0.162281 0.412158 0.761437 9 0.969180 0.215166 0.769721 10 0.272827 0.817238 0.093650 11 0.196416 0.643602 0.262683 Type: <class 'pandas.core.frame.DataFrame'>
Explanation:
np_array = np.random.rand(12,3): This line generates a 12x3 NumPy array with random values between 0 and 1 from a uniform distribution and stores in the variable np_array.
df = pd.DataFrame(np.random.rand(12,3),columns=['A','B','C']): Creates a new 12x3 pandas DataFrame ‘df’ with random values between 0 and 1 from a uniform distribution. The columns are labeled 'A', 'B', and 'C'.
Pictorial Presentation:
Python-Numpy Code Editor:
Previous: Write a NumPy program to convert a Python dictionary to a Numpy ndarray.
Next: Write a NumPy program to get all 2D diagonals of a 3D numpy array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/python-exercises/numpy/python-numpy-exercise-168.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics