簡體   English   中英

將字典列表轉換為數據框

[英]Convert a list of dictionary to a a dataframe

我有一個字典列表,它看起來像:

list_dict = [{'test1':{'a':1,'b':12,'c':40,'d':120,'e':20,'f':1,'g':2,'h':'2'}},
                  {'test2':{'a':5,'b':'10','c':20}},
                   {'test3':{'e':21,'f':'18','g':22,'h':20}}]

我想將其轉換為這樣的數據框:鍵應該作為行出現,測試應該作為列出現。 並且在測試沒有其他測試中存在的鍵的情況下,應將值填充為 NAN

    mac_type  test1  test2  test3
    a         1      5      NAN
    b         12     10     NAN
    c         40     20     NAN
    d         120    NAN    NAN
    e         20     NAN    21
    f         1      NAN    18
    g         2      NAN    22
    h         2      NAN    20

請幫助我。

將 dict 理解與展平嵌套的Dataframe一起使用並傳遞給Dataframe構造函數:

df = pd.DataFrame({k: v for x in list_dict for k, v in x.items()})
print (df)
  test1 test2 test3
a     1     5   NaN
b    12    10   NaN
c    40    20   NaN
d   120   NaN   NaN
e    20   NaN    21
f     1   NaN    18
g     2   NaN    22
h     2   NaN    20

或者為每個嵌套字典創建DataFrame並傳遞給concat ,如果大字典和許多外部鍵這應該像第一個解決方案一樣慢:

df = pd.concat([pd.DataFrame(x) for x in list_dict], axis=1)
print (df)
  test1 test2 test3
a     1     5   NaN
b    12    10   NaN
c    40    20   NaN
d   120   NaN   NaN
e    20   NaN    21
f     1   NaN    18
g     2   NaN    22
h     2   NaN    20

使用reduce構建您之前DataFrame

from functools import reduce
df = pd.DataFrame(reduce(lambda cum_dict, new_dict: dict(cum_dict, **new_dict), 
                         list_dict))

print (df)
  test1 test2 test3
a     1     5   NaN
b    12    10   NaN
c    40    20   NaN
d   120   NaN   NaN
e    20   NaN    21
f     1   NaN    18
g     2   NaN    22
h     2   NaN    20

暫無
暫無

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

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