Intro
很简单的需求,不多说,直接看代码
import pandas as pd
pd.__version__
'0.23.4'
Demo
dict1 = {"x1": 1, "x2": 2, "x3": 3}
pd.DataFrame(dict1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-6aaa44730903> in <module>()
1 dict1 = {"x1": 1, "x2": 2, "x3": 3}
----> 2 pd.DataFrame(dict1)
D:\code\anaconda\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
346 dtype=dtype, copy=copy)
347 elif isinstance(data, dict):
--> 348 mgr = self._init_dict(data, index, columns, dtype=dtype)
349 elif isinstance(data, ma.MaskedArray):
350 import numpy.ma.mrecords as mrecords
D:\code\anaconda\lib\site-packages\pandas\core\frame.py in _init_dict(self, data, index, columns, dtype)
457 arrays = [data[k] for k in keys]
458
--> 459 return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
460
461 def _init_ndarray(self, values, index, columns, dtype=None, copy=False):
D:\code\anaconda\lib\site-packages\pandas\core\frame.py in _arrays_to_mgr(arrays, arr_names, index, columns, dtype)
7354 # figure out the index, if necessary
7355 if index is None:
-> 7356 index = extract_index(arrays)
7357
7358 # don't force copy because getting jammed in an ndarray anyway
D:\code\anaconda\lib\site-packages\pandas\core\frame.py in extract_index(data)
7391
7392 if not indexes and not raw_lengths:
-> 7393 raise ValueError('If using all scalar values, you must pass'
7394 ' an index')
7395
ValueError: If using all scalar values, you must pass an index
卡卡报了一堆错,这个错误可以通过修改dict解决,即value改成list
dict2 = {"x1": [1], "x2": [2], "x3": [3]}
pd.DataFrame(dict2)
x1 | x2 | x3 | |
---|---|---|---|
0 | 1 | 2 | 3 |
如果不修改原始数据咋整
dict1 = {"x1": 1, "x2": 2, "x3": 3}
pd.DataFrame([dict1])
x1 | x2 | x3 | |
---|---|---|---|
0 | 1 | 2 | 3 |
Ref
[1] https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe
2020-05-18 于南京市江宁区九龙湖