Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row-index values of Pandas DataFrame as list? [duplicate]

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?

like image 778
TravisVOX Avatar asked Aug 21 '13 13:08

TravisVOX


People also ask

Can Pandas DataFrame index have duplicates?

duplicated() function Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated.

How do you get the index of a DataFrame as a list?

To convert an index to a list in Pandas, use Index 's tolist() method.

Can index have duplicates?

Duplicate indexes are those that exactly match the Key and Included columns. That's easy. Possible duplicate indexes are those that very closely match Key/Included columns.

How to get the index or rows of a pandas Dataframe?

In Python, we can easily get the index or rows of a pandas DataFrame object using a for loop. In this method, we will create a pandas DataFrame object from a Python dictionary using the pd.DataFrame () function of pandas module in Python.

How to convert a pandas Dataframe to a Python list?

This is a handy tool of the pandas module which converts the index of a pandas DataFrame object into a Python list. In this method, we create a pandas DataFrame object using the pd.DataFrame () function as we did in the previous methods.

How do you select the 5th row in a Dataframe?

.iloc selects rows based on an integer index. So, if you want to select the 5th row in a DataFrame, you would use df.iloc [ [4]] since the first row is at index 0, the second row is at index 1, and so on. .loc selects rows based on a labeled index.

How to extract each row of a Dataframe into a list?

Now we will use the DataFrame.iterrows () function to iterate over each of the row of the given Dataframe and construct a list out of the data of each row. As we can see in the output, we have successfully extracted each row of the given dataframe into a list.


1 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 
like image 86
Phillip Cloud Avatar answered Oct 03 '22 02:10

Phillip Cloud