将字典转换为数据框Pandas



我有多个字典作为数组,我想转换为数据帧

df= [{'Federal-gov': 0, 'Local-gov': 1, 'Never-worked': 2},
{'Divorced': 0, 'Married-AF-spouse': 1, 'Married-civ-spouse': 2, 'Married-spouse-absent': 3, 'Never-married': 4, 'Separated': 5, 'Widowed': 6}]

我想创建一个这样的表

Federalgov 0
Local-gov 1
Never-worked 2
.
.
.
.
separeted 5
widowed 6

i tried this

df.dropna()
df.head()

用bfill填充Nan值,然后转置。

df =  pd.DataFrame(df)
df= df.fillna(method="bfill")
df = df.dropna(how='any').T.astype(int)
print(df)

输出
Federal-gov            0
Local-gov              1
Never-worked           2
Divorced               0
Married-AF-spouse      1
Married-civ-spouse     2
Married-spouse-absent  3
Never-married          4
Separated              5
Widowed                6
>>> 

尝试:

df = pd.DataFrame(item for rec in dicts for item in rec.items())

示例dicts的结果

dicts = [
{'Federal-gov': 0, 'Local-gov': 1, 'Never-worked': 2},
{'Divorced': 0, 'Married-AF-spouse': 1, 'Married-civ-spouse': 2, 'Married-spouse-absent': 3, 'Never-married': 4, 'Separated': 5, 'Widowed': 6}
]

0  1
0            Federal-gov  0
1              Local-gov  1
2           Never-worked  2
3               Divorced  0
4      Married-AF-spouse  1
5     Married-civ-spouse  2
6  Married-spouse-absent  3
7          Never-married  4
8              Separated  5
9                Widowed  6

如果您想要dicts的键作为索引:

df = pd.DataFrame(item for rec in dicts for item in rec.items()).set_index(0)
1
0                       
Federal-gov            0
Local-gov              1
Never-worked           2
Divorced               0
Married-AF-spouse      1
Married-civ-spouse     2
Married-spouse-absent  3
Never-married          4
Separated              5
Widowed                6

相关内容

  • 没有找到相关文章