Get row-index values of Pandas DataFrame as list?

PythonListPandasIndexing

Python Problem Overview


I'm probably using poor search terms when trying to find this answer. Right now, before indexing a DataFrame, I'm getting a list of values in a column this way...

 list = list(df['column']) 

...then I'll set_index on the column. This seems like a wasted step. When trying the above on an index, I get a key error.

How can I grab the values in an index (both single and multi) and put them in a list or a list of tuples?

Python Solutions


Solution 1 - Python

To get the index values as a list/list of tuples for Index/MultiIndex do:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

or

list(df.index.values)  # this will always work in pandas

Solution 2 - Python

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTravisVOXView Question on Stackoverflow
Solution 1 - PythonPhillip CloudView Answer on Stackoverflow
Solution 2 - PythonsmciView Answer on Stackoverflow