python - 熊猫数据框到 3D 数组
问题描述
我有一个这样的数据框
group b c d e label
A 0.577535 0.299304 0.617103 0.378887 1
0.167907 0.244972 0.615077 0.311497 0
B 0.640575 0.768187 0.652760 0.822311 0
0.424744 0.958405 0.659617 0.998765 1
0.077048 0.407182 0.758903 0.273737 0
我想使用填充将其重塑为 LSTM 可以用作输入的 3D 数组。所以A组应该输入长度为3的序列(填充后)和长度为3的B组。所需的输出类似于
array1 = [[[0.577535, 0.299304, 0.617103, 0.378887],
[0.167907, 0.244972, 0.615077, 0.311497],
[0, 0, 0, 0]],
[[0.640575, 0.768187, 0.652760, 0.822311],
[0.424744, 0.958405, 0.659617, 0.998765],
[0.077048, 0.407182, 0.758903, 0.273737]]]
然后标签也必须相应地重新塑造
array2 = [[1,
0,
0],
[0,
1,
0]]
如何放入填充并重塑我的数据?
解决方案
您可以先使用cumcount
为每个组创建一个计数,然后reindex
用MultiIndex.from_product
0 填充,最后导出到列表:
df["count"] = df.groupby("group")["label"].cumcount()
mux = pd.MultiIndex.from_product([df["group"].unique(), range(max(df["count"]+1))], names=["group","count"])
df = df.set_index(["group","count"]).reindex(mux, fill_value=0)
print (df.iloc[:,:4].groupby(level=0).apply(pd.Series.tolist).values.tolist())
[[[0.577535, 0.299304, 0.617103, 0.378887],
[0.167907, 0.24497199999999997, 0.6150770000000001, 0.31149699999999997],
[0.0, 0.0, 0.0, 0.0]],
[[0.640575, 0.768187, 0.65276, 0.822311],
[0.42474399999999995, 0.958405, 0.659617, 0.998765],
[0.077048, 0.40718200000000004, 0.758903, 0.273737]]]
print (df.groupby(level=0)["label"].apply(list).tolist())
[[1, 0, 0], [0, 1, 0]]
推荐阅读
- c# - ActionLink 和相对路径
- sql-server - SQL 表连接查找匹配数据
- google-kubernetes-engine - 我们如何为私有集群设置 Docker 镜像?
- google-chrome -
上传到 Chrome 商店时更改为 \u003Call_urls> - php - Laravel 服务提供者延迟加载
- mysql - mysql 5.5 中“有子句”中的未知列
- java - java.nio.file.DirectoryNotEmptyException 错误
- ansible - ansible 检查不存在的服务
- laravel - 将 Google 身份验证器与 laravel 5.6 集成的问题。如何集成 Google 身份验证 2 步过程
- bigdata - 什么是数据仓库,它可以应用于复杂数据吗?