From dict to pandas dataframe as rows

I am sure i must be missing something basic here. But as far as I know you can create a dataframe from a dict with pd.DataFrame.from_dict(). But I am not sure how it can be set that key-values pairs in a dict can be put it as rows in a dataframe.

For instance, given this example

d = {'a':1,'b':2}

the desired output would be:

    col1 col2
0    a     1
1    b     2

I know that the index might be a problem but that can be handle it with a simple index = [0]

Upvotes: 0

Views: 63

Answers (2)

loule.got
loule.got

Reputation: 16

This code should help you.

d = {k: [l] for k, l in d.items()}
pd.DataFrame(d).T.reset_index().rename(columns={'index': 'col1', 0: 'col2'})

Upvotes: 0

skoeb
skoeb

Reputation: 885

Duplicate of Convert Python dict into a dataframe.

Simple answer for python 3.

import pandas as pd
d = {'a':1,'b':2, 'c':3}
df = pd.DataFrame(list(d.items()), columns = ['cola','colb'])

Upvotes: 1

Related Questions