Home > Software engineering >  Convert Dictionary to Dataframe Pandas
Convert Dictionary to Dataframe Pandas

Time:12-24

i have multiple dict as array which i want to convert to dataframe

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}]

iwant this to make a table like this

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

i tried this

df.dropna()
df.head()

CodePudding user response:

Fill Nan values with bfill then transpose It.

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

outputs

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
>>> 

CodePudding user response:

Try:

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

Result for your example 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}
]

is

                       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

If you want the keys of the dicts as index:

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
  • Related