首页 > 解决方案 > 将 3d pandas DataFrame 转换为 Numpy ndarray

问题描述

我有一个像

xs = pd.DataFrame({
    'batch1': {
        'timestep1': [1, 2, 3],
        'timestep2': [3, 2, 1]
    }
}).T

DataFrame,其中每个单元格都是一个列表

我想把它转换成一个形状的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()

未堆叠的数据框

标签: pythonpandasnumpy

解决方案


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

推荐阅读