python
Pandas - Get index values of a DataFrame as a List
In this post, we are going to explain to get the index values of a DataFrame. We will get the index values in a List. We will be using DataFrame.index.values to do it.
import pandas as pd
# create a dataframe
df = pd.DataFrame({
"id": [1, 2, 3, 4, 5],
"name": ["Joy", "Rick", "Carol", "Dumpty", "Clark"],
"designation": ["Programmer", "Manager", "Admin", "Accountant", "Designer"]
})
print(df)
# get all the indexes
indexes = df.index.values.tolist()
print("All indexes of DataFrame df are: ", end="")
print(indexes)
Output
╒════╤══════╤════════╤═══════════════╕
│ │ id │ name │ designation │
╞════╪══════╪════════╪═══════════════╡
│ 0 │ 1 │ Joy │ Programmer │
├────┼──────┼────────┼───────────────┤
│ 1 │ 2 │ Rick │ Manager │
├────┼──────┼────────┼───────────────┤
│ 2 │ 3 │ Carol │ Admin │
├────┼──────┼────────┼───────────────┤
│ 3 │ 4 │ Dumpty │ Accountant │
├────┼──────┼────────┼───────────────┤
│ 4 │ 5 │ Clark │ Designer │
╘════╧══════╧════════╧═══════════════╛
All indexes of DataFrame df are: [0, 1, 2, 3, 4]
If you want to get all the index values of a DataFrame, you can use one of the code examples explained below.
# Method 1: Using df.index.values.tolist()
We can get df.index object from the DataFrame and then get the index values from it. In order to do that we can use the below code.
result = df.index.values.tolist()
# Method 2: Using list(df.index.values)
result = list(df.index.values)
Example 2
import pandas as pd
# create a dataframe
df = pd.DataFrame({
"col_a": ["A", "B", "C", "D", "E"],
"col_b": [10, 20, 30, 40, 50]
})
# get all the indexes
indexes = list(df.index.values)
print(indexes)
Output
[0, 1, 2, 3, 4]
Was this helpful?
Similar Posts
- Get column values as list in Pandas DataFrame
- Pandas - Change rows order of a DataFrame using index list
- Pandas - Delete multiple rows from DataFrame using index list
- Get a value from DataFrame row using index and column name in pandas
- Get column names from Pandas DataFrame as a python List
- Get a column rows as a List in Pandas Dataframe
- Pandas - How to check whether a pandas DataFrame is empty