如果满足某些条件,我想在当前存储在(第1行)的第二天打开价格并将其存储在新列中.
df['b']='' df['shift']='' df['shift']=df['open'].shift(-1) df['b']=df[x for x in df['shift'] if df["MA10"]>df["MA100"]]
解决方法
有几种方法.使用申请:
>>> df = pd.read_csv("bondstack.csv") >>> df["shift"] = df["open"].shift(-1) >>> df["b"] = df.apply(lambda row: row["shift"] if row["MA10"] > row["MA100"] else np.nan,axis=1)
哪个产生
>>> df[["MA10","MA100","shift","b"]][:10] MA10 MA100 shift b 0 16.915625 17.405625 16.734375 NaN 1 16.871875 17.358750 17.171875 NaN 2 16.893750 17.317187 17.359375 NaN 3 16.950000 17.279062 17.359375 NaN 4 17.137500 17.254062 18.640625 NaN 5 17.365625 17.229063 18.921875 18.921875 6 17.550000 17.200312 18.296875 18.296875 7 17.681250 17.177500 18.640625 18.640625 8 17.812500 17.159375 18.609375 18.609375 9 17.943750 17.142813 18.234375 18.234375
对于更加矢量化的方法,您可以使用
>>> df = pd.read_csv("bondstack.csv") >>> df["b"] = np.nan >>> df["b"][df["MA10"] > df["MA100"]] = df["open"].shift(-1)
或者我的首选方法:
>>> df = pd.read_csv("bondstack.csv") >>> df["b"] = df["open"].shift(-1).where(df["MA10"] > df["MA100"])