1

I have a dictionary like this:

{'6DEC19': 0.61, '13DEC19': 0.58, '27DEC19': 0.63, '31JAN20': 0.66, '27MAR20': 0.69, '26JUN20': 0.71}

I'm very simply trying to turn this in to a DataFrame with the columns being 6DEC19, 13DEC19 etc, with the index then being set to the current date and hour, the code for which I would use as pd.Timestamp.now().floor('60min').

With the resulting df looking like this:

                    6DEC19  13DEC19  27DEC19  31JAN20  27MAR20  26JUN20
2019-12-04 20:00:00 0.61    0.58     0.63     0.66     0.69     0.71

My first step would just be to turn the dict in to a dataframe and as far as I'm concerned this code should do the trick:

df = pd.DataFrame.from_dict(dict)

But I get this error message: ValueError: If using all scalar values, you must pass an index.

I really have no idea what the problem is here? Any suggestions would be great, and if anyone can fit the problem of changing the index in to the bargin so much the better. Cheers

top bantz
  • 585
  • 1
  • 12
  • 29
  • 1
    Duplicate of: [this](https://stackoverflow.com/questions/17839973/constructing-pandas-dataframe-from-values-in-variables-gives-valueerror-if-usi) – outflanker Dec 04 '19 at 20:17

3 Answers3

3

As the error message says you need to specify the index, so you can do the following:

import pandas as pd

d = {'6DEC19': 0.61, '13DEC19': 0.58, '27DEC19': 0.63, '31JAN20': 0.66, '27MAR20': 0.69, '26JUN20': 0.71}
df = pd.DataFrame(d, index=[pd.Timestamp.now().floor('60min')])

print(df)

Output

                     6DEC19  13DEC19  27DEC19  31JAN20  27MAR20  26JUN20
2019-12-04 17:00:00    0.61     0.58     0.63     0.66     0.69     0.71
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • That works perfectly thanks mate, why does adding the index stop the error? Why can't it just have set the index to 0 to begin with? Thanks again – top bantz Dec 04 '19 at 20:20
  • 1
    @topbantz I believe is an implementation decision, can't say for sure. – Dani Mesejo Dec 04 '19 at 20:24
1

try this:

import pandas as pd

a = {'6DEC19': [0.61], '13DEC19': [0.58], '27DEC19': [0.6], '31JAN20': [0.66], '27MAR20': [0.69], '26JUN20': [0.71]}

df = pd.DataFrame.from_dict(a)

print(df)
Chen-CN
  • 103
  • 7
-1

try this

newDF = pd.DataFrame(yourDictionary.items())
YzHan
  • 1