如何从函数返回将dataframe分配给面板

2024-06-01 08:36:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个返回面板和数据帧的函数。例如

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

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

^{pr2}$

其中pn4是Panel4结构,pn3是Panel。据我所知,pn4.loc[0]应该是一个面板,pn3.loc[0]应该是一个数据帧。但是当我运行这样的代码时,我收到了一条错误消息

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

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

为了获得更多信息,我在下面发布了我的代码:

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

Tags: infordefvaluccoldlocmax
2条回答

对于数据帧和序列,可以使用lociloc(以及at和{})来获取和设置。这需要编码才能实现。你看到了错误

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

意味着还没有人能抽出时间来制造面板。在

你应该能够用

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

fo中的返回类型是dataframe;但是在代码的最后一行中,您将pn4.loc[0]和{}分配给dataframe对象。pn.4loc[0]和{}可以是Pandas系列,这就是为什么您看到错误,因为索引是。在

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

下面是Pandas 0.15.1中描述您遇到的非实现错误的源代码部分:

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!")

正如您所看到的,如果框架和面板的尺寸不匹配,它将引发错误。在

相关问题 更多 >