【问题标题】:Convert 3d pandas DataFrame to Numpy ndarray将 3d pandas DataFrame 转换为 Numpy ndarray
【发布时间】:2021-02-05 00:53:07
【问题描述】:

我有一个类似的数据框

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

我想将它转换成一个 numpy 形状的数组(批处理、时间步长、特征)。对于xs,应该是 (1,2,3)。

问题是熊猫只知道二维形状,所以to_numpy 产生一个二维形状。

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)

[编辑] 添加有关数据框如何到达此状态的上下文。

dataframe 最初开始于

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()

【问题讨论】:

  • 你看过 to_numpy 产生了什么吗? (不仅仅是它的形状)
  • 是的。它通常会产生正确的形状,即xs.to_numpy().shape # (1, 2),如果您检查最里面的尺寸,您可以看到正确的长度:xs.to_numpy()[0][0].shape # (3,)。因此,我认为,我一直在努力将最内在的形状提升一个层次。

标签: python pandas numpy


【解决方案1】:
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]]]

【讨论】:

  • 如果 DataFrame 作为多索引开始,是否可以避免爆炸/下降?即(批次,时间步长)= [特征]
  • 您能否展示如何在这样的 MultiIndex 中转换您的数据框?
  • 当然。编辑了问题描述。
  • 查看帖子中的编辑。
  • 谢谢!问题是我的原始数据框是锯齿状的。一个我按预期平衡了我能够to_numpy().reshape的所有时间步长。
猜你喜欢
  • 1970-01-01
  • 2018-05-22
  • 2019-10-31
  • 2019-08-04
  • 2020-02-10
  • 2015-06-13
  • 1970-01-01
  • 2018-02-15
  • 2020-08-20
相关资源
最近更新 更多