我的熊猫lambda地图出了什么问题?

时间:2015-12-10 17:11:49

标签: python numpy pandas lambda

我试图找到第二个数据帧中的观察值所属的数据帧的百分位数,我认为lambda函数可以像这样做:

df1.var1.map(lambda x: np.percentile(df2.var1, x))
我在系列x中为每个df1.var1阅读的

应用了np.percentile(df2.var1, x)函数,该函数在系列x中找到了df2.var1的百分位数。出于某种原因,我收到了错误

kth(=-9223372036854775599) out of bounds (209)

其中209是df2的长度,但我不知道kth部分指的是什么。我在这里做错了什么想法?

完全错误:

ValueError                                Traceback (most recent call last)
<ipython-input-82-02d5cacfecd4> in <module>()
----> 1 df1.var1.map(lambda x: np.percentile(df2.var1, x))
   C:\Users\ngudat\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\series.pyc in map(self, arg, na_action)
   2043                                      index=self.index).__finalize__ (self)
   2044         else:
-> 2045             mapped = map_f(values, arg)
   2046             return self._constructor(mapped,
   2047                                      index=self.index).__finalize__(self)

pandas\src\inference.pyx in pandas.lib.map_infer (pandas\lib.c:62187)()

<ipython-input-82-02d5cacfecd4> in <lambda>(x)
----> 1 df.qof.map(lambda x: np.percentile(prac_prof.qof, x))

C:\Users\ngudat\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\lib\function_base.pyc in percentile(a, q, axis, out, overwrite_input, interpolation, keepdims)
   3266     r, k = _ureduce(a, func=_percentile, q=q, axis=axis, out=out,
   3267                     overwrite_input=overwrite_input,
-> 3268                     interpolation=interpolation)
   3269     if keepdims:
   3270         if q.ndim == 0:

C:\Users\ngudat\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\lib\function_base.pyc in _ureduce(a, func, **kwargs)
   2995         keepdim = [1] * a.ndim
   2996 
-> 2997     r = func(a, **kwargs)
   2998     return r, keepdim
   2999 

C:\Users\ngudat\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\lib\function_base.pyc in _percentile(a, q, axis, out, overwrite_input, interpolation, keepdims)
   3370         weights_above.shape = weights_shape
   3371 
-> 3372         ap.partition(concatenate((indices_below, indices_above)),axis=axis)
   3373 
   3374         # ensure axis with qth is first

ValueError: kth(=-9223372036854775599) out of bounds (209)

1 个答案:

答案 0 :(得分:2)

Percentile不会在这里给你你需要的东西,它需要一个百分位并给你价值。你需要相反的。您应该对列中的条目进行排名,并从中计算百分位数:

import pandas as pd
aa = [1,3,2,4,11,8,9]
dd = pd.DataFrame(data=aa,columns=['xx'])
dd['rank']=dd['xx'].rank()
dd['percentile'] = dd['rank']/len(dd)

这为您提供了与每个条目相对应的百分位数:

   xx  rank  percentile
0   1     1    0.142857
1   3     3    0.428571
2   2     2    0.285714
3   4     4    0.571429
4  11     7    1.000000
5   8     5    0.714286
6   9     6    0.857143