Python 将三维熊猫数据帧转换为Numpy ndarray
我有一个像这样的数据帧Python 将三维熊猫数据帧转换为Numpy ndarray,python,pandas,numpy,Python,Pandas,Numpy,我有一个像这样的数据帧 xs = pd.DataFrame({ 'batch1': { 'timestep1': [1, 2, 3], 'timestep2': [3, 2, 1] } }).T 我想把它转换成一个形状的numpy数组(批处理、时间步、特征)。对于xs,应为(1,2,3) 问题是熊猫只知道2D形状,所以to_numpy生成2D形状 xs.to_numpy().shape # (1, 2) 类似地,这会阻止使用np.refor
xs = pd.DataFrame({
'batch1': {
'timestep1': [1, 2, 3],
'timestep2': [3, 2, 1]
}
}).T
我想把它转换成一个形状的numpy数组(批处理、时间步、特征)。对于xs
,应为(1,2,3)
问题是熊猫只知道2D形状,所以to_numpy
生成2D形状
xs.to_numpy().shape # (1, 2)
类似地,这会阻止使用np.reformate
,因为numpy似乎不会将最里面的维度视为数组
xs.to_numpy().reshape((1,2,3)) # ValueError: cannot reshape array of size 2 into shape (1,2,3)
[编辑]添加数据帧如何到达此状态的上下文
数据帧最初以
xs = pd.DataFrame({
('batch1','timestep1'): {
'feature1': 1,
'feature2': 2,
'feature3': 3
},
('batch1', 'timestep2'): {
'feature1': 3,
'feature2': 2,
'feature3': 1
}
}
).T
我使用
xs.apply(pd.DataFrame.to_numpy, axis=1).unstack()
输出:
timestep1 timestep2
batch1 1 3
batch1 2 2
batch1 3 1
[[[1 3 2]
[2 3 1]]]
[[[1 2 3]
[3 2 1]]
[[4 5 6]
[7 8 9]]]
编辑
从原始数据帧开始,您可以执行以下操作:
xs = pd.DataFrame({
('batch1','timestep1'): {
'feature1': 1,
'feature2': 2,
'feature3': 3
},
('batch1', 'timestep2'): {
'feature1': 3,
'feature2': 2,
'feature3': 1
},
('batch2','timestep1'): {
'feature1': 4,
'feature2': 5,
'feature3': 6
},
('batch2', 'timestep2'): {
'feature1': 7,
'feature2': 8,
'feature3': 9
}
}
).T
array = xs.to_numpy().reshape(2,2,3)
print(array)
输出:
timestep1 timestep2
batch1 1 3
batch1 2 2
batch1 3 1
[[[1 3 2]
[2 3 1]]]
[[[1 2 3]
[3 2 1]]
[[4 5 6]
[7 8 9]]]
你看过numpy生产什么了吗?(不仅仅是它的形状)是的。它通常会生成正确的形状,即
xs.to_numpy().shape#(1,2)
,如果检查最里面的尺寸,可以看到正确的长度:xs.to_numpy()[0][0]。shape#(3,2)
。我想,我一直在努力将最内层的形状提升一个层次。如果数据帧是以多索引开始的,那么爆炸/掉落可以避免吗?i、 e.(批处理,时间步长)=[功能]您能展示一下如何在这样的多索引中转换数据帧吗?当然。编辑了问题描述。请参阅文章中的编辑。谢谢!问题是我原来的数据帧是参差不齐的。一个是我将所有的时间步都调平了,我可以到_numpy()。按照预期重塑
。