我有一个Pandas DataFrame。
df = pd.read_excel("data.xlsx")
df
B Price S Price Amount %Change
500 600 100 4
80 300 220 4.2
485 800 315 3.65
59 300 241 4.56
487 1000 513 2.52
187 400 213 2
168 500 332 1.50
185 300 115 1.30
200 134 66 -5.56
100 16 84 -4.44
200 92 108 -4.15
100 44 56 -3
200 145 55 -2.98
102 36 62 -2.50
200 103 97 -2
301 207 94 -2.42
我要应用此条件,如果df [“%Change”]列大于或等于3,则将Result列值设置为Buy, 如果df [“%Change”]列小于或等于-3,则将Result列值设置为Sell, 其余条件将“结果”列的值设置为“在此数据帧上等待”。
if df["%Change"] >= 3:
df["Result"] = "Buy"
elif df["%Change"] <= -3:
df["Result"] = "Sell"
else:
df["Result"] = "Wait"
您能告诉我如何编程吗?
预期输出:
B Price S Price Amount %Change Result
500 600 100 4 Buy
80 300 220 4.2 Buy
485 800 315 3.65 Buy
59 300 241 4.56 Buy
487 1000 513 2.52 Wait
187 400 213 2 Wait
168 500 332 1.50 Wait
185 300 115 1.30 Wait
200 134 66 -5.56 Sell
100 16 84 -4.44 Sell
200 92 108 -4.15 Sell
100 44 56 -3 Sell
200 145 55 -2.98 Wait
102 36 62 -2.50 Wait
200 103 97 -2 Wait
301 207 94 -2.42 Wait
答案 0 :(得分:0)
使用:
import numpy as np
conditions = [(df['%Change'] >= 3), (df['%Change'] <= -3)]
values = ['Buy', 'Sell']
df['result'] = np.select(conditions, values, 'wait')
由于“%Change”列中包含字符串,因此可以使用以下内容:
import numpy as np
conditions = [(df['%Change'].astype(float) >= 3), (df['%Change'].astype(float) <= -3)]
df['result'] = np.select(conditions, ['Buy', 'Sell'], 'wait')
print(df)