使用 df.iterrows() 迭代时如何检查我是否在最后一行?

问题描述 投票:0回答:3

如何在使用

df.itterows()
遍历行时检查我是否位于最后一行?

我的代码:

for index, row in df.iterrows():
...     # I want to check last row in df iterrows(). somelike row[0].tail(1)
python pandas dataframe
3个回答
20
投票

使用

for i, (index, row) in enumerate(df.iterrows()):
    if i == len(df) - 1:
        pass

18
投票

pandas.DataFrame 类有一个可下标的

index
属性。 因此,可以在使用
iterrows()
对照 df.index 属性的最后一个值迭代行时检查行的索引,如下所示:

for idx,row in df.iterrows():
    if idx == df.index[-1]:
        print('This row is last')

-1
投票
for idx,row in df.iterrows():
    if idx == df.index[0]:
        print('This is the first row)

我在互联网上搜索并尝试使用 Microsoft Copilot 进行各种搜索,以帮助我检查循环是否位于数据帧组的第一次迭代上,并偶然发现了上述解决方案。我将这篇文章发布给那些寻找解决方案来检查第一行的人。

感谢上面的 Alexander Lobkovsky Meitiv!

© www.soinside.com 2019 - 2024. All rights reserved.