ValueError: 9 columns passed, passed data had 2 columns

Question:

Why can’t I just convert a dict into a data frame?

dict = {
    "carat": 0.3,
    "cut": 64.0,
    "color": 55.0,
    "clarity": 4.25,
    "depth": 4.28,
    "table": 2.73,
    "x": 2.0,
    "y": 1.0,
    "z": 6.0
}

novo = pd.DataFrame(dict.items(), columns = dict.keys())

novo

This returns the error:

ValueError: 9 columns passed, passed data had 2 columns
Asked By: unstuck

||

Answers:

dict.items() returns 2-tuples (key, value); a sensible columns for that would then be, well, e.g. ('key', 'value'). But that wouldn’t give you the dataframe you’re likely after, anyway.

If passing in a dict, Pandas expects you to pass in one with lists for values (e.g. one value per row).
You can do that with a dictionary comprehension that takes each single value and wraps it in an 1-value list:

novo = pd.DataFrame({col: [value] for (col, value) in d.items()})
print(novo)

so

   carat   cut  color  clarity  depth  table    x    y    z
0    0.3  64.0   55.0     4.25   4.28   2.73  2.0  1.0  6.0
Answered By: AKX
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.