aberger aberger - 1 year ago 81
Python Question

Pandas: Get corresponding column value in row based on unique value

I've figured out how to get the information I want, but I would be surprised if there is not a better, more readable way to do so.

I want to get the value in a different column in the row that holds the data element I specify. For example, what is the value in 'b' that corresponds to the value of 10 in 'a'.

>>> df
a b c
0 10 20 30
1 11 21 31
2 12 22 32

>>> df['b'][df[df['a'] == 11].index.tolist()].tolist()

This is how I currently solved it, but in practice my dataframes are not named so concisely and I have long strings as column names so the line gets hard to read.

EDIT: If the value in 'a' is not unique is there also a way to get all corresponding values in 'b'?

Answer Source

You can use a boolean mask with loc to return all rows where the boolean condition is met, here we mask the df with the condition where 'a' == 11, and where this is met return all values for 'b':

In [120]:
df = pd.DataFrame({'a':[10,11,11],'b':np.arange(3), 'c':np.random.randn(3)})

    a  b         c
0  10  0 -1.572926
1  11  1 -0.639703
2  11  2 -1.282575

In [121]:
df.loc[df['a'] == 11,'b']

1    1
2    2
Name: b, dtype: int32
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download