如何使用Pandas获取数据集中Score列负值的索引?
获取Score列负值对应的索引
Got it, let's walk through how to get the indices of negative values in your Score column.
First, let's recap your sample data to make sure we're on the same page:
sdf.head()
Out[65]:
Score
0 161
1 238
2 -53
3 83
4 171
Method 1: Boolean Indexing + .index
The simplest way is to use a boolean mask to filter rows where Score is negative, then extract their indices:
# Create a boolean mask for negative values negative_mask = sdf['Score'] < 0 # Filter the dataframe and get the indices negative_indices = sdf[negative_mask].index # If you want the indices as a list instead of an Index object negative_indices_list = negative_indices.tolist()
Running this on your sample data would give:
negative_indices→Int64Index([2], dtype='int64')negative_indices_list→[2]
Method 2: Using .loc (Concise Alternative)
You can also condense this into a single line with .loc:
negative_indices = sdf.loc[sdf['Score'] < 0].index
This works exactly the same as the first method—it's just a more compact way to write it.
Quick Breakdown
- The boolean mask
sdf['Score'] < 0generates a Series where each entry isTrueif the correspondingScoreis negative, andFalseotherwise. - Slicing the dataframe with this mask keeps only the rows where the mask is
True. - Calling
.indexon the filtered subset pulls out the original indices of those negative-value rows.
内容的提问来源于stack exchange,提问作者IndigoChild
相关产品推荐
相关产品推荐

