Bru*_*cci 4 python numpy pandas
我有一个数据框...
>>> 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
Run Code Online (Sandbox Code Playgroud)
如果“数字”是“字母”列的最小值,我想将“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
Run Code Online (Sandbox Code Playgroud)
我很难将点连接起来以将 '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
Run Code Online (Sandbox Code Playgroud)
所以这里发生的事情是,通过调用loc我们只选择您的transform方法返回的行,这些行会1根据需要设置。
不确定它是否很重要,但您可以调用,unique以便您只获得行标签而不会重复,这可能会更快:
df.loc[df.groupby('letters')['numbers'].transform('idxmin').unique(), 'is_min']=1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8619 次 |
| 最近记录: |