Skip to content

BUG 12800 fixed inconsistent behavior of last_valid_index and first_valid_index #12834

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3766,12 +3766,18 @@ def first_valid_index(self):
"""
Return label for first non-NA/null value
"""
if len(self) == 0:
return None

return self.index[self.count(1) > 0][0]

def last_valid_index(self):
"""
Return label for last non-NA/null value
"""
if len(self) == 0:
return None

return self.index[self.count(1) > 0][-1]

# ----------------------------------------------------------------------
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/frame/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,3 +336,8 @@ def test_first_last_valid(self):

index = frame.last_valid_index()
self.assertEqual(index, frame.index[-6])

def test_empty_first_last(self):
empty_frame = DataFrame()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add the issue number as a comment (and below)

self.assertIsNone(empty_frame.last_valid_index())
self.assertIsNone(empty_frame.first_valid_index())
5 changes: 5 additions & 0 deletions pandas/tests/series/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -617,3 +617,8 @@ def test_timeseries_coercion(self):
self.assertTrue(ser.is_time_series)
self.assertTrue(ser.index.is_all_dates)
self.assertIsInstance(ser.index, DatetimeIndex)

def test_empty_first_last(self):
empty_frame = Series()
self.assertIsNone(empty_frame.last_valid_index())
self.assertIsNone(empty_frame.first_valid_index())