0

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]

2 Answers2

1

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'])
skoeb
  • 805
  • 1
  • 6
  • 13
  • Weird, I was writing the same solution, but it keeps giving me an error: `'list' object is not callable` – Erfan Mar 12 '19 at 17:26
  • Are you using Python 2 or 3? The d.items() only needs to be converted to a list in Python 3 I believe. – skoeb Mar 12 '19 at 17:31
  • Using python 3.7. Very weird, might post this as question. – Erfan Mar 12 '19 at 17:31
0

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'})
loule.got
  • 16
  • 2