我有一个 Dataframe,table
,看起来像这样:
year name prop sex soundex
1880 John 0.081541 boy J500
1880 William 0.080511 boy W450
....
2008 Elianna 0.000127 girl E450
我正在尝试按 'year'
对 table
进行分组,并为每个组访问 'name'
列中的选择索引。
我的代码如下(假设special_indices
已经定义):
def get_indices_func(x):
name = [x['name'].iloc[y] for y in special_indices]
return pd.Series(name)
table.groupby(by='year').apply(get_indices_func)
我收到以下错误:
/Users/***/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
722 """
723 try:
--> 724 return self._engine.get_value(series, key)
725 except KeyError, e1:
726 if len(self) > 0 and self.inferred_type == 'integer':
KeyError: 1000
我做错了什么?我想我并没有真正理解 apply(及其表兄弟 aggregate 和 agg)是如何工作的。如果有人能解释一下,我将不胜感激!
最佳答案
I'm trying to find the most popular name for each year. Is there a clever way to go about doing this?
有一种无需排序的方法:给定一个像这样的 DataFrame:
In [5]: df
Out[5]:
year name prop sex soundex
0 1880 John 0.081541 boy J500
1 1880 William 0.080511 boy W450
2 2008 Elianna 0.000127 girl E450
[3 rows x 5 columns]
您可以按年份分组,隔离 prop 列,应用 argmax
,并使用 loc
来选择所需的行:
In [15]: df.loc[df.groupby('year')['prop'].apply(lambda x: x.argmax())]
Out[15]:
year name prop sex soundex
0 1880 John 0.081541 boy J500
2 2008 Elianna 0.000127 girl E450
[2 rows x 5 columns]
In [19]: df['name'].loc[df.groupby('year')['prop'].apply(lambda x: x.argmax())]
Out[19]:
0 John
2 Elianna
Name: name, dtype: object
请注意,argmax
和loc
的使用依赖于具有唯一索引的df
。如果 DataFrame 没有唯一索引,您需要首先使索引唯一:
df.reset_index()
请注意,argmax
是一个O(n)
操作,而排序是O(n log n)
。即使对于小型 DataFrame,速度优势也是显而易见的:
In [125]: %timeit df[['year', 'name']].loc[df.groupby('year')['prop'].apply(lambda x: x.argmax())]
1000 loops, best of 3: 1.07 ms per loop
In [126]: %timeit df.groupby('year').apply(lambda x: x.sort('prop', ascending=False).iloc[0]['name'])
100 loops, best of 3: 2.14 ms per loop
基准测试在此 DataFrame 上运行:
In [131]: df
Out[131]:
year name prop sex soundex
0 2008 A 0.000027 girl E450
1 1880 John 0.081541 boy J500
2 2008 B 0.000027 girl E450
3 2008 Elianna 0.000127 girl E450
4 1880 William 0.080511 boy W450
5 2008 C 0.000027 girl E450
6 1880 D 0.080511 boy W450
[7 rows x 5 columns]
关于python - 在 Pandas 中使用 'apply'(外部定义函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23862429/