solarenqu
solarenqu

Reputation: 814

Pandas dict to DataFrame

I have a python dict like this:

{'va1':   variable    bin                   points
 0         var1        NaN                   593.0,
 'var2':   variable    bin                   points
 22        var2        C2                    7.0
 23        var2        C5                    4.0
 24        var2        C0                    -30.0,
 'var3':   variable    bin                   points
 7         var3        06:                   2.0
 8         var3        05:                   0.0
 9         var3        01:                   -1.0}

I am trying to create a dataframe:

scores = pd.DataFrame(list(card.items()),columns=['bin','points'])

But my dataframe will looks like this:

enter image description here

So the points column contains all data, and it's not separated.

How can i create a dataframe properly? Thank you!

Upvotes: 0

Views: 90

Answers (1)

Wolf A
Wolf A

Reputation: 219

Format your dictionary so that the keys match the column names, and the corresponding values are the column values as a list.

import pandas as pd
import numpy as np
scores_dict = {'variable': ['var1', 'var2', 'var2', 'var2', 'var3', 'var3', 'var3'],
               'bin': [np.nan, 'C2', 'C5', 'C0', '06', '05', '01'],
               'points': [593, 7, 4, -30, 2, 0, -1]}

scores = pd.DataFrame.from_dict(scores_dict)


  variable  bin  points
0     var1  NaN     593
1     var2   C2       7
2     var2   C5       4
3     var2   C0     -30
4     var3   06       2
5     var3   05       0
6     var3   01      -1

Upvotes: 1

Related Questions