pandas from_dict 处理错误:ValueError: If using all scalar values, you must pass an index
- 字典的values的类型,同时是否需要指定orient='index’这个属性
pandas.core.frame.DataFrame @classmethod def from_dict(cls,
data: dict,
orient: Any = "columns",
dtype: Any = None,
columns: Any = None) -> DataFrame
'''
Construct DataFrame from dict of array-like or dicts.
Creates DataFrame object from dictionary by columns or by index allowing dtype specification.
'''
See Also
DataFrame.from_records
DataFrame from structured ndarray, sequence of tuples or dicts, or DataFrame.
DataFrame
DataFrame object creation using constructor.
By default the keys of the dict become the DataFrame columns:
>>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
>>> pd.DataFrame.from_dict(data)
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
>>> data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']}
>>> pd.DataFrame.from_dict(data, orient='index')
0 1 2 3
row_1 3 2 1 0
row_2 a b c d
>>> pd.DataFrame.from_dict(data, orient='index',
... columns=['A', 'B', 'C', 'D'])
A B C D
row_1 3 2 1 0
row_2 a b c d
Params:
data – Of the form {field : array-like} or {field : dict}.
orient – The "orientation" of the data. If the keys of the passed dict should be the columns of the resulting DataFrame, pass 'columns' (default). Otherwise if the keys should be rows, pass 'index'.
dtype – Data type to force, otherwise infer.
columns – Column labels to use when ``orient='index'``. Raises a ValueError if used with ``orient='columns'``.
< Python 3.8 (base) >
`from_dict(cls, data, orient="columns", dtype=None, columns=None)` on pandas.pydata.org
dictA = {"name": ["莎士比亚"], "age": [2000], "hobby": ["writing"]}
print(pd.DataFrame(dictA))
'''
name age hobby
0 莎士比亚 2000 writing
'''
dictA = {"name": "莎士比亚", "age": 2000, "hobby": "writing"}
print(pd.DataFrame(dictA,index=[1]))
'''
name age hobby
1 莎士比亚 2000 writing
'''
print(pd.DataFrame.from_dict(dictA, orient="index",columns=['A']))
'''将key作为了row名字
A
name 莎士比亚
age 2000
hobby writing
'''
print(pd.DataFrame.from_dict(dictA, orient="index").T)
'''
name age hobby
0 莎士比亚 2000 writing
'''