Apply Function on DataFrame Index

后端 未结 4 1855
孤独总比滥情好
孤独总比滥情好 2021-01-31 01:22

What is the best way to apply a function over the index of a Pandas DataFrame? Currently I am using this verbose approach:

pd.DataFrame({\"Month\":          


        
4条回答
  •  执念已碎
    2021-01-31 01:45

    As already suggested by HYRY in the comments, Series.map is the way to go here. Just set the index to the resulting series.

    Simple example:

    df = pd.DataFrame({'d': [1, 2, 3]}, index=['FOO', 'BAR', 'BAZ'])
    df
            d
    FOO     1
    BAR     2
    BAZ     3
    
    df.index = df.index.map(str.lower)
    df
            d
    foo     1
    bar     2
    baz     3
    

    Index != Series

    As pointed out by @OP. the df.index.map(str.lower) call returns a numpy array. This is because dataframe indices are based on numpy arrays, not Series.

    The only way of making the index into a Series is to create a Series from it.

    pd.Series(df.index.map(str.lower))
    

    Caveat

    The Index class now subclasses the StringAccessorMixin, which means that you can do the above operation as follows

    df.index.str.lower()
    

    This still produces an Index object, not a Series.

提交回复
热议问题