I have a Pandas DataFrame with a named index. I want to pass it off to a piece off code that takes a DataFrame, a column name, and some other stuff, and does a bunch of work inv
You could also use df.index.get_level_values
if you need to access a (index) column by name. It also works with hierarchical indices (MultiIndex
).
>>> df.index.get_level_values('name')
Index(['a', 'b', 'c', 'd', 'e'], dtype='object', name='name')
Instead of using reset_index
, you could just copy the index to a normal column, do some work and then drop the column, for example:
df['tmp'] = df.index
# do stuff based on df['tmp']
del df['tmp']
Index has a special meaning in Pandas. It's used to optimise specific operations and can be used in various methods such as merging / joining data. Therefore, make a choice:
reset_index
and treat it as another column.df.index
.We can't make this choice for you. It should be dependent on the structure of your underlying data and on how you intend to analyse your data.
For more information on use of a dataframe index, see: