Get row-index values of Pandas DataFrame as list?

Question:

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?

Asked By: TravisVOX

||

Answers:

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
Answered By: Phillip Cloud

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.

Answered By: smci
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.