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?
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.
To convert an index to a list in Pandas, use Index 's tolist() method.
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.
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.
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.
.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.
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.
To get the index
values as a list
/list
of tuple
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With