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