2

Assuming I have a DataFrame:

import pandas as pd
df = pd.DataFrame([["house", "red"], ["car", "blue"]], columns=["item", "colour"])

What is the idiomatic way to return a single row, or raise an exception if exactly one row is not found, using DataFrame.loc:

match = df.loc[df["colour"] == "red"]]
# I know there is exactly one row in the resulting DataFrame
# TODO: How to make match to return a single row as pd.Series

This would be similar to SQLAlchemy's Query.one()

1 Answer 1

2

You can squeeze and assert that the output is a Series (or use a test if you don't want to raise an exception):

match = df.loc[df["colour"] == "red"].squeeze()

assert isinstance(match, pd.Series)

alternative to assert:

if isinstance(match, pd.Series):
    # do something
else:
    # do something else
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.