Home > Mobile >  Return match in a one-to-one table (pandas)
Return match in a one-to-one table (pandas)

Time:01-03

Suppose I have a df where I am sure the results are one-to-one like

State Abbr
Alaska AK
Alabama AL
Arkansas AR

How can I simply return one column given the other, as a string? So given 'Alaska', return 'AK'.

I tried

df['abbr'].where(df['state'] == 'Alaska')

But it just returns a Series. Do I need to just convert it to a dict or is there some simple solution I'm missing?

CodePudding user response:

You can use the .loc indexer to select the element in the 'Abbr' column that is in the same row as the value 'Alaska' in the 'State' column.

df.loc[df['State'] == 'Alaska', 'Abbr']

This will return a Pandas series with a single element, which you can access using .values[0] if you want to get the value as a string:

df.loc[df['State'] == 'Alaska', 'Abbr'].values[0]

Alternatively, you can use the .at indexer to directly access the value at the specified row and column:

df.at[df['State'] == 'Alaska', 'Abbr']

This will return the value as a string.

Note that both of these methods assume that there is only one row that matches the condition df['State'] == 'Alaska', which is the case in a one-to-one table. If there are multiple rows that match the condition, these methods will return a series with multiple elements, or an error will be raised if you use .at.

CodePudding user response:

There many ways to achieve this:

result_1 = df.query("State.eq('Alaska')")["Abbr"].squeeze()

result_2 = df.set_index("State").at["Alaska", "Abbr"]

result_3 = df[df["State"] == "Alaska"]["Abbr"].squeeze()
  • Related