如何取消包含多个条目的数据帧字典的堆栈?

2024-04-19 17:34:52 发布

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

嗨,我有这本字典在下面

str1         x      y
        a   1.0   -3.0
        b   2.0   -2.5 

str2:        x      y                 
        a   3.0   -2.0
        b   4.0   -1.5

str3:        x      y 
        a   5.0   -1.0
        b   6.0   -0.5

我想要的结果是能够取消它的堆栈,这样我就得到了一个带有index=[str1,str2,str3]columns=[a,b]的数据帧。为了选择是使用x列上的值还是y列上的值来填充预期数据帧的行,我使用整数N

可以将N视为限制,说明上面的每一行使用x值,下面的每一行使用y值。你知道吗

If N=1, I use x values for str 1, y values for str 2 and str 3。你知道吗

If N=2, I use x values for str 1 and str 2 , y values for str 3.

If N=3, I use x values for str 1, str 2 and str 3.

当i=1时:

        a      b 
str1   1.0    2.0    (x values)
str2  -2.0   -1.5    (y values)
str3  -1.0   -0.5    (y values)

我知道我可以得到两个数据帧,在x和y上展开,然后连接我想保留的行,但是我想知道是否有更快的方法。你知道吗


Tags: columnsand数据forindexif字典堆栈
3条回答

为了更好地以Pythonic的方式解决这个问题,您可以首先将您的规则(使用x或y值)翻译成字典(可能有字典理解):

# replicate the dictionary in the post
>>> d = {'str1':{'a':{'x':1, 'y':-3}, 'b':{'x':2,'y':-2.5}}, 'str2':{'a':{'x':3, 'y':-2}, 'b':{'x':4,'y':-1.5}}, 'str3':{'a':{'x':5, 'y':-1}, 'b':{'x':6,'y':-0.5}}}
>>> indexes = ['str1', 'str2', 'str3']
>>> N_map = {1:{'str1':'x', 'str2':'y', 'str3':'y'}, 2:{'str1':'x', 'str2':'x', 'str3':'y'}}

然后我们可以循环N=1,。。。并通过列表/字典理解构建数据帧:

# only take the first two rules as an example
>>> for i in range(1, 3):
...   df_d = {col:[d[index][col][N_map[i][index]] for index in indexes] for col in ['a', 'b']}
...   pd.DataFrame(df_d, index=indexes)  

      a    b
str1  1  2.0
str2 -2 -1.5
str3 -1 -0.5
      a    b
str1  1  2.0
str2  3  4.0
str3 -1 -0.5

使用此数据帧字典:

d2
"""
{'str1':      a    b
         x  1.0  2.0
         y -3.0 -2.5, 
 'str2':      a    b
         x  3.0  4.0
         y -2.0 -1.5, 
 'str3':      a    b
         x  5.0  6.0
         y -1.0 -0.5}
"""

定义

df2 = pd.concat(d2)
df2.set_index(df2.index.droplevel(1),inplace=True) # remove 'x','y' labels
select = { N:[ 2*i + (i>=N) for i in range(3)] for N in range(1,4) }  

例如N = 1

In [3]: df2.iloc[select[N]]
Out[3]: 
        a    b
str1  1.0  2.0
str2 -2.0 -1.5
str3 -1.0 -0.5

下面是使用有序字典中的dictcomp的代码(有点pythonic):

def N_unstack(d,N):
    d = collections.OrderedDict(d)
    idx = list('x'*N+'y'*(len(d)-N))
    return pd.DataFrame({k:v[idx[i]] for i,(k,v) in enumerate(d.items())}).T

N_unstack(d,1)的输出,其中d是数据帧字典:

         a      b
str1     1.0    2.0
str2    -2.0    -1.5
str3    -1.0    -0.5

下面是我将如何做到这一点(使用pd.concat)。有点冗长:

def N_unstack(d,N):
    idx = list('x'*N+'y'*(len(d)-N))
    df = pd.concat([d['str1'][idx[0]],d['str2'][idx[1]],d['str3'][idx[2]]], axis=1).T
    df.index = ['str1','str2','str3']
    return df

编辑:使代码更像python

相关问题 更多 >