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\":
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.