我创建了2个熊猫数据框,第一个名为'dfmas',索引为'Date',然后是日期,数据和3个移动平均列;
OPEN HIGH LOW LAST ma5 ma8 ma21
Date
11/23/2009 88.84 89.19 88.58 88.97 NaN NaN NaN
11/24/2009 88.97 89.07 88.36 88.50 NaN NaN NaN
11/25/2009 88.50 88.63 87.22 87.35 NaN NaN NaN
11/26/2009 87.35 87.48 86.30 86.59 NaN NaN NaN
11/27/2009 86.59 87.02 84.83 86.53 87.588 NaN NaN
11/30/2009 87.17 87.17 85.87 86.41 87.076 NaN NaN
12/1/2009 86.41 87.53 86.17 86.68 86.712 NaN NaN
12/2/2009 86.68 87.49 86.59 87.39 86.720 87.302 NaN
12/3/2009 87.39 88.48 87.32 88.26 87.054 87.214 NaN
12/4/2009 88.26 90.77 88.00 90.56 87.860 87.471 NaN
第二个数据帧是根据以上数据查看移动平均线何时交叉;
ma = [0,]
ma5Last = ma5[0]
ma8Last = ma8[0]
for ma5Curr, ma8Curr in zip(ma5[1:], ma8[1:]):
if ma5Curr > ma5Last and ma8Curr > ma8Last:
ma.append(1)
elif ma5Curr < ma5Last and ma8Curr < ma8Last:
ma.append(-1)
else:
ma.append(0)
ma5Last = ma5Curr
ma8Last = ma8Curr
maX = pd.DataFrame(ma).astype('float')
maX.columns = ['maX']
并在下面被称为'maX';
maX
0 0.0
1 0.0
2 0.0
3 0.0
4 0.0
5 0.0
6 0.0
7 0.0
8 0.0
9 1.0
但是我无法合并/连接2个数据帧。 如何将“日期”索引添加到第二个'maX'dataframe,然后合并/连接/合并两个数据帧?非常感谢提前。
答案 0 :(得分:1)
如果数据框的长度相同,只需在原始index
中添加DataFrame
以便对齐索引:
maX = pd.DataFrame(ma, index=df.index).astype('float')
答案 1 :(得分:1)
这就是你追求的吗?
df['maX'] = maX.maX.values
df
Out[1263]:
OPEN HIGH LOW LAST ma5 ma8 ma21 maX
Date
11/23/2009 88.84 89.19 88.58 88.97 NaN NaN NaN 0.0
11/24/2009 88.97 89.07 88.36 88.50 NaN NaN NaN 0.0
11/25/2009 88.50 88.63 87.22 87.35 NaN NaN NaN 0.0
11/26/2009 87.35 87.48 86.30 86.59 NaN NaN NaN 0.0
11/27/2009 86.59 87.02 84.83 86.53 87.588 NaN NaN 0.0
11/30/2009 87.17 87.17 85.87 86.41 87.076 NaN NaN 0.0
12/1/2009 86.41 87.53 86.17 86.68 86.712 NaN NaN 0.0
12/2/2009 86.68 87.49 86.59 87.39 86.720 87.302 NaN 0.0
12/3/2009 87.39 88.48 87.32 88.26 87.054 87.214 NaN 0.0
12/4/2009 88.26 90.77 88.00 90.56 87.860 87.471 NaN 1.0