Skip to content
Advertisement

Check column for variable and get value from another column in matched row

How can I get the values of one column in a csv-file by matching attributes in another column?

CSV-file would look like that:

JavaScript

I only want to get the values of column 3, if they have the value “car” in column 2. I also do not want them to be added but rather have them printed in a list, or like that:

JavaScript

My approach is looking like that, but doesn’t really work:

JavaScript

How can I get the exact value for a matched item?

Advertisement

Answer

In one line you can do it like:

JavaScript

Output:

JavaScript

For multiple items try:

JavaScript

Output:

JavaScript

Explanation

  1. df['Two']=='car' returns a Dataframe with boolean True at row positions where value in column Two of of df is car
  2. .values gets these boolean values as a numpy.ndarray, result would be [True False True True]
  3. We can filter the values in column Three by using this list of booleans like so: df['Three'][<Boolean_list>]
  4. To combine the resulting arrays we convert each numpy.ndarray to python list using tolist() and append it to res_list
  5. Then we use sorted to sort res_list
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement