python - 将 3d pandas DataFrame 转换为 Numpy ndarray
问题描述
我有一个像
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.reshape
因为 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()
解决方案
import pandas as pd
xs = pd.DataFrame({
'batch1': {
'timestep1': [1, 2, 3],
'timestep2': [3, 2, 1]
}
}).T
xs = pd.concat((xs.explode('timestep1').drop('timestep2', axis=1), xs.explode('timestep2').drop('timestep1', axis=1)), axis=1)
print(xs, '\n')
n = xs.to_numpy().reshape(1, 2, 3)
print(n)
输出:
timestep1 timestep2
batch1 1 3
batch1 2 2
batch1 3 1
[[[1 3 2]
[2 3 1]]]
编辑
从您的原始数据框开始,您可以执行以下操作:
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)
输出:
[[[1 2 3]
[3 2 1]]
[[4 5 6]
[7 8 9]]]
推荐阅读
- python - 导入 shared_randomstreams.RandomStreams 时无法从 Google Colab 上的 Theano 导入 local_bitwidth
- javascript - 如何将变量传递到 AWS Step Functions 中的 catch 语句
- gwt - GWTBootstrap3 已停产
- flutter - 如何在持久导航栏中增加主页按钮圆圈的大小
- android - 保存为 gs:// 或 https:// 用于用户的图像。哪种方式值得推荐?
- sql - 如何从 min - max 中获取数据,将同一表中的两列连接起来
- web - 如何在 CD 上创建一个带有 Web 服务器的网站
- android - Google Places API 建立取货点
- javascript - 如何将 next.js 应用部署到 Cpanel?
- tradingview-api - 有谁知道为什么它说变量 ,,`len` 已声明”,我该如何修复它... 交易视图