如何通过函数将数据帧分配给面板 return

How to assign dataframe to panel from a function return

我有一个 returns 面板和数据框的功能。例如,

def fo(pn,df)
  some update on pn,df
  return pn, df

然后我需要调用 fo 函数来更新 pn4 和 pn3,如下所示,

pn4.loc[0], pn3.loc[0] = fo(pn,df)

其中pn4是Panel4结构,pn3是Panel。据我所知,pn4.loc[0] 应该是一个面板,pn3.loc[0] 应该是一个数据框。但是当我 运行 这样的代码

时,我收到了一条错误消息

NotImplementedError: cannot set using an indexer with a Panel yet!

那么我该如何解决这个错误呢?提前致谢。

有关更多信息,我 post 我的代码如下:

def update(x, UC, SC, A, U): # accelerated version, examined on 07/15 

    for a in A:
        UC_old = UC.copy()
        for u in U:
            UC.loc[a,:,u] = UC_old.loc[a,:,u] - UC_old.loc[a,:,x] * UC_old.loc[a,x,u]
        SC_old = SC.copy()
        SC.loc[:,a] = SC_old.loc[:,a] + UC_old.loc[a,x,:] * (1 - SC_old.loc[x,a])

    return UC, SC


def Streaming(UC, Au, k, U, A):
    ep = 0.01
    SC = pd.DataFrame(0.0, index = U, columns = A)
    max_mg = 0    
    for x in U:
        mg = computeMG(x, UC, SC, Au, A, U)
        max_mg = mg if mg > max_mg else max_mg
    del SC
    C = []
    S = {}
    m = max_mg
    while (m <= k*max_mg):
        C.append(m)
        S[m] = []        
        m = m * (1+ep)
    print len(C)
    UCC = pd.Panel4D(dict([(c, UC.copy()) for c in C]))           
    SCC = pd.Panel(0., items = C, major_axis = U, minor_axis = A)
    for x in U:
        for c in C:
            if (computeMG(x, UCC.loc[c], SCC.loc[c], Au, A, U) > c/float(2*k)) and (len(S[c])<k):
                S[c].append(x)
                UCC.loc[c], SCC.loc[c] = update(x, UCC.loc[c], SCC.loc[c], A, U) # where the error happens
    max_val = 0
    for c in C:
        val = 0
        for u in U:
            Tsu = 0
            for a in A:
                Tsu += SCC.loc[c,u,a]
            Tsu = Tsu / float(Au.loc[u])
            val += Tsu
        if val > max_val:
            S = S[c]
            max_val = val
    return S, max_val

fo中的return类型是dataframe;但是在代码的最后一行中,您将 pn4.loc[0]pn3.loc[0] 分配给数据框对象。 pn.4loc[0]pn3.loc[0] 可以是 Pandas 系列,这就是您看到错误的原因,因为索引是 .

将您的 return 命令设为 return pn.loc[0], df.loc[0],您可能可以解决问题。

以下是 Pandas 0.15.1 中描述您遇到的 NonImplementError 的源代码部分:

def _align_panel(self, indexer, df):
        is_frame = self.obj.ndim == 2
        is_panel = self.obj.ndim >= 3
        raise NotImplementedError("cannot set using an indexer with a Panel 
                                  yet!")

如您所见,如果框架和面板的尺寸不匹配,则会引发错误。

对于数据帧和系列,您可以使用 lociloc(以及 atiat)来获取和设置。这需要编码才能实现。您看到的错误

NotImplementedError: cannot set using an indexer with a Panel yet!

意味着还没有人在面板上实现它。

你应该可以用

完成作业
pn4[0], pn3[0] = fo(pn,df)