pandas multigroup apply()更改视图值

2024-06-26 14:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

由于某些原因,这不起作用:

样本数据:

dt = pd.DataFrame({'sid':['a']*9 + ['b']*9 + ['c']*9,
                   'src': [1] *18 + [2] * 9,
                   'val':np.random.randn(27),
                    'dval': [0]*18 + np.random.rand(9)})

我想根据src、sid进行多组,并根据一些val标准,为那些c行更改dval行值。你知道吗

我一直收到一个StopIteration错误。你知道吗

# -- set bycp threshold for probability val to alert
    def quantg(g):
        try:

            g['dval'] = g['dval'].apply(lambda x: x > x['val'].quantile(.90) and 1 or 0 )
            print '***** bycp ', g.head(2)
            #print 'discretize bycp ', g.head()
            return g
        except (Exception,StopIteration) as e:
            print '**bycp error\n', e
            print g.info()
            pass

然后我尝试在groupby之前按行筛选:

d = d[d['alert_t']=='bycp'].groupby(['source','subject_id','alert_t','variable']).apply(quantg )

我还尝试了多级选择:

 # -- xs for multilevel select
 g['dval'] = g.xs(('c','sid')).map(lambda x: len(g['value']) and\
                                                             #(x>g['value'].quantile(.90) and 1 or 0 ))

但是运气不好!你知道吗

获取frameindexstopiteration类型错误。你知道吗

怎么办,我怎么办?你知道吗


Tags: andsrcfor错误nprandomvalalert
1条回答
网友
1楼 · 发布于 2024-06-26 14:37:10

以下操作与您认为的不同:

x > x['val'].quantile(.90) and 1 or 0

事实上,如果你用一个序列来尝试,它应该会引起一个ValueError。

In [11]: dt and True
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

在编写这样的内容时,您希望使用np.where

np.where(x > x['val'].quantile(.90), 1, 0)

注意:astype('int64')也会起作用,或者把它作为bool。。。

但是,我想我可以在这里使用一个转换(提取每个组的分位数,然后掩盖这个),如下所示:

q90 = g.transform(lambda x: x.quantile(.90))
df[df.val > q90]

相关问题 更多 >