簡體   English   中英

列列表中的 Select 值接近 pandas 中的另一個值

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

我有以下數據框:

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    

我想創建另一列Sup存儲一個低於Price的值。 預期結果:

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

這是我一直在嘗試的:

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)

如果差異大於 3%,則說明工作不正確。 請注意, s 列可能會有所不同,所以我想保留np.sort(df.filter(like='S').values, axis=1)

一點幫助將不勝感激。 謝謝!

嘗試這個:

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

也許這可以完成工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM