pandas.DataFrame.from_dict#
- classmethodDataFrame.from_dict(data,orient='columns',dtype=None,columns=None)[source]#
Construct DataFrame from dict of array-like or dicts.
Creates DataFrame object from dictionary by columns or by indexallowing dtype specification.
- Parameters:
- datadict
Of the form {field : array-like} or {field : dict}.
- orient{‘columns’, ‘index’, ‘tight’}, default ‘columns’
The “orientation” of the data. If the keys of the passed dictshould be the columns of the resulting DataFrame, pass ‘columns’(default). Otherwise if the keys should be rows, pass ‘index’.If ‘tight’, assume a dict with keys [‘index’, ‘columns’, ‘data’,‘index_names’, ‘column_names’].
- dtypedtype, default None
Data type to force after DataFrame construction, otherwise infer.
- columnslist, default None
Column labels to use when
orient='index'. Raises a ValueErrorif used withorient='columns'ororient='tight'.
- Returns:
- DataFrame
See also
DataFrame.from_recordsDataFrame from structured ndarray, sequence of tuples or dicts, or DataFrame.
DataFrameDataFrame object creation using constructor.
DataFrame.to_dictConvert the DataFrame to a dictionary.
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"]}>>>pd.DataFrame.from_dict(data) col_1 col_20 3 a1 2 b2 1 c3 0 d
Specify
orient='index'to create the DataFrame using dictionarykeys as rows:>>>data={"row_1":[3,2,1,0],"row_2":["a","b","c","d"]}>>>pd.DataFrame.from_dict(data,orient="index") 0 1 2 3row_1 3 2 1 0row_2 a b c d
When using the ‘index’ orientation, the column names can bespecified manually:
>>>pd.DataFrame.from_dict(data,orient="index",columns=["A","B","C","D"]) A B C Drow_1 3 2 1 0row_2 a b c d
Specify
orient='tight'to create the DataFrame using a ‘tight’format:>>>data={..."index":[("a","b"),("a","c")],..."columns":[("x",1),("y",2)],..."data":[[1,3],[2,4]],..."index_names":["n1","n2"],..."column_names":["z1","z2"],...}>>>pd.DataFrame.from_dict(data,orient="tight")z1 x yz2 1 2n1 n2a b 1 3 c 2 4