From 13f1022edec4ccbb6266204519c5acf73971a39e Mon Sep 17 00:00:00 2001 From: lexual Date: Sat, 19 Jul 2014 10:01:32 +1000 Subject: [PATCH] dropna method added to Index. ref pydata/pandas#6194 ref pydata/pandas#7784 --- pandas/core/index.py | 10 ++++++++++ pandas/tests/test_index.py | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/pandas/core/index.py b/pandas/core/index.py index 6927d5a732440..98fafe41ced1b 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -215,6 +215,16 @@ def is_(self, other): # use something other than None to be clearer return self._id is getattr(other, '_id', Ellipsis) + def dropna(self): + """ + Return Index without null values + + Returns + ------- + dropped : Index + """ + return self[~isnull(self.values)] + def _reset_identity(self): """Initializes or resets ``_id`` attribute with new object""" self._id = _Identity() diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index a8486beb57042..7ebbac4541c8e 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -905,6 +905,13 @@ def test_nan_first_take_datetime(self): exp = Index([idx[-1], idx[0], idx[1]]) tm.assert_index_equal(res, exp) + def test_dropna(self): + idx = Index([np.nan, 'a', np.nan, np.nan, 'b', 'c', np.nan], + name='idx') + expected = Index(['a', 'b', 'c'], name='idx') + result = idx.dropna() + tm.assert_index_equal(result, expected) + class TestFloat64Index(tm.TestCase): _multiprocess_can_split_ = True @@ -1049,6 +1056,13 @@ def test_astype_from_object(self): tm.assert_equal(result.dtype, expected.dtype) tm.assert_index_equal(result, expected) + def test_dropna(self): + idx = Index([np.nan, 1.0, np.nan, np.nan, 2.0, 3.0, np.nan], + name='idx') + expected = Index([1.0, 2.0, 3.0], name='idx') + result = idx.dropna() + tm.assert_index_equal(result, expected) + class TestInt64Index(tm.TestCase): _multiprocess_can_split_ = True @@ -1474,6 +1488,12 @@ def test_slice_keep_name(self): idx = Int64Index([1, 2], name='asdf') self.assertEqual(idx.name, idx[1:].name) + def test_dropna_does_nothing(self): + idx = Index([1, 2, 3], name='idx') + expected = Index([1, 2, 3], name='idx') + result = idx.dropna() + tm.assert_index_equal(result, expected) + class TestMultiIndex(tm.TestCase): _multiprocess_can_split_ = True @@ -2824,6 +2844,12 @@ def test_level_setting_resets_attributes(self): # if this fails, probably didn't reset the cache correctly. assert not ind.is_monotonic + def test_dropna_does_nothing(self): + idx = MultiIndex.from_tuples([('bar', 'two')]) + expected = idx + result = idx.dropna() + tm.assert_index_equal(result, expected) + def test_get_combined_index(): from pandas.core.index import _get_combined_index