python - 如何将字典的字典展开到 pandas DataFrame 中以获得更大的字典?

标签 python python-3.x pandas dictionary dataframe

考虑以下 python3.x 中的字典字典

dict1 = {4: {4:25, 5:39, 3:42}, 5:{24:94, 252:49, 25:4, 55:923}}

我想将其展开到 pandas DataFrame 中。似乎有两个选择:

df1 = pd.DataFrame.from_dict(dict1, orient='columns')

print(df1)
        4      5
3    42.0    NaN
4    25.0    NaN
5    39.0    NaN
24    NaN   94.0
25    NaN    4.0
55    NaN  923.0
252   NaN   49.0

其中的列是主字典键 4 和“5”,行索引是子字典键,值是子字典值。

另一个选项是

df2 = pd.DataFrame.from_dict(dict1, orient='index')
print(df2)
    4     5     3     24    252  25     55 
4  25.0  39.0  42.0   NaN   NaN  NaN    NaN
5   NaN   NaN   NaN  94.0  49.0  4.0  923.0

其中列是内部“子字典”的键,行索引是主字典的键,值是子字典的键。

是否有一种标准方法可以让我们如下展开Python字典?

key inner_key values
4        3      42 
4        4      25
4        5      39
5        24     94
5        25     4
5        55     923
5        252    49

使用from_dict()后最好不要操作DataFrame,因为对于更大的Python字典,这可能会变得相当内存密集。

最佳答案

列表理解

列表理解应该相当有效:

dict1 = {4: {4:25, 5:39, 3:42}, 5: {24:94, 252:49, 25:4, 55:923}}

cols = ['key', 'inner_key', 'values']

df = pd.DataFrame([[k1, k2, v2] for k1, v1 in dict1.items() for k2, v2 in v1.items()],
                  columns=cols).sort_values(cols)

print(df)

   key  inner_key  values
2    4          3      42
0    4          4      25
1    4          5      39
3    5         24      94
5    5         25       4
6    5         55     923
4    5        252      49

pd.melt + dropna

如果您不介意使用 df1 进行工作,您可以通过 pd.melt 取消数据透视,然后删除 value 为空的行.

df1 = df1.reset_index()

res = pd.melt(df1, id_vars='index', value_vars=[4, 5])\
        .dropna(subset=['value']).astype(int)

print(res)

    index  variable  value
0       3         4     42
1       4         4     25
2       5         4     39
10     24         5     94
11     25         5      4
12     55         5    923
13    252         5     49

关于python - 如何将字典的字典展开到 pandas DataFrame 中以获得更大的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53422873/

相关文章:

python - 使用 pywin32 获取 GUIThreadInfo()

特定大小的 Python 类型数组

python - 使用 Pandas 导入时,如何跳过 .txt 文件中值多于/少于 6 的行

Python从子集中查找对(对数正在变化)

python - 在 Python 中处理 `
`

python - 热图 Python

python - Memoize Python 垃圾收集

python - 将 pandas 中的字典条目解压到数据框中

谁能把这个翻译成Python?

python - 解开数据框