在DataFrame索引上应用函数 [英] Apply Function on DataFrame Index
问题描述
在Pandas DataFrame
的索引上应用函数的最佳方法是什么?
目前我正在使用这种冗长的方法:
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": df.reset_index().Date.apply(foo)})
其中日期
是索引的名称, foo
是我正在申请的函数的名称。
where Date
is the name of the index and foo
is the name of the function that I am applying.
推荐答案
正如HYRY在评论中所建议的, Series.map 是这里的方法。只需将索引设置为结果系列。
As already suggested by HYRY in the comments, Series.map is the way to go here. Just set the index to the resulting series.
简单示例:
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
索引!=系列
正如@OP所指出的那样。 df.index.map(str.lower)
调用返回一个numpy数组。
这是因为数据帧索引是基于numpy数组,而不是系列。
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))
警告
指数
class现在是 StringAccessorMixin
的子类,这意味着您可以执行以下操作,如下所示
Caveat
The Index
class now subclasses the StringAccessorMixin
, which means that you can do the above operation as follows
df.index.str.lower()
这仍然会生成一个Index对象,而不是一个Series。
This still produces an Index object, not a Series.
这篇关于在DataFrame索引上应用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!