To get the index of a pandas DataFrame and create a list in Python, the easiest way by using index.to_list() on a DataFrame.
import pandas as pd
df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"],
"gender":["F","F","F","F","M","M","M","F","M"],
"age":[1,2,3,4,5,6,7,8,9],
"weight":[10,20,15,20,25,10,15,30,40]})
index_list = df.index.to_list()
print(index_list)
#Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
You can also use index.values.tolist() function to convert a pandas Index to a list.
import pandas as pd
df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"],
"gender":["F","F","F","F","M","M","M","F","M"],
"age":[1,2,3,4,5,6,7,8,9],
"weight":[10,20,15,20,25,10,15,30,40]})
index_list = df.index.values.tolist()
print(index_list)
#Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
When working with collections of data, the ability to be able to easily access certain pieces of information is valuable.
One such situation is if you want to get the index values of a pandas DataFrame in Python.
There are a few ways you can convert the index of a pandas DataFrame to a list.
Having the index values in a list can be useful if you want to loop over the index values and perform an action.
The easiest way is to access the index with the pandas DataFrame index attribute and then use the to_list() function.
Below shows a simple example of how you can convert a DataFrame index to list in Python.
import pandas as pd
df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"],
"gender":["F","F","F","F","M","M","M","F","M"],
"age":[1,2,3,4,5,6,7,8,9],
"weight":[10,20,15,20,25,10,15,30,40]})
index_list = df.index.to_list()
print(index_list)
#Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Using index.values.tolist() to Convert pandas Index to List in Python
Another way you can convert index values to a list is with the index.values.tolist() function.
Below shows another example of how you can get the index of a DataFrame as a list in Python.
import pandas as pd
df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"],
"gender":["F","F","F","F","M","M","M","F","M"],
"age":[1,2,3,4,5,6,7,8,9],
"weight":[10,20,15,20,25,10,15,30,40]})
index_list = df.index.values.tolist()
print(index_list)
#Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Hopefully this article has been useful for you to be able to learn how to convert pandas Index to a list in Python.