python - Pandas:返回值的第一个实例和最后一个实例的索引值
问题描述
我有以下数据框:
df = pd.DataFrame({'index':[0,1,2,3,4,5,6,7,8,9,10], 'X':[0,0,1,1,0,0,1,1,1,0,0]})
df.set_index('index', inplace = True)
X
index
0 0
1 0
2 1
3 1
4 0
5 0
6 1
7 1
8 1
9 0
10 0
我需要的是返回一个元组列表,显示每个 1 序列的 1 的第一个和最后一个实例的索引值(对不起,如果这令人困惑)。IE
想:
[(2,3), (6,8)]
第一个 1 的第一个实例出现在索引点 2,然后该序列中的最后一个 1 出现在索引点 3。下一个 1 出现在索引点 6,该序列中的最后一个 1 出现在索引点 8。
我试过的:
我可以使用 numpy 的 argmax 函数来获取第一个。IE
x1 = np.argmax(df.values)
y1 = np.argmin(df.values[x1:])
(x1,2 + y1 - 1)
这会给我第一个元组,但迭代似乎很混乱,我觉得有更好的方法。
解决方案
你需要more_itertools.consecutive_groups
import more_itertools as mit
def find_ranges(iterable):
"""Yield range of consecutive numbers."""
for group in mit.consecutive_groups(iterable):
group = list(group)
if len(group) == 1:
yield group[0]
else:
yield group[0], group[-1]
list(find_ranges(df['X'][df['X']==1].index))
输出:
[(2, 3), (6, 8)]
推荐阅读
- java - WindowBuilder 无法显示 GUI。无法加载组件 javax.swing.JFrame 的 *.wbp-component.xml 描述
- impala - 重启后 Impala 无法读取内置函数
- azure-active-directory - 想要将 Azure 弹性池(在故障转移组中配置)从一个订阅移动到另一个订阅(不同的租户)
- python - Selenium Python 由于睡眠不足而崩溃
- python-3.x - 使用 flake8 的 Gitlab CI 退出代码 1
- reactjs - mui 主题颜色不适用
- apache-spark - 如何根据 Pyspark 中的单元格值重命名列?
- angular - Angular Web-app 麦克风切换导致错误“NotReadableError:并发麦克风进程限制”
- angular - Angular 以 dd/MM/yyyy HH:mm 格式获取过去 24 小时的日期
- c# - 如何使用 c# 从 ajax 中的嵌套 JSON 对象中获取值