Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame.
Approach :
- Import the
PandasandNumpymodules. - Create a
Numpyarray. - Create list of index values and column values for the DataFrame.
- Create the DataFrame.
- Display the DataFrame.
Example 1 :
# importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([[1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125], [6, 36, 216], [7, 49, 343]]) # creating a list of index namesindex_values = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh'] # creating a list of column namescolumn_values = ['number', 'squares', 'cubes'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df) |
Output :
Example 2 :
# importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([['Aditya', 20], ['Samruddhi', 15], ['Rohan', 21], ['Anantha', 20], ['Abhinandan', 21]]) # creating a list of index namesindex_values = ['A', 'B', 'C', 'D', 'E'] # creating a list of column namescolumn_values = ['Names', 'Age'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df) |
Output :
Example 3 :
# importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([['CEO', 20, 5], ['CTO', 22, 4.5], ['CFO', 21, 3], ['CMO', 24, 2]]) # creating a list of index namesindex_values = [1, 2, 3, 4] # creating a list of column namescolumn_values = ['Names', 'Age', 'Net worth in Millions'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df) |
Output :


