Python – Get a value through a column index, where a row is a specific value

Get a value through a column index, where a row is a specific value… here is a solution to the problem.

Get a value through a column index, where a row is a specific value

I have a data frame sheet_overview:

    Unnamed: 0 Headline Unnamed: 2 Unnamed: 3
  0         nan    1. 1.   username       Erik
  1         nan    1. 2.    userage         23
  2         nan    1. 3.   favorite        ice

I would like to do this by looking up “1. 2. ” to get the value 23.
If I don’t want to go into column names, I have to use an index. My question is, if my approach is too complicated.

It works, but it seems too much and not very pythonic:

age = sheet_overview.iloc[
                    sheet_overview[
                        sheet_overview.iloc[:, 1] == '1. 2.']
                        .index[0], 3]

Solution

Add values for values with numpy array of filters for iloc is then used next returns the first matching value – get missing: if it doesn’t exist

a = sheet_overview.iloc[(sheet_overview.iloc[:, 1] == '1. 2.').values, 3]

a = next(iter(a), 'missing')
print (a)
23

If performance is important, use numba:

from numba import njit

@njit
def first_val(A, k):
    a = A[:, 0]
    b = A[:, 1]
    for i in range(len(a)):
        if a[i] == k:
            return b[i]
    return 'missing'

a = first_val(sheet_overview.iloc[:, [1,3]].values, '1. 2.')

Related Problems and Solutions