Apply Function on DataFrame Index

后端 未结 4 1929
孤独总比滥情好
孤独总比滥情好 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:38

    You can always convert an index using its to_series() method, and then either apply or map, according to your preferences/needs.

    ret = df.index.map(foo)                # Returns pd.Index
    ret = df.index.to_series().map(foo)    # Returns pd.Series
    ret = df.index.to_series().apply(foo)  # Returns pd.Series
    

    All of the above can be assigned directly to a new or existing column of df:

    df["column"] = ret
    

    Just for completeness: pd.Index.map, pd.Series.map and pd.Series.apply all operate element-wise. I often use map to apply lookups represented by dicts or pd.Series. apply is more generic because you can pass any function along with additional args or kwargs. The differences between apply and map are further discussed in this SO thread. I don't know why pd.Index.apply was omitted.

提交回复
热议问题