pandas from_dict 处理错误:ValueError: If using all scalar values, you must pass an index

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.

# Examples
By default the keys of the dict become the DataFrame columns:
>>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']} # 正常的传入字典,values需要时[]
>>> pd.DataFrame.from_dict(data) # 默认orient='columns',将key作为columns的名字,values传入的是list,长度需要一致
   col_1 col_2
0      3     a
1      2     b
2      1     c
3      0     d
# Specify orient='index' to create the DataFrame using dictionary keys as rows:
# 指定orient='index' key变成row
>>> 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
# When using the 'index' orientation, the column names can be specified manually:
>>> pd.DataFrame.from_dict(data, orient='index',
...                        columns=['A', 'B', 'C', 'D']) # 指定index后可以传入columns name
       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 


# 栗子1
# 如果values是用list包裹的 {'key':['value1','value2',...]} 不需要指定index,直接使用pd.DataFrame.from_dict(dict)就ok
dictA = {"name": ["莎士比亚"], "age": [2000], "hobby": ["writing"]}
print(pd.DataFrame(dictA)) # 默认orient='columns'
'''
   name   age    hobby
0  莎士比亚  2000  writing
'''
# 如果字典是费字典,dictA的时候我们需要指定index
dictA = {"name": "莎士比亚", "age": 2000, "hobby": "writing"}
print(pd.DataFrame(dictA,index=[1]))
'''
name   age    hobby
1  莎士比亚  2000  writing
'''

# 栗子2
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) #也可以实现上面1的需求
'''
   name   age    hobby
0  莎士比亚  2000  writing
'''

你可能感兴趣的:(pandas,python)