Agapic
Agapic

Reputation: 13

extract the value of a column based on corresponding two other columns in pandas

I tried

print(df.loc[df['A'] == 'A value', 'B'].item())

Which returns the value of B corresponding to A value.

But what if I wanted to do something like this:

print(df.loc[df['A'] == 'B' & df['C'] == 'C Value', 'Grade'].item())

I want the returned value to be a normal string without brackets.

Upvotes: 0

Views: 2268

Answers (1)

Zero
Zero

Reputation: 1899

Suppose I have dataframe which looks like this,

A B C D
0 0 0 1 0
1 1 0 0 0
2 1 1 0 0

And I want to get the value of column D for all rows who have equal column A and B values and whose column C value is equal to 1, I can do this,

df.loc[(df["A"] == df["B"]) & (df["C"] == 1), "D"]

Upvotes: 1

Related Questions