【问题标题】:Pandas Panel as numpy multidimensional array熊猫面板作为 numpy 多维数组
【发布时间】:2014-02-04 12:24:45
【问题描述】:

我是熊猫新手。我尝试在我有一个三维点网格中做一个例子,网格的维度是N1 x N2 x N3。 网格中的每个点都包含一些数据(numpy.ndarray、float 数字等)。例如:Point(0,0,0): 'date' = 18、'temperature array' = numpy.array([[1,2,3], [4,5,6]])。

现在我的目标是创建一个熊猫“表”(我来宾pandas.Panel),这样当我调用table['date'][Point(0,0,0)]时,结果应该返回:18,当我调用table['temperature array'][Point(0,0,0)]时,它返回@ 987654329@.

你能发一个简单的例子吗,对我有很大帮助。

谢谢

【问题讨论】:

    标签: python pandas panel


    【解决方案1】:

    Panel4D 可能就是您要找的。它实质上是根据您的前 3 个维度创建多级索引。

    import pandas as pd
    import numpy as np
    
    # 100 x 100 x 100 x 3 array
    data = np.random.randn(100,100,100,3)
    data[0,0,0]
    # out[]:
    #     array([ 0.85284721, -0.04883839, -0.09375558])
    
    table = pd.Panel4D(data)
    table.ix[0,0,0]
    # out[]:
    #     minor
    #     0    0.852847
    #     1   -0.048838
    #     2   -0.093756
    #     Name: 0, dtype: float64
    

    【讨论】:

      【解决方案2】:

      我还没有弄清楚如何将一个 numpy 数组存储在 Pandas NDFrame 的单个单元格中,即使我成功了,我也怀疑这不是一个好主意。 Pandas NDFrames 使用 NumPy 数组来存储基础数据。要将 NumPy 数组作为值存储在 NumPy 数组中,外部 NumPy 数组需要是 object dtype,这会阻止 NumPy(和 Pandas)将快速数值例程应用于数组。因此,在 NDFrame(例如 Panel 或 DataFrame)中嵌套 NumPy 数组会损害性能。

      您可以改为使用带有 MultiIndex 的 DataFrame:

      import pandas as pd
      
      index = pd.MultiIndex.from_tuples([(0,0,0),(0,0,1)])
      table = pd.DataFrame([(18,1,2,3,4,5,6),
                            (19,10,20,30,40,50,60)], index=index,
                           columns=['date','t0','t1','t2','t3','t4','t5'])
      print(table)
      #        date  t0  t1  t2  t3  t4  t5
      # 0 0 0    18   1   2   3   4   5   6
      #     1    19  10  20  30  40  50  60
      
      print(table.ix[(0,0,0),'date'])
      # 18
      
      print(table.ix[(0,0,1),'t0':'t5'].reshape(2,-1))
      # [[10 20 30]
      #  [40 50 60]]
      

      【讨论】:

      • “平面优于嵌套”仅适用于代码。它的意思是“尽可能平坦”。
      • @HeinzKurt:是的,你是对的。谢谢指正。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多