alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[1055] Get the index of the “True” values in a Pandas Series

To get the index of the “True” values in a Pandas Series, you can use the index attribute along with boolean indexing. Here’s a simple way to do it:

  1. Import Pandas:

    import pandas as pd
  2. Create your Series:

    series = pd.Series([True, False, True, False, True])
  3. Get the indices of “True” values:

    true_indices = series[series].index
  4. Convert to a list (optional):

    true_indices_list = list(true_indices)

Here’s the complete code snippet:

import pandas as pd
# Create your Series
series = pd.Series([True, False, True, False, True])
# Get the indices of "True" values
true_indices = series[series].index
# Convert to a list (optional)
true_indices_list = list(true_indices)
print(true_indices_list)

This will output:

[0, 2, 4]

This method uses boolean indexing to filter the Series for “True” values and then retrieves their indices.

Would you like more details or help with another aspect of Pandas?


Sure, let’s break down the script step by step:

Script:

true_indices = series[series].index

Explanation:

  1. series[series]:

    • This part uses boolean indexing. When you use a Series as an indexer for itself, it filters the Series based on the boolean values it contains.
    • For example, if series is:
      0 True
      1 False
      2 True
      3 False
      4 True
      dtype: bool
      Then series[series] will return only the elements where the value is True:
      0 True
      2 True
      4 True
      dtype: bool
  2. .index:

    • The .index attribute of a Series returns the index labels of the Series.
    • Applying .index to the filtered Series (series[series]) will give you the indices of the True values.

Putting it all together:

  • series[series] filters the Series to include only the True values.
  • .index extracts the indices of these True values.

So, if series is:

0 True
1 False
2 True
3 False
4 True
dtype: bool

Then true_indices will be:

Int64Index([0, 2, 4], dtype='int64')

This means the indices of the True values are 0, 2, and 4.

Does this help clarify things? Would you like to dive deeper into any part of the explanation?

posted on   McDelfino  阅读(17)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2023-09-05 【876】Top 50 matplotlib Visualizations – The Master Plots (with full python code)
2023-09-05 【875】numpy复制并扩充维度
2021-09-05 【657】深度学习模型预测单张图片
2021-09-05 【656】SegNet 相关说明
点击右上角即可分享
微信分享提示