Skip to main content
 首页 » 编程设计

python之Pandas :在单独的列中显示嵌套的字典值

2025年01月19日9落叶无声

我有一个像这样的字典列表

[ 
  { 
    "detail": { 
    "name": "boo", 
    "id": 1 
    }, 
    "other": { 
      "gender": "m", 
      "no": "234" 
    } 
  }, 
  { 
    "detail": { 
      "name": "hoo", 
      "id": 2 
    }, 
    "other": { 
      "gender": "f", 
      "no": "456" 
    } 
  } 
] 

我想以下列格式在 excel 文件中打印此数据

  detail          other 
name    id    gender    no 
boo    1      m        234    
hoo    2      f        456 

简而言之,我想在父键列下的列中显示嵌套值。我如何使用 Pandas 实现这一目标?

或者是他们的任何其他库,我可以通过它实现这一点,因为 pandas 是一个非常沉重的库。

请您参考如下方法:

使用 pd.io.json.json_normalize -

df = pd.io.json.json_normalize(data)    

这导致列名看起来像这样 -

df.columns 
Index(['detail.id', 'detail.name', 'other.gender', 'other.no'], dtype='object') 

我们需要将其转换为 MultiIndex,使用 df.columns.str.split -

i = list(map(tuple, df.columns.str.split('.'))) 

调用 pd.MultiIndex.from_tuples 并返回结果 -

df.columns = pd.MultiIndex.from_tuples(i) 
df 
 
  detail       other      
      id name gender   no 
0      1  boo      m  234 
1      2  hoo      f  456 

如果您的数据更复杂,您可能需要对列进行额外的 sort_index 调用 -

df = df.sort_index(axis=1)