在pandas中连接连续行的简明方法
我想获取一个数据帧并连接连续的行以进行比较 e、 g。 接受 看起来像:在pandas中连接连续行的简明方法,pandas,Pandas,我想获取一个数据帧并连接连续的行以进行比较 e、 g。 接受 看起来像: x y t 0 1.237007 -1.035837 0.0 1 -1.782458 1.042942 1.0 2 0.063130 0.355014 2.0 并作出: a b x y t x
x y t
0 1.237007 -1.035837 0.0
1 -1.782458 1.042942 1.0
2 0.063130 0.355014 2.0
并作出:
a b
x y t x y t
0 1.237007 -1.035837 0.0 -1.782458 1.042942 1.0
1 -1.782458 1.042942 1.0 0.063130 0.355014 2.0
我能想到的最好办法是:
pd.DataFrame(
[np.append(x,y) for (x, y) in zip(xyt.values, xyt[1:].values)],
columns=pd.MultiIndex.from_product([('a', 'b'), xyt.columns]))
有更好的方法吗?让我们用框架在axis=1上试试:
将熊猫作为pd导入
xyt=pd.DataFrame({'x':{0:1.237007,1:-1.782458,2:0.06313},
‘y’:{0:-1.035837,1:1.042942,2:0.355014},
't':{0:0.0,1:1.0,2:2.0})
合并=pd.concat((xyt,xyt.shift(-1)),轴=1,键=('a','b')).iloc[:-1]
打印(合并)
合并
:
a b
x y t x y t
0 1.237007 -1.035837 0.0 -1.782458 1.042942 1.0
1 -1.782458 1.042942 1.0 0.063130 0.355014 2.0
您可以使用
pd.concat
:
#生成随机数据
n=10
x、 y=np.random.randn(2,n)
t=np.arange(n)
xyt=pd.DataFrame({
'x':x,'y':y,'t':t
})
#电话
pd.concat([xyt,xyt.shift(-1)],轴=1,键=['a','b']))
#结果
a b
x y t x y t
0 1.180544 1.707380 0 -0.227370 0.734225 1.0
1 -0.227370 0.734225 1 0.271997 -1.039424 2.0
2 0.271997 -1.039424 2 -0.729960 -1.081224 3.0
3 -0.729960 -1.081224 3 0.185301 0.530126 4.0
4 0.185301 0.530126 4 -0.175333 -0.126157 5.0
5 -0.175333 -0.126157 5 -0.634870 0.068683 6.0
6 -0.634870 0.068683 6 0.350867 0.361564 7.0
7 0.350867 0.361564 7 0.090678 -0.269504 8.0
8 0.090678 -0.269504 8 0.177076 -0.976640 9.0
9 0.177076-0.976640 9楠楠楠楠
a b
x y t x y t
0 1.237007 -1.035837 0.0 -1.782458 1.042942 1.0
1 -1.782458 1.042942 1.0 0.063130 0.355014 2.0