Repository: pandas-dev/pandas

Issue:
Problem with nlargest / nsmallest on dataframes with MultiIndex columns
#### The Problem
The `nlargest` / `nsmallest` functionality is broken when applied to dataframes with `MultiIndex` columns. For example:

```python
columns = pd.MultiIndex.from_tuples([('x', 'a'), ('x', 'b'), ('y', 'c'), ('y', 'd')])
values = np.random.rand(5, 4)
df = pd.DataFrame(data=values, columns=columns)
df.nlargest(3, ('x', 'a'))
```

This raises an error because the multi-level lookup `('x', 'a')` is interpreted as a list of column names `['x', 'a']`.

This is a problem, because this behavior is inconsistent with the usual multi-level lookup behavior.



#### Output of ``pd.show_versions()``

<details>
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.6.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 142 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.23.4
pytest: None
pip: 10.0.1
setuptools: 39.0.1
Cython: None
numpy: 1.14.5
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 6.5.0
sphinx: None
patsy: None
dateutil: 2.7.3
pytz: 2018.5
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 3.0.0
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: 1.0.1
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None


</details>



Discussion:

Resolving patch:
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1161,7 +1161,7 @@ class SelectNFrame(SelectN):
 
     def __init__(self, obj, n, keep, columns):
         super(SelectNFrame, self).__init__(obj, n, keep)
-        if not is_list_like(columns):
+        if not is_list_like(columns) or isinstance(columns, tuple):
             columns = [columns]
         columns = list(columns)
         self.columns = columns


Test patch:
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py
--- a/pandas/tests/frame/test_analytics.py
+++ b/pandas/tests/frame/test_analytics.py
@@ -2153,7 +2153,7 @@ def test_n(self, df_strings, nselect_method, n, order):
             tm.assert_frame_equal(result, expected)
 
     @pytest.mark.parametrize('columns', [
-        ('group', 'category_string'), ('group', 'string')])
+        ['group', 'category_string'], ['group', 'string']])
     def test_n_error(self, df_main_dtypes, nselect_method, columns):
         df = df_main_dtypes
         col = columns[1]
@@ -2259,3 +2259,20 @@ def test_series_nat_conversion(self):
         df.rank()
         result = df
         tm.assert_frame_equal(result, expected)
+
+    def test_multiindex_column_lookup(self):
+        # Check whether tuples are correctly treated as multi-level lookups.
+        # GH 23033
+        df = pd.DataFrame(
+            columns=pd.MultiIndex.from_product([['x'], ['a', 'b']]),
+            data=[[0.33, 0.13], [0.86, 0.25], [0.25, 0.70], [0.85, 0.91]])
+
+        # nsmallest
+        result = df.nsmallest(3, ('x', 'a'))
+        expected = df.iloc[[2, 0, 3]]
+        tm.assert_frame_equal(result, expected)
+
+        # nlargest
+        result = df.nlargest(3, ('x', 'b'))
+        expected = df.iloc[[3, 2, 1]]
+        tm.assert_frame_equal(result, expected)