Skip to content

Improve lookup documentation #61471

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
32 changes: 24 additions & 8 deletions doc/source/user_guide/indexing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1461,16 +1461,32 @@ Looking up values by index/column labels

Sometimes you want to extract a set of values given a sequence of row labels
and column labels, this can be achieved by ``pandas.factorize`` and NumPy indexing.
For instance:

.. ipython:: python
For heterogeneous column types, we subset columns to avoid unnecessary numpy conversions:
Copy link
Member

Choose a reason for hiding this comment

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

NumPy again.


.. code-block:: python

def pd_lookup_het(df, row_labels, col_labels):
rows = df.index.get_indexer(row_labels)
cols = df.columns.get_indexer(col_labels)
sub = df.take(np.unique(cols), axis=1)
sub = sub.take(np.unique(rows), axis=0)
rows = sub.index.get_indexer(row_labels)
values = sub.melt()["value"]
cols = sub.columns.get_indexer(col_labels)
flat_index = rows + cols * len(sub)
result = values[flat_index]
return result

For homogeneous column types, it is fastest to skip column subsetting and go directly to numpy:
Copy link
Member

Choose a reason for hiding this comment

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

Nit: NumPy


.. code-block:: python

df = pd.DataFrame({'col': ["A", "A", "B", "B"],
'A': [80, 23, np.nan, 22],
'B': [80, 55, 76, 67]})
df
idx, cols = pd.factorize(df['col'])
df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)), idx]
def pd_lookup_hom(df, row_labels, col_labels):
rows = df.index.get_indexer(row_labels)
Copy link
Member

Choose a reason for hiding this comment

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

Can you add df = df.loc[:, sorted(set(col_labels))] here.

cols = df.columns.get_indexer(col_labels)
result = df.to_numpy()[rows, cols]
return result

Formerly this could be achieved with the dedicated ``DataFrame.lookup`` method
which was deprecated in version 1.2.0 and removed in version 2.0.0.
Expand Down
Loading