Add Rows and Columns Headers in NumPy Array

In this tutorial, we will learn how to add rows and columns headers in NumPy array? By Pranit Sharma Last updated : April 19, 2023

Overview

Suppose that we are given a numpy ndarray and we need to add row and column headers i.e., we need to add some name to each column and each row of this ndarray.

For example, if we are given as

[ 1, 2
  3, 4 ]

And, we have to add the column's name as "A", "B" and the row's name as "A", "B". The result would be,

    A   B
A   1   2
B   3   4

How to Add Rows and Columns Headers in NumPy Array?

To add rows/columns headers in the NumPy array, you need to convert this array into a DataFrame where you can assign index and column names during DataFrame creation by using the pd.DataFrame(arr, index = "rows", columns = "cols"). Pass a list of row indexes to the index parameter and a list of column names to the columns parameter.

Syntax

result = pd.DataFrame(arr, index=name,columns=name)

Python Program to Add Rows and Columns Headers in NumPy Array

# Import numpy
import numpy as np

# Import pandas
import pandas as pd

# Creating an array
arr = np.random.randint(0, 10, size=36).reshape(6, 6)

# Display original array
print("Original array:\n", arr, "\n")

# index and column names
row_names = ["Row_1", "Row_2", "Row_3", "Row_4", "Row_5", "Row_6"]
column_names = ["A", "B", "C", "D", "E", "F"]

# Giving names to rows and columns
res = pd.DataFrame(arr, index=row_names, columns=column_names)

# Display result
pd.set_option("max_columns", 6)
print("Result:\n", res)

Output

Original array:
 [[8 1 4 8 5 1]
 [6 8 8 4 3 6]
 [5 1 8 3 5 9]
 [2 3 3 8 7 4]
 [6 7 0 3 2 1]
 [4 7 4 7 3 4]] 

Result:
        A  B  C  D  E  F
Row_1  8  1  4  8  5  1
Row_2  6  8  8  4  3  6
Row_3  5  1  8  3  5  9
Row_4  2  3  3  8  7  4
Row_5  6  7  0  3  2  1
Row_6  4  7  4  7  3  4

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.