4

I have the following dataframe:

import pandas as pd
import numpy as np
data = {
    "index": [1, 2, 3, 4, 5],
    "A": [11, 17, 5, 9, 10],
    "B": [8, 6, 16, 17, 9],
    "C": [10, 17, 12, 13, 15],
    "target": [12, 13, 8, 6, 12]
}
df = pd.DataFrame.from_dict(data)
print(df)

I would like to find nearest values for column target in column A, B and C, and put those values into column result. As far as I know, I need to use abs() and argmin() function. Here is the output I expected:

     index   A      B     C    target  result
0      1     11     8    10      12      11
1      2     17     6    17      13      17
2      3     5     16    12       8       5
3      4     9     17    13       6       9
4      5     10     9    15      12      10

Here is the solution and links what i have found from stackoverflow which may help:

(df.assign(closest=df.apply(lambda x: x.abs().argmin(), axis='columns'))
 .apply(lambda x: x[x['target']], axis='columns'))

Identifying closest value in a column for each filter using Pandas https://codereview.stackexchange.com/questions/204549/lookup-closest-value-in-pandas-dataframe

cs95
  • 379,657
  • 97
  • 704
  • 746
ah bon
  • 9,293
  • 12
  • 65
  • 148

2 Answers2

5

Subtract "target" from the other columns, use idxmin to get the column of the minimum difference, followed by a lookup:

idx = df.drop(['index', 'target'], 1).sub(df.target, axis=0).abs().idxmin(1)
df['result'] = df.lookup(df.index, idx)
df
   index   A   B   C  target  result
0      1  11   8  10      12      11
1      2  17   6  17      13      17
2      3   5  16  12       8       5
3      4   9  17  13       6       9
4      5  10   9  15      12      10

General solution handling string columns and NaNs (along with your requirement of replacing NaN values in target with value in "v1"):

df2 = df.select_dtypes(include=[np.number])
idx = df2.drop(['index', 'target'], 1).sub(df2.target, axis=0).abs().idxmin(1)
df['result'] = df2.lookup(df2.index, idx.fillna('v1'))

You can also index into the underlying NumPy array by getting integer indices using df.columns.get_indexer.

# idx = df[['A', 'B', 'C']].sub(df.target, axis=0).abs().idxmin(1)
idx = df.drop(['index', 'target'], 1).sub(df.target, axis=0).abs().idxmin(1)
# df['result'] = df.values[np.arange(len(df)), df.columns.get_indexer(idx)]
df['result'] = df.values[df.index, df.columns.get_indexer(idx)]

df
   index   A   B   C  target  result
0      1  11   8  10      12      11
1      2  17   6  17      13      17
2      3   5  16  12       8       5
3      4   9  17  13       6       9
4      5  10   9  15      12      10
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thanks for your help. But i get following ValueError: ValueError: operands could not be broadcast together with shapes (25,) (5,) . Maybe because there are NaNs in columns A, B and C. – ah bon Dec 29 '18 at 13:26
  • @ahbon which line? NaNs won't make a difference here. – cs95 Dec 29 '18 at 13:27
  • @ahbon Not particular about whose answer is accepted, but does this mean you got it to work? – cs95 Dec 29 '18 at 13:31
  • Sorry, my real data have some columns which are not numbers. Does this cause the ValueError? – ah bon Dec 29 '18 at 13:32
  • 1
    @ahbon Yeah, likely. Try this: `df2 = df.select_dtypes(include=[np.number])` and try my code with `df2` (make sure to drop "index" and "target" from `df2` as appropriate). – cs95 Dec 29 '18 at 13:32
  • I have added df2 as my example dataframe. May i ask if there are NaNs in target column, at that case, I hope it returns value in v1, what i should do? Thanks. – ah bon Dec 29 '18 at 13:49
5

You can use NumPy positional integer indexing with argmin:

col_lst = list('ABC')
col_indices = df[col_lst].sub(df['target'], axis=0).abs().values.argmin(1)
df['result'] = df[col_lst].values[np.arange(len(df.index)), col_indices]

Or you can lookup column labels with idxmin:

col_labels = df[list('ABC')].sub(df['target'], axis=0).abs().idxmin(1)
df['result'] = df.lookup(df.index, col_labels)

print(df)

   index   A   B   C  target  result
0      1  11   8  10      12      11
1      2  17   6  17      13      17
2      3   5  16  12       8       5
3      4   9  17  13       6       9
4      5  10   9  15      12      10

The principle is the same, though for larger dataframes you may find NumPy more efficient:

# Python 3.7, NumPy 1.14.3, Pandas 0.23.0

def np_lookup(df):
    col_indices = df[list('ABC')].sub(df['target'], axis=0).abs().values.argmin(1)
    df['result'] = df[list('ABC')].values[np.arange(len(df.index)), col_indices]
    return df

def pd_lookup(df):
    col_labels = df[list('ABC')].sub(df['target'], axis=0).abs().idxmin(1)
    df['result'] = df.lookup(df.index, col_labels)
    return df

df = pd.concat([df]*10**4, ignore_index=True)

assert df.pipe(pd_lookup).equals(df.pipe(np_lookup))

%timeit df.pipe(np_lookup)  # 7.09 ms
%timeit df.pipe(pd_lookup)  # 67.8 ms
jpp
  • 159,742
  • 34
  • 281
  • 339