繁体   English   中英

pandas应用带参数no lambda的函数

[英]pandas apply function with arguments no lambda

我试图使用apply args参数将函数应用于数据帧的行。 我看到了多个 类似的 问题 ,但是按照解决方案似乎没有用。 我已经创建了一个示例示例。

在这里,我将数据帧除以其列的总和

pij=pd.DataFrame(np.random.randn(500,2))
pij.divide(pij.sum(1),axis=0).head() 
          0         1
0  1.077353 -0.690463
1  0.608302  0.583209
2 -0.724272 -1.665318
3 -0.735404 -0.606744
4 -0.033409 -0.162695

我知道如何使用lambda来返回相同的结果

def lambda_divide(row):
    return row / row.sum(0)
pij.apply(lambda row: lambda_divide(row), axis=1).head()
          0         1
0  1.077353 -0.690463
1  0.608302  0.583209
2 -0.724272 -1.665318
3 -0.735404 -0.606744
4 -0.033409 -0.162695

但是,当我尝试使用apply参数时,它不起作用

pij.apply(np.divide,args=(pij.sum(1)))

完整的错误表明这是由于pandas特殊的套管ufuncs:

   4045
   4046         if isinstance(f, np.ufunc):
-> 4047             results = f(self.values)
   4048             return self._constructor(data=results, index=self.index,
   4049                                      columns=self.columns, copy=False)

ValueError: invalid number of arguments

这看起来像个错误!


在这种特定情况下,您可以使用div:

In [11]: df.div(df.sum(1), axis=0)
Out[11]:
          0         1
0  2.784649 -1.784649
1  0.510530  0.489470
2  0.303095  0.696905
3  0.547931  0.452069
4  0.170364  0.829636

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM