To convert a Pandas Index to a List, you can use the tolist
method.
This method is applied to a Index
object and returns a new list containing the values in the Index
.
For example, consider the following DataFrame
:
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50],
'C': [100, 200, 300, 400, 500]
})
This DataFrame
has three columns A
, B
, and C
, with five rows of data. The DataFrame
also has an Index
object containing the row labels for the data.
To convert the Index
to a list, you could do the following:
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50],
'C': [100, 200, 300, 400, 500]
})
# Convert the Index to a list
idx_list = df.index.tolist()
# Print the resulting list
print(idx_list)
[0, 1, 2, 3, 4]
In the code above, the tolist
method is applied to the Index
object of the DataFrame
, which converts the Index
to a new list containing the row labels. In this case, the resulting list has the values 0, 1, 2, 3, 4
.
You can also use the tolist
method on a Series
object to convert the Index
of that Series
to a list.
For example, if you wanted to convert the Index
of the B
column to a list, you could do the following:
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50],
'C': [100, 200, 300, 400, 500]
})
# Convert the Index of column B to a list
idx_list = df['B'].index.tolist()
# Print the resulting list
print(idx_list)
[0, 1, 2, 3, 4]
In the code above, the tolist
method is applied to the Index
object of the B
column, which converts the Index
to a new list containing the row labels. In this case, the resulting list has the values 0, 1, 2, 3, 4
.
Related tutorials curated for you
How to groupby mean in Pnadas
How to create a bar chart in Pandas
How to reshape a Pandas DataFrame
How to use str.split() in Pandas
How to convert string to float in Pandas
What is idxmax() in Pandas?
How to give multiple conditions in loc() in Pandas
How to read a TSV file in Pandas
How to use ffill() in Pandas
How to apply a function to multiple columns in Pandas
How to convert a series to a NumPy array in Pandas
How to convert Pandas timestamp to datetime