在大 pandas DataFrame中对数据进行条件选择 [英] Conditional selection of data in a pandas DataFrame
问题描述
我的大熊猫DataFrame中有两列。
I have two columns in my pandas DataFrame.
A B
0 1 5
1 2 3
2 3 2
3 4 0
4 5 1
我需要A中的值,其中B的值最小。在上述情况下,我的答案将是4,因为最小B值为0。
I need the value in A where the value of B is minimum. In the above case my answer would be 4 since the minimum B value is 0.
任何人都可以帮助我吗?
Can anyone help me with it?
推荐答案
要查找列B中的最小值,可以使用 df.B.min()
。对于您的DataFrame,它返回 0
。
To find the minimum in column B, you can use df.B.min()
. For your DataFrame this returns 0
.
要在DataFrame的特定位置查找值,可以使用 loc
:
To find values at particular locations in a DataFrame, you can use loc
:
>>> df.loc[(df.B == df.B.min()), 'A']
3 4
Name: A, dtype: int64
所以这里, loc
选出列B等于其最小值的所有行值( df.B == df.B.min()
),并在列A中选择相应的值。
So here, loc
picks out all of the rows where column B is equal to its minimum value (df.B == df.B.min()
) and selects the corresponding values in column A.
此方法返回A中与B中的最小值相对应的所有值。如果只需要找到其中一个值,最好使用 idxmin
作为@ aus_lacy建议。
This method returns all values in A corresponding to the minimum value in B. If you only need to find one of the values, the better way is to use idxmin
as @aus_lacy suggests.
这篇关于在大 pandas DataFrame中对数据进行条件选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!