Skip to main content
 首页 » 编程设计

python之将字典转换为 Pandas 中的数据框列

2025年05月04日13txw1958

我有一个像这样的嵌套字典

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

我想将它更改为数据框列,这样外部字典键就变成行,并且它的元素充当列的元素。

期望的输出:

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

请您参考如下方法:

如果这就是您字典中的内容,则它不一定会保留内部字典的键顺序。

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)