首页 > 解决方案 > 如何检索索引中的前两个值?

问题描述

我正在遍历一个索引并用这个打印出一些值:

fl = gis.content.get(fl_item_id).layers[fl_item_idx].query(where="City = 'Round Rock'", order_by_fields='Date_Confirmed DESC' ).sdf

for index, total in fl.iterrows():
    print(total['Cumulative_Totals'])

这导致:

4020
3965
3937
3880
3832
3775
3714
3699
3670
3615
3533
3502
3475
3441
3371
3338
3314
3275
3258
3256
3221
3198
3178
3162

我想从上面的输出中获取前两个值并将它们分配给一个变量。我在想我需要以某种方式将其包装在for i in range(2) 中...

fl 看起来像这样:

OBJECTID    Date_Confirmed  City    Cumulative_Totals
0   324541  2020-12-02 06:00:00 Round Rock  4020
1   324540  2020-12-01 06:00:00 Round Rock  3965
2   324539  2020-11-30 06:00:00 Round Rock  3937
3   324538  2020-11-29 06:00:00 Round Rock  3880
4   324537  2020-11-28 06:00:00 Round Rock  3832
... ... ... ... ...
237 324304  2020-03-27 05:00:00 Round Rock  8
238 324303  2020-03-25 05:00:00 Round Rock  6
239 324302  2020-03-24 05:00:00 Round Rock  5
240 324301  2020-03-22 05:00:00 Round Rock  2
241 324300  2020-03-19 05:00:00 Round Rock  1

标签: pythonpython-3.xjupyter-notebook

解决方案


要将n迭代器的第一个元素作为列表获取,您可以使用list(itertools.islice(it, n)).

或者,如果您只想要该特定字段:

cumtotals = [total['Cumulative_Totals']
             for _, total in itertools.islice(fl.iterrows(), 2)]

推荐阅读