gpt4 book ai didi

python - Pandas 在 groupby 中设置值

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:54 24 4
gpt4 key购买 nike

我有一个数据框...

>>> 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”列设置为 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”的值设置为 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

关于python - Pandas 在 groupby 中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35046725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com