Accessing a Pandas index like a regular column

后端 未结 3 2105
后悔当初
后悔当初 2021-02-19 02:29

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

相关标签:
3条回答
  • 2021-02-19 03:03

    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')
    
    0 讨论(0)
  • 2021-02-19 03:24

    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']
    
    0 讨论(0)
  • 2021-02-19 03:27

    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:

    • If it's "just another column", use reset_index and treat it as another column.
    • If it's genuinely used for indexing, keep it as an index and use 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:

    • What is the performance impact of non-unique indexes in pandas?
    • What is the point of indexing in pandas?
    0 讨论(0)
提交回复
热议问题