簡體   English   中英

如何將帶有字典的 dataframe 列轉換為行和列?

[英]How to convert dataframe column with dictionary to rows and columns?

我有一個 pandas dataframe 格式:

姓名
第一的 [{col1:'1',col2:'2'},{col1:'6',col2:'7'},{col1:'9',col2:'2'}]
第二 [{col1:'88',col2:'277'},{col1:'889',col2:'290'}]

我想把它轉換成這個 dataframe:

姓名 col1 col2
第一的 '1' '2'
第一的 '6' '7'
第一的 '9' '2'
第二 '88' '277'
第二 '889' '290'

我該怎么做? 謝謝!

您可以先分解explode ,然后通過應用Series將字典轉換為列。

import pandas as pd

data = {'name': ['First', 'Second'],
        'T': [[{'col1': '1', 'col2': '2'}, {'col1': '6', 'col2': '7'}, {'col1': '9', 'col2': '2'}],
              [{'col1': '88', 'col2': '277'}, {'col1': '889', 'col2': '290'}]]}
df = pd.DataFrame.from_dict(data)

df1 = df.explode('T')
df1 = pd.concat([df1.name, df1['T'].apply(pd.Series)], 1)

結果:

     name col1 col2
0   First    1    2
0   First    6    7
0   First    9    2
1  Second   88  277
1  Second  889  290

您可以直接使用json_normalize獲取所需的 dataframe。 但輸入必須是dictionary

df_dict = df.to_dict("records")
df_dict
[{'name': 'First',
  'T': [{'col1': '1', 'col2': '2'},
   {'col1': '6', 'col2': '7'},
   {'col1': '9', 'col2': '2'}]},
 {'name': 'Second',
  'T': [{'col1': '88', 'col2': '277'}, {'col1': '889', 'col2': '290'}]}]

json_normalize中,傳遞字典、要json_normalize的列,然后傳遞要包含的其他列

pd.json_normalize(df_dict, 'T', ['name']).reindex(columns=['name', 'col1', 'col2'])

    name    col1   col2
0   First   1      2
1   First   6      7
2   First   9      2
3   Second  88     277
4   Second  889    290

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM