简体   繁体   中英

Select value from a list of columns that is close to another value in pandas

I have the following data frame:

S0  S1  S2  S3  S4  S5... Price
10  15  18  12  18  19     16
55  45  44  66  58  45     64
77  84  62  11  61  44     20    

I want to create another column Sup which stores one value lower than the Price . Intended result:

S0  S1  S2  S3  S4  S5... Price  Sup
10  15  18  12  18  19     16    15
55  45  44  66  58  45     64    58
77  84  62  11  61  44     20    11

Here's what I have been trying:

s = np.sort(df.filter(like='S').values, axis=1)
mask = (s*1.03) > df['Close'].values[:,None]
df['Sup'] = np.where(mask.any(1), s[np.arange(s.shape[0]),mask.argmax(1)], 0)

If the difference is greater than 3% it doesn't do the job right. Note that the s columns may vary so I would want to keep the np.sort(df.filter(like='S').values, axis=1)

Little help will be appreciated. THANKS!

Try this:

s = df.filter(like='S')

# compare to the price
mask = s.lt(df['Price'], axis=0)

# `where(mask)` places `NaN` where mask==False
# `max(1)` takes maximum along rows, ignoring `NaN`
# rows with all `NaN` returns `NaN` after `max`, 
# `fillna(0)` fills those with 0
df['Price'] = s.where(mask).max(1).fillna(0)

Output:

   S0  S1  S2  S3  S4  S5  Price
0  10  15  18  12  18  19   15.0
1  55  45  44  66  58  45   58.0
2  77  84  62  11  61  44   11.0

Maybe this would get the job done:

p = df['Price']
m = df.filter(like='S').lt(p, axis=0)
df['Sup'] = df[m].max(axis=1).astype(int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM