Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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 column b that corresponds to the value of 11 in column 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()
[21]

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'?

like image 445
aberger Avatar asked Oct 14 '16 15:10

aberger


2 Answers

You can use loc to return all the rows where the condition is met. This code will give you the exact value that corresponds to that row where a condition is met.

result=df.loc[df['a'] == 11,'b'].values[0]
print(result)
like image 69
Rishabh Gupta Avatar answered Nov 08 '22 16:11

Rishabh Gupta


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)})
df

Out[120]:
    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']

Out[121]:
1    1
2    2
Name: b, dtype: int32
like image 42
EdChum Avatar answered Nov 08 '22 16:11

EdChum