我对df.apply()
如何运作感到非常困惑。这是我遇到的问题之一:
import seaborn as sns
tips = sns.load_dataset("tips")
tips['tip_pct'] = tips['tip'] / tips['total_bill']
tips.head()
total_bill tip smoker day time size tip_pct
0 16.99 1.01 No Sun Dinner 2 0.059447
1 10.34 1.66 No Sun Dinner 3 0.160542
2 21.01 3.50 No Sun Dinner 3 0.166587
3 23.68 3.31 No Sun Dinner 2 0.139780
4 24.59 3.61 No Sun Dinner 4 0.146808
我正在尝试按tips
列排序tips['tip_pct']
。我可以直接申请sort_values
。
In [153]: tips.sort_values(by='tip_pct').head()
Out[153]:
total_bill tip smoker day time size tip_pct
237 32.83 1.17 Yes Sat Dinner 2 0.035638
102 44.30 2.50 Yes Sat Dinner 3 0.056433
57 26.41 1.50 No Sat Dinner 2 0.056797
0 16.99 1.01 No Sun Dinner 2 0.059447
187 30.46 2.00 Yes Sun Dinner 5 0.065660
现在,我首先尝试按smoker
列对此数据框进行分组,然后按tip_pct
列进行排序。
In [156]: tips.groupby('smoker').apply(lambda x: x.sort_values(by='tip_pct')).head()
Out[156]:
total_bill tip smoker day time size tip_pct
smoker
No 57 26.41 1.50 No Sat Dinner 2 0.056797
0 16.99 1.01 No Sun Dinner 2 0.059447
48 28.55 2.05 No Sun Dinner 3 0.071804
146 18.64 1.36 No Thur Lunch 3 0.072961
130 19.08 1.50 No Thur Lunch 2 0.078616
我试图理解groupby
和apply
如何协同工作,所以我尝试了以下方法,但它失败了。
In [157]: for name, group in tips.groupby('smoker'):
...: group.apply(lambda x: x.sort_values(by='tip_pct'))
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-157-5b5096eaa4d6> in <module>()
1 for name, group in tips.groupby('smoker'):
----> 2 group.apply(lambda x: x.sort_values(by='tip_pct'))
3
//anaconda/lib/python3.5/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
4260 f, axis,
4261 reduce=reduce,
-> 4262 ignore_failures=ignore_failures)
4263 else:
4264 return self._apply_broadcast(f, axis)
//anaconda/lib/python3.5/site-packages/pandas/core/frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)
4356 try:
4357 for i, v in enumerate(series_gen):
-> 4358 results[i] = func(v)
4359 keys.append(v.name)
4360 except Exception as e:
<ipython-input-157-5b5096eaa4d6> in <lambda>(x)
1 for name, group in tips.groupby('smoker'):
----> 2 group.apply(lambda x: x.sort_values(by='tip_pct'))
3
TypeError: ("sort_values() got an unexpected keyword argument 'by'", 'occurred at index total_bill')
我理解失败的原因是因为apply()
函数会在每列上尝试sort_value
,因此by
不适用于series.sort_values()
。但是,我不明白为什么groupby
没有任何问题。根据我的理解,groupby
只是拆分数据集,因此它仍然是几个较小的数据框,在应用sort_values()
时会出现上述问题。
有人可以解释为什么groupby
和apply(sort_values)
没有因直接将sort_values
应用于原始数据框而导致的任何问题?
提前致谢!