我有这样的dict:

data = {'1':{'a':10, 'b':30}, '2':{'a':20, 'b':60}}

我想转换成这样的数据框:
x   y   z
1   a   10
1   b   30
2   a   20
2   b   60

有人知道吗?

最佳答案

结合使用dictionary comprehension concat :

df = pd.concat({k: pd.Series(v) for k, v in data.items()}).reset_index()
df.columns = list('xyz')

print (df)
   x  y   z
0  1  a  10
1  1  b  30
2  2  a  20
3  2  b  60

为了获得更好的性能,请使用list compehensionsorting:
L = sorted([(k,k1,v1) for k,v in data.items() for k1,v1 in v.items()],
            key=lambda x: (x[0], x[1]))
print (L)
[('1', 'a', 10), ('1', 'b', 30), ('2', 'a', 20), ('2', 'b', 60)]

df = pd.DataFrame(L, columns=list('xyz'))
print (df)
   x  y   z
0  1  a  10
1  1  b  30
2  2  a  20
3  2  b  60

时间:
In [34]: %timeit jez1(data)
16.8 ms ± 403 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [35]: %timeit jez(data)
1.96 s ± 90.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [37]: %timeit jp(data)
43 ms ± 353 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

与@jp相同的代码:
data = {str(k): {'a': 10, 'b': 30} for k in range(10000)}

def jp(data):
    return pd.melt(pd.DataFrame.from_dict(data, orient='index').reset_index().rename(columns={'index': 'x'}),
                   id_vars=['x'], value_vars=['a', 'b'], var_name='y', value_name='z')\
             .sort_values(['x', 'y']).reset_index(drop=True)

def jez(data):
    df = pd.concat({k: pd.Series(v) for k, v in data.items()}).reset_index()
    df.columns = list('xyz')
    return df

def jez1(data):
    L = sorted([(k,k1,v1) for k,v in data.items() for k1,v1 in v.items()], key=lambda x: (x[0], x[1]))
    df = pd.DataFrame(L, columns=list('xyz'))
    return df

assert (jez1(data).values == jez(data).values).all()

关于python - 将dict的dict转换为pandas中的dataframe,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49817811/

10-12 18:02