How to refer to previous row with itertuples()

I’ve imported a CSV file using pandas. It has 2 columns: a date and a payment amount. I’d like to iterate through it and calculate the elapse time between rows. But when I use for row in pymtdata.itertuples(): I can’t figure out how to access values in the previous row. Any suggestions?

The first element of the tuple is the index. If you can figure out the previous row from that value (i.e. if they’re sequential) you can retrieve said row that way.

Alternatively, you could wrap your iterator with enumerate and then you’d have a sequential index alongside your tuple.

As a final option: pandas can compute this kind of thing. If it has parsed your dates properly, it should be possible to compute the row-to-row difference with the diff method.

As @jamestwebber noted, the .diff method will already compute a difference for you. For slightly more general needs, there is also a .shift method on Series that you can use to create a shifted version of a column, where the value in the shifted column at row n is the value in original column at row n-1 (or n+1, or actually you can shift by any offset) . This can be used to create a new column that is a shifted version of an existing column, effectively allowing you to use ordinary operations on a single row that take account of values in the next/previous row.

1 Like