Extract pandas DataFrame Index as NumPy Array or List in Python (2 Examples)

In this Python programming tutorial you’ll learn how to get the indices of a pandas DataFrame as a list or a NumPy array.

Creation of Example Data

import pandas as pd                         # Load pandas
my_df = pd.DataFrame({"A":range(10, 15),    # Constructing a pandas DataFrame
                      "B":range(20, 25)})
print(my_df)                                # Display pandas DataFrame
#     A   B
# 0  10  20
# 1  11  21
# 2  12  22
# 3  13  23
# 4  14  24

Example 1: Get pandas DataFrame Index as NumPy Array

df_ind_array = my_df.index.values           # Convert to NumPy array
print(df_ind_array)                         # Print index as NumPy array
# [0 1 2 3 4]

Example 2: Get pandas DataFrame Index as List Object

df_ind_list = my_df.index.tolist()          # Convert to list
print(df_ind_list)                          # Print index as list
# [0, 1, 2, 3, 4]

Further Resources

Please find some related Python programming tutorials on topics such as naming data, data inspection, and lists in the following list.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top