Use function (not using lambda) with apply method for pandas DataFrame
我正在尝试根据此页后面的数据框中的现有列添加列。由于if case很多,所以我将if case定义为函数(getdirection方法),并尝试通过apply方法(adddirection方法)调用。不过,我有以下错误。
1 | TypeError: getDirection() takes 1 positional argument but 2 were given |
有人能告诉我如何通过应用数据帧来调用函数吗?代码如下所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | def addDirection(self): group=self.group group['direction']=group['Azimuth [deg]'].apply(self.getDirection) def getDirection(angle): if angle < 11.25 or angle >= 348.75: return"N" elif angle < 33.75 and angle >= 11.25: return"NNE" elif angle < 56.25 and angle >= 33.75: return"NE" elif angle < 78.75 and angle >= 56.25: return"ENE" elif angle < 101.25 and angle >= 78.75: return"E" elif angle < 123.75 and angle >= 101.25: return"ESE" elif angle < 146.25 and angle >= 123.75: return"SE" elif angle < 168.75 and angle >= 146.25: return"SSE" elif angle < 191.25 and angle >= 168.75: return"S" elif angle < 213.75 and angle >= 191.25: return"SSW" elif angle < 236.25 and angle >= 213.75: return"SW" elif angle < 258.75 and angle >= 236.25: return"WSW" elif angle < 281.25 and angle >= 258.75: return"W" elif angle < 303.75 and angle >= 281.25: return"WNW" elif angle < 326.25 and angle >= 303.75: return"NW" elif angle < 348.75 and angle >= 326.25: return"NNW" |
正如@cornflex所说,是因为你使用self传递了额外的参数,所以你得到了这个错误。要么是
因为它的大熊猫不是那么多,如果不是的话,我们可以用pd.cut,也就是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | df = pd.DataFrame({'Azimuth [deg]':[300,340,150]}) bins = [11.25, 33.75, 56.25, 78.75, 101.25, 123.75, 146.25, 168.75, 191.25, 213.75, 236.25, 258.75, 281.75, 303.75, 326.25, 348.75] labels = ['NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'] pd.cut(df['Azimuth [deg]'],bins=bins,labels=labels).fillna('N') # fillna is for your first condition. 0 WNW 1 NNW 2 SSE Name: Azimuth [deg], dtype: category Categories (15, object): [NNE < NE < ENE < E ... W < WNW < NW < NNW] In [557]: df['Azimuth [deg]'].apply(getDirection) 0 WNW 1 NNW 2 SSE Name: Azimuth [deg], dtype: object |
调用
调用函数的方式(在
如果错误地将函数作为实例方法调用,则应编写
如果希望
另请参见关于实例和类方法的这个答案。