gpt4 book ai didi

python - 如何检测 DataFrame 中某些值的连续性?

转载 作者:太空宇宙 更新时间:2023-11-04 02:21:00 25 4
gpt4 key购买 nike

在 Python DataFrame 中,我想检测一行中 False 值 block 的开始和结束位置。如果该 block 仅包含一个 False,我想获得该位置。

例子:

df = pd.DataFrame({"a": [True, True, True,False,False,False,True,False,True],})
In[110]: df
Out[111]:
a
0 True
1 True
2 True
3 False
4 False
5 False
6 True
7 False
8 True

在这个例子中,我想获得位置

`3`, `5`

`7`, `7`.

最佳答案

使用:

a = (df.a.cumsum()[~df.a]
.reset_index()
.groupby('a')['index']
.agg(['first','last'])
.values
.tolist())
print(a)
[[3, 5], [7, 7]]

解释:

先通过cumsum得到累计和- 获取所有 False 唯一组:

print (df.a.cumsum())
0 1
1 2
2 3
3 3
4 3
5 3
6 4
7 4
8 5
Name: a, dtype: int32

仅过滤 Falseboolean indexing使用反转 bool 列:

print (df.a.cumsum()[~df.a])
3 3
4 3
5 3
7 4
Name: a, dtype: int32

根据 reset_index 的索引创建列:

print (df.a.cumsum()[~df.a].reset_index())
index a
0 3 3
1 4 3
2 5 3
3 7 4

每个组按 agg 聚合函数 firstlast :

print (df.a.cumsum()[~df.a].reset_index().groupby('a')['index'].agg(['first','last']))
first last
a
3 3 5
4 7 7

最后转换为嵌套的 list:

print (df.a.cumsum()[~df.a].reset_index().groupby('a')['index'].agg(['first','last']).values.tolist())
[[3, 5], [7, 7]]

关于python - 如何检测 DataFrame 中某些值的连续性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51626733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com