python - 在 pandas 数据框中的 block 中查找第一个 'True' 值

标签 python pandas

我有一个数据框,其中一列仅包含 block 中的 True 或 False 值。例如:

df =   
            b
  0     False
  1      True
  2      True
  3     False
  4      True
  5      True
  6      True
  7      True
  8     False
  9     False
 10     False
 11     False
 12     False
 13      True
 14      True
 15      True

我需要用 True 找到 block 的开头:

>> find_first_true(df)
>> array([1, 4, 13])

有什么优雅的解决方案吗?

编辑

感谢您提出的解决方案。我想知道,从我找到的索引开始提取一定长度的 block 的最简单方法是什么?

例如,我需要在索引之前获取长度为 4 的 block (行数)。所以,如果我的索引(之前找到)

index = array([1, 4, 13])

然后我需要积木:

[df.loc[0:4], df.loc[9:13]]

            b
  0     False
  1      True
  2      True
  3     False
  4      True
  9     False
 10     False
 11     False
 12     False
 13      True

我正在遍历索引,但想知道更多 pandasian 解决方案

最佳答案

In [2]: df = pd.read_clipboard()
In [3]: df
Out[3]:
        b
0   False
1    True
2    True
3   False
4    True
5    True
6    True
7    True
8   False
9   False
10  False
11  False
12  False
13   True
14   True
15   True
In [11]: np.where(((df.b != df.b.shift(1)) & df.b).values)[0]
Out[11]: array([ 1,  4, 13], dtype=int64)

关于python - 在 pandas 数据框中的 block 中查找第一个 'True' 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45417303/

相关文章:

python - Django View : working with a file result in indentation error

python - uwsgi_param 和 proxy_set_header 的区别

python - 一个更简单的案例列表

Python:通过升序重新排列DataFrame中的列顺序

python - 比较 Pandas 列中的上一个和下一个不同值

python - 正则表达式捕获组的可选顺序

Python绘图无法运行: 'x and y must have same first dimension'

python - 使用 fillna、downcast 和 pandas

python - 将行转换为单行的问题

python - 空数据错误 : No columns to parse from file about streamlit