Convert Python dict into a dataframe

前端 未结 16 2692
暗喜
暗喜 2020-11-22 03:18

I have a Python dictionary like the following:

{u\'2012-06-08\': 388,
 u\'2012-06-09\': 388,
 u\'2012-06-10\': 388,
 u\'2012-06-11\': 389,
 u\'2012-06-12\':          


        
16条回答
  •  天命终不由人
    2020-11-22 04:10

    The error here, is since calling the DataFrame constructor with scalar values (where it expects values to be a list/dict/... i.e. have multiple columns):

    pd.DataFrame(d)
    ValueError: If using all scalar values, you must must pass an index
    

    You could take the items from the dictionary (i.e. the key-value pairs):

    In [11]: pd.DataFrame(d.items())  # or list(d.items()) in python 3
    Out[11]:
                 0    1
    0   2012-07-02  392
    1   2012-07-06  392
    2   2012-06-29  391
    3   2012-06-28  391
    ...
    
    In [12]: pd.DataFrame(d.items(), columns=['Date', 'DateValue'])
    Out[12]:
              Date  DateValue
    0   2012-07-02        392
    1   2012-07-06        392
    2   2012-06-29        391
    

    But I think it makes more sense to pass the Series constructor:

    In [21]: s = pd.Series(d, name='DateValue')
    Out[21]:
    2012-06-08    388
    2012-06-09    388
    2012-06-10    388
    
    In [22]: s.index.name = 'Date'
    
    In [23]: s.reset_index()
    Out[23]:
              Date  DateValue
    0   2012-06-08        388
    1   2012-06-09        388
    2   2012-06-10        388
    

提交回复
热议问题