我遇到了一个我无法理解的奇怪的 python 错误:
import pandas as pd
import numpy as np
def logit(p):
if 0 < p < 1:
return np.log(p / (1 - p))
elif p == 0 or p == 1:
return pd.NA
else:
raise ValueError(f"logit input must be [0,1], got {p}")
class D(object):
d = pd.DataFrame({'prob': np.random.rand(100)})
transformation = logit
def transform1(self):
d = self.d
self.transformation = [self.transformation]
for trans in self.transformation:
d['prob'] = d['prob'].apply(trans)
@staticmethod
def transform2(d, transformation):
transformation = [transformation]
for trans in transformation:
d['prob'] = d['prob'].apply(trans)
当我做:
In [5]: dat = D()
In [6]: dat.transform1()
--------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-602e90bcb76e> in <module>
----> 1 dat.transform1()
<ipython-input-4-3de477ddc9d9> in transform1(self)
17 self.transformation = [self.transformation]
18 for trans in self.transformation:
---> 19 d['prob'] = d['prob'].apply(trans)
20
21 @staticmethod
~/anaconda3/envs/py377/lib/python3.7/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
3846 else:
3847 values = self.astype(object).values
-> 3848 mapped = lib.map_infer(values, f, convert=convert_dtype)
3849
3850 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
TypeError: logit() takes 1 positional argument but 2 were given
但其他类似的实现工作正常
In [8]: dat.transform2(dat.d, logit)
In [9]: dat.d.head()
Out[9]:
prob
0 -0.766136
1 -0.279224
2 1.209884
3 -0.461204
4 -1.265117
似乎在transform1
,当我调用apply
apd.DataFrame
时,类对象本身被传递到应用函数中:
In [1]: import pandas as pd
...: import numpy as np
...:
...: def logit(*p):
...: print(p)
...: if 0 < p < 1:
...: return np.log(p / (1 - p))
...: elif p == 0 or p == 1:
...: return pd.NA
...: else:
...: raise ValueError(f"logit input must be [0,1],
...: got {p}")
In [2]: dat.transform1()
(<__main__.D object at 0x7fb2b01cda50>, 0.24971056160452076)
-------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-602e90bcb76e> in <module>
----> 1 dat.transform1()
为什么会这样?我正在使用Python 3.7.7
. 谢谢!