Skip to main content

Python Pandas Get Index List Of Dataframe (Example)

Generating index list from a dataframe.

Dataframe object has "index" method which returns the required data object. This can be converted into list.
Index list can be used for counting of current number of rows , for using ".iloc" , shuffling etc.

Creating a new dataframe with data

# importing pandas
import pandas as pd


# animal_data dictionary
animal_data = {
    "Name": ["Cat", "Dog", "Cow"],
    "Speed": [15, 12, 10],
    "Sound": ["Meow", "Woof", "Mooo"],
}

#creating a dataframe using the animal_data dictionary
animal_df = pd.DataFrame(animal_data)

#printing animal_df
print("animal_df \n", animal_df)
animal_df Name Speed Sound 0 Cat 15 Meow 1 Dog 12 Woof 2 Cow 10 Mooo

# create a list containing values
indices_as_list = list(animal_df.index)


print("indices_as_list \n", indices_as_list)

print("\n length of indices_as_list \n", len(indices_as_list))




# or directly use the object
indices = animal_df.index


print("\n indices \n", indices)

print("\n length of indices \n", len(indices))

indices_as_list [0, 1, 2] length of indices_as_list 3 indices RangeIndex(start=0, stop=3, step=1) length of indices 3

Comments

Topics

Show more