Skip to main content
 首页 » 编程设计

python之pandas DF的嵌套可变长度列表字典

2025年05月04日15落叶

我有一本看起来像这样的字典:

{ I1 : [['A',1],['B',2],['C',3]], 
  I2 : [['B',2],['D',4]], 
  I3 : [['A',2],['E',5]] 
} 

即我有一个索引(键),然后是可变数量的对。我想创建一个与字典具有相同索引的 pandas 数据框,其中列是列表对的第一个值,值是列表对的第二个值,NaN 填充缺失值(即第 I2 行将有“A”列中的 NaN)。有没有巧妙的方法来做到这一点?

请您参考如下方法:

import pandas as pd 
 
a={ 'I1' : [['A',1],['B',2],['C',3]], 
    'I2' : [['B',2],['D',4]], 
    'I3' : [['A',2],['E',5]] 
  } 
 
 
# create a list of dictionary from each rows 
 
''' 
The map function is used to convert say 'I3' 
to integer 3, which can then be used to sort on 
This is done because sorting  merely by the index string will lead to 
say 'I15' to appear before 'I4'(assuming a more general  
case of you having more than just 3 indexes) 
''' 
# the sorted function is used because the order of keys is not maintained in a dict 
 
row_dict = [dict(a[idx]) for _,idx in sorted(zip(map(lambda x: int(x[1:]),a),a))] 
 
df=pd.DataFrame(row_dict) 
 
 
    A   B   C   D   E 
0   1   2   3 NaN NaN 
1 NaN   2 NaN   4 NaN 
2   2 NaN NaN NaN   5