熊猫在groupby中设置值

布鲁斯·普契(Bruce Pucci)

我有一个DataFrame ...

>>> df = pd.DataFrame({
...            'letters' : ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], 
...            'is_min' : np.zeros(9),
...            'numbers' : np.random.randn(9)
... })

    is_min  letters numbers
0   0       a       0.322499
1   0       a      -0.196617
2   0       a      -1.194251
3   0       b       1.005323
4   0       b      -0.186364
5   0       b      -1.886273
6   0       c       0.014960
7   0       c      -0.832713
8   0       c       0.689531

如果“数字”是列“字母”的最小值,我想将“ is_min” col设置为1。我已经尝试过了,觉得自己很亲近...

>>> df.groupby('letters')['numbers'].transform('idxmin')

0    2
1    2
2    2
3    5
4    5
5    5
6    7
7    7
8    7
dtype: int64

我很难连接各个点以将'is_min'的val设置为1。

埃德·楚姆

将行标签传递给loc并设置列:

In [34]:
df.loc[df.groupby('letters')['numbers'].transform('idxmin'), 'is_min']=1
df

Out[34]:
   is_min letters   numbers
0       1       a -0.374751
1       0       a  1.663334
2       0       a -0.123599
3       1       b -2.156204
4       0       b  0.201493
5       0       b  1.639512
6       0       c -0.447271
7       0       c  0.017204
8       1       c -1.261621

因此,这里发生的是,通过调用,loc我们仅选择您的transform方法返回的行,并将其设置1为所需的行。

不知道这是否重要,但是您可以致电unique以便您仅获得行标签而无需重复,这可能会更快:

df.loc[df.groupby('letters')['numbers'].transform('idxmin').unique(), 'is_min']=1

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章