Convert numpy array to dataframe Python
In this post, you will learn how to convert a numpy array to a dataframe in Python programming.
NumPy is the fundamental package for scientific computing with Python. It is a highly optimised library for numerical operations. The support of NumPy makes the task easier. Several libraries, like OpenCV, SciPy, and Matplotlib, when combined with NumPy, increase the number of weapons in your arsenal.
A DataFrame is a tabular-like data structure containing an ordered collection of columns. Each column can be of different data types, like numeric, boolean, strings, etc. It has both a row and a column index. It is basically used for analytical purposes.
We can easily convert a numpy array to a Pandas DataFrame by using the function pandas.DataFrame().
pandas.DataFrame( data, index, columns, dtype, copy)
Here, the data can be ndarray, series, dict, map, lists, constants, and also dataframes. The index is used for the resulting frame, the columns are used for column labels, dtype is the data type of each column, and the copy is used for copying data.
Convert the numpy array to DataFrame
In the given example, first we imported the Pandas and Numpy modules and created a Numpy array. Next, we have created a list of index values and column values for the DataFrame. Then, we used the pd.DataFrame() function to convert the numpy array into a dataframe.
# importing the modules
import pandas as pd
import numpy as np
# Creating the Numpy array
array = np.array([[98, 89, 88], [97, 88, 87], [95, 85, 89],
[93, 80, 85], [92, 79, 80], [91, 75, 81],
[79, 66, 77]])
# Creating a list of index names
index_values = ['First', 'Second', 'Third',
'Fourth', 'Fifth', 'Sixth', 'Seventh']
# Creating a list of column names
column_values = ['Maths', 'Phy', 'Chm']
# Creating the dataframe
df = pd.DataFrame(data = array,
index = index_values,
columns = column_values)
# Displaying the dataframe
print(df)
Output of the above code:
Maths Phy Chm
I 98 89 88
II 97 88 87
III 95 85 89
IV 93 80 85
V 92 79 80
VI 91 75 81
VII 79 66 77
Related Articles
Python convert list to numpy arrayPython Numpy Array Shape
Python NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Trigonometric functions Python Numpy
Python Pandas Dataframe to CSV
Python Pandas DataFrame
Convert list to dictionary Python
Python dict inside list
Convert dictionary to dataframe Python
Python Pandas CSV to Dataframe
Convert List to Dataframe Python
Python add list to list
Difference between tuple and list in Python
Convert Excel to CSV Python Pandas
Alphabetical order Python
Python | Generate QR Code using pyqrcode module