3

I am reading a CSV file in Pandas. Suppose the CSV is as follows:

column_1,column_2,column_3
1,2,value_1
1,3,value_2
2,1,value_3
2,2,value_4

I want to get the value from column_3 (i.e. value_2) where column_1=1 and column_2=3. I am certain that there will only be 1 row that matches this condition.

So I am doing something like this:

df = pd.read_csv(...file...)
cond = (df['column_1'] == 1) & (df['column_2'] == 3)
...

I tried the df.loc[cond, 'column_3'] to give me the value, however it returns a dataframe with the index as the row number of this row. The row number here is not 0, but 1 (i.e. original row number in the CSV file), which does not let me do a df.loc[cond, 'column_3'][0]

How do I get the column value here?

user2684198
  • 812
  • 1
  • 10
  • 18

1 Answers1

7

This should work:

import pandas as pd

data = {
    'column_1': [1, 1, 2, 2],
    'column_2': [2, 3, 1, 2],
    'column_3': ['value_1', 'value_2', 'value_3', 'value_4']
}

df = pd.DataFrame(data=data)

cond = (df['column_1'] == 1) & (df['column_2'] == 3)
result = df[cond].column_3.values[0]
result
Carlos Azevedo
  • 660
  • 3
  • 13