How can I check last row in Python pandas df.itterows() during its iteration?
My code :
for index, row in df.iterrows():
... # I want to check last row in df iterrows(). somelike row[0].tail(1)
Pandas DataFrame iterrows() Method The iterrows() method generates an iterator object of the DataFrame, allowing us to iterate each row in the DataFrame. Each iteration produces an index object and a row object (a Pandas Series object).
Select & print last row of dataframe using tail() It will return the last row of dataframe as a dataframe object. Using the tail() function, we fetched the last row of dataframe as a dataframe and then just printed it.
iterrows() function in Python. Pandas DataFrame. iterrows() is used to iterate over a pandas Data frame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in form of series.
itertuples() takes 16 seconds to iterate through a data frame with 10 million records that are around 50x times faster than iterrows().
Use
for i, (index, row) in enumerate(df.iterrows()):
if i == len(df) - 1:
pass
The pandas.DataFrame class has a subscriptable index
attribute. So one can check the index of the row when iterating over the row using iterrows()
against the last value of the df.index attribute like so:
for idx,row in df.iterrows():
if idx == df.index[-1]:
print('This row is last')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With