在pandas中将字典转换为dataframe列

2024-04-26 15:32:05 发布

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

我有一本这样的嵌套字典

  d = {1 : {'we': 26, 'is': 112},
       2 : {'tp': 26, 'fp': 91},
       3 : {'pp': 23, 'kj': 74}}

我想把它改为dataframe列,这样外部dict键变成行,它的元素充当列的元素。

期望输出:

  rows           col1      
  1      'we': 26, 'is': 112
  2      'tp': 26, 'fp': 91
  3      'pp': 23, 'kj': 74

Tags: 元素dataframe字典isdictppcol1rows
1条回答
网友
1楼 · 发布于 2024-04-26 15:32:05

如果这就是你字典里的东西,它不一定会保留内部dict的键顺序

import pandas as pd
d = {1 : {'we': 26, 'is': 112},
     2 : {'tp': 26, 'fp': 91},
     3 : {'pp': 23, 'kj': 74}}
# Replace the inner dicts with their string representations
for i in d:
    d[i] = str(d[i])
# Convert to dataframe
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
# Clean up column names
df.rename(columns={'index': 'row', 0: 'col1'}, inplace=True)

相关问题 更多 >