search
Search
Unlock 100+ guides
search toc
close
Outline
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Getting column values based on another column values in a DataFrame in Pandas

schedule Aug 10, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Consider the following DataFrame:

``` import pandas as pddf = pd.DataFrame({"A":[1,2,3,3],"B":[4,5,6,7]})df A B0 1 41 2 52 3 63 3 7 ```

# Solution

To get a column value based on another column value:

``` df.query("A == 3")["B"] 2 63 7Name: B, dtype: int64 ```

Here, we are getting the value of column `B` if the value of column `A` is equal to `3`.

# Explanation

We first fetch the row which has a value of `3` using the `query(~)` method:

``` df.query("A == 3") # returns a DataFrame A B2 3 63 3 7 ```

We then extract the column `B`:

``` df.query("A == 3")["B"] # returns a Series 2 63 7Name: B, dtype: int64 ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!