Skip to content

Fix first_valid_index/last_valid_index on DataFrame of all None/NaN values #17646

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
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
21 changes: 18 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4070,7 +4070,15 @@ def first_valid_index(self):
if len(self) == 0:
return None

return self.index[self.count(1) > 0][0]
try:
return self.index[self.count(1) > 0][0]
except IndexError:
# Ensures same behavior as a Series of all Null values.
mask = isna(self._values)
if all(mask):
return None

raise

def last_valid_index(self):
"""
Expand All @@ -4079,8 +4087,15 @@ def last_valid_index(self):
if len(self) == 0:
return None

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

try:
return self.index[self.count(1) > 0][-1]
except IndexError:
# Ensures same behavior as a Series of all Null values.
mask = isna(self._values)
if all(mask):
return None

raise
# ----------------------------------------------------------------------
# Data reshaping

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 @@ -440,6 +440,11 @@ def test_first_last_valid(self):
assert empty.last_valid_index() is None
assert empty.first_valid_index() is None

# GH17400
allnulls = DataFrame({'a': [np.nan, np.nan]})
assert allnulls.first_valid_index() is None
assert allnulls.last_valid_index() is None

def test_at_time_frame(self):
rng = date_range('1/1/2000', '1/5/2000', freq='5min')
ts = DataFrame(np.random.randn(len(rng), 2), index=rng)
Expand Down