Skip to content
Merged
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
77 changes: 77 additions & 0 deletions databricks/koalas/indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,83 @@ def symmetric_difference(self, other, result_name=None, sort=None):

return result

# TODO: return_indexer
def sort_values(self, ascending=True):
"""
Return a sorted copy of the index.

.. note:: This method is not supported for pandas when index has NaN value.
pandas raises unexpected TypeError, but we support treating NaN
as the smallest value.

Parameters
----------
ascending : bool, default True
Should the index values be sorted in an ascending order.

Returns
-------
sorted_index : ks.Index or ks.MultiIndex
Sorted copy of the index.

See Also
--------
Series.sort_values : Sort values of a Series.
DataFrame.sort_values : Sort values in a DataFrame.

Examples
--------
>>> idx = ks.Index([10, 100, 1, 1000])
>>> idx
Int64Index([10, 100, 1, 1000], dtype='int64')

Sort values in ascending order (default behavior).

>>> idx.sort_values()
Int64Index([1, 10, 100, 1000], dtype='int64')

Sort values in descending order.

>>> idx.sort_values(ascending=False)
Int64Index([1000, 100, 10, 1], dtype='int64')

Support for MultiIndex.

>>> kidx = ks.MultiIndex.from_tuples([('a', 'x', 1), ('c', 'y', 2), ('b', 'z', 3)])
>>> kidx # doctest: +SKIP
MultiIndex([('a', 'x', 1),
('c', 'y', 2),
('b', 'z', 3)],
)

>>> kidx.sort_values() # doctest: +SKIP
MultiIndex([('a', 'x', 1),
('b', 'z', 3),
('c', 'y', 2)],
)

>>> kidx.sort_values(ascending=False) # doctest: +SKIP
MultiIndex([('c', 'y', 2),
('b', 'z', 3),
('a', 'x', 1)],
)
"""
sdf = self._internal.sdf
sdf = sdf.orderBy(self._internal.index_scols, ascending=ascending)

internal = _InternalFrame(
sdf=sdf.select(self._internal.index_scols),
index_map=self._internal.index_map)

result = DataFrame(internal).index

if isinstance(self, MultiIndex):
result.names = self.names
else:
result.name = self.name
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we need this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

without this, i think we can't keep names when below case.

>>> kidx = ks.MultiIndex.from_tuples([('a', 'x', 1), ('c', 'y', 2), ('b', 'z', 3)])
>>> kidx.names = ['A', 'B', 'C']
>>> kidx.sort_values()
MultiIndex([('a', 'x', 1),
            ('b', 'z', 3),
            ('c', 'y', 2)],
           )

Copy link
Collaborator

Choose a reason for hiding this comment

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

ah, I see. @names.setter seems wrong.

Copy link
Contributor Author

@itholic itholic Dec 13, 2019

Choose a reason for hiding this comment

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

ah, i got it.

in @names.setter, the new index_map is overwritten to self._kdf._internal, not to self._internal.

like below

self._kdf._internal = internal.copy(index_map=list(zip(internal.index_columns, names)))

at this point, i curious why we overwrite self._kdf._internal rather than simply self._internal?

For now, i've fixed it to the current implementation


return result

def __getattr__(self, item: str) -> Any:
if hasattr(_MissingPandasLikeIndex, item):
property_or_func = getattr(_MissingPandasLikeIndex, item)
Expand Down
2 changes: 0 additions & 2 deletions databricks/koalas/missing/indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ class _MissingPandasLikeIndex(object):
slice_indexer = unsupported_function('slice_indexer')
slice_locs = unsupported_function('slice_locs')
sort = unsupported_function('sort')
sort_values = unsupported_function('sort_values')
sortlevel = unsupported_function('sortlevel')
take = unsupported_function('take')
to_flat_index = unsupported_function('to_flat_index')
Expand Down Expand Up @@ -183,7 +182,6 @@ class _MissingPandasLikeMultiIndex(object):
slice_indexer = unsupported_function('slice_indexer')
slice_locs = unsupported_function('slice_locs')
sort = unsupported_function('sort')
sort_values = unsupported_function('sort_values')
sortlevel = unsupported_function('sortlevel')
swaplevel = unsupported_function('swaplevel')
take = unsupported_function('take')
Expand Down
22 changes: 22 additions & 0 deletions databricks/koalas/tests/test_indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,3 +334,25 @@ def test_index_fillna(self):

with self.assertRaisesRegex(TypeError, "Unsupported type <class 'list'>"):
kidx.fillna([1, 2])

def test_sort_values(self):
pidx = pd.Index([-10, -100, 200, 100])
kidx = ks.Index([-10, -100, 200, 100])

self.assert_eq(pidx.sort_values(), kidx.sort_values())
self.assert_eq(pidx.sort_values(ascending=False), kidx.sort_values(ascending=False))

pidx.name = 'koalas'
kidx.name = 'koalas'

self.assert_eq(pidx.sort_values(), kidx.sort_values())
self.assert_eq(pidx.sort_values(ascending=False), kidx.sort_values(ascending=False))

pidx = pd.MultiIndex.from_tuples([('a', 'x', 1), ('b', 'y', 2), ('c', 'z', 3)])
kidx = ks.MultiIndex.from_tuples([('a', 'x', 1), ('b', 'y', 2), ('c', 'z', 3)])

pidx.names = ['hello', 'koalas', 'goodbye']
kidx.names = ['hello', 'koalas', 'goodbye']

self.assert_eq(pidx.sort_values(), kidx.sort_values())
self.assert_eq(pidx.sort_values(ascending=False), kidx.sort_values(ascending=False))
9 changes: 8 additions & 1 deletion docs/source/reference/indexing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ Conversion
Index.to_series
Index.to_numpy

.. _api.multiindex:
Sorting
~~~~~~~
.. autosummary::
:toctree: api/

Index.sort_values

Combining / joining / set operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand All @@ -77,6 +82,8 @@ Selecting

Index.isin

.. _api.multiindex:

MultiIndex
----------
.. autosummary::
Expand Down