Alicia tech
Alicia tech

Reputation: 29

Dictionary to dataFrame

I have a dictionary that I want to convert to a 3-column Data Frame.

dict= {(0, 367): 0.0,
 (2, 6): 0.0,
 (2, 4): 0.0,
 (2, 3): 0.0,
 (2, 1): 0.0,
 (5, 6): 0.0,
 (5, 263): 0.0}

What I tried:

pd.DataFrame(results)

error I get:

ValueError: If using all scalar values, you must pass an index

Expected result

col1 col2 col3
0 367 0.0
2 6 0.0
2 4 0.0
2 3 0.0
2 1 0.0
5 6 0.0
5 263 0.0

Upvotes: 2

Views: 106

Answers (3)

BENY
BENY

Reputation: 323376

Try with Series

pd.Series(d).reset_index()
Out[140]: 
   level_0  level_1    0
0        0      367  0.0
1        2        6  0.0
2        2        4  0.0
3        2        3  0.0
4        2        1  0.0
5        5        6  0.0
6        5      263  0.0

Upvotes: 1

Henry Ecker
Henry Ecker

Reputation: 35686

Another option nesting result to make it a Multi-Index column then reset_index and change the column names:

results = {(0, 367): 0.0,
           (2, 6): 0.0,
           (2, 4): 0.0,
           (2, 3): 0.0,
           (2, 1): 0.0,
           (5, 6): 0.0,
           (5, 263): 0.0}

df = pd.DataFrame({'col3': results}).reset_index()
df.columns = ['col1', 'col2', 'col3']

df:

   col1  col2  col3
0     0   367   0.0
1     2     1   0.0
2     2     3   0.0
3     2     4   0.0
4     2     6   0.0
5     5     6   0.0
6     5   263   0.0

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195593

I suppose you want to create a DataFrame containing all values, not only first two:

dct = {
    (0, 367): 0.0,
    (2, 6): 0.0,
    (2, 4): 0.0,
    (2, 3): 0.0,
    (2, 1): 0.0,
    (5, 6): 0.0,
    (5, 263): 0.0,
}

df = pd.DataFrame(
    [[*k, v] for k, v in dct.items()], columns=["col1", "col2", "col3"]
)
print(df)

Prints:

   col1  col2  col3
0     0   367   0.0
1     2     6   0.0
2     2     4   0.0
3     2     3   0.0
4     2     1   0.0
5     5     6   0.0
6     5   263   0.0

Upvotes: 3

Related Questions