首页 > 解决方案 > 熊猫数据框到 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]]

如何放入填充并重塑我的数据?

标签: pythonpandasnumpy

解决方案


您可以先使用cumcount为每个组创建一个计数,然后reindexMultiIndex.from_product0 填充,最后导出到列表:

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]]

推荐阅读