Convert a Pandas DataFrame to a dictionary

前端 未结 7 963
悲哀的现实
悲哀的现实 2020-11-22 08:07

I have a DataFrame with four columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys and the elements of o

7条回答
  •  自闭症患者
    2020-11-22 08:29

    DataFrame.to_dict() converts DataFrame to dictionary.

    Example

    >>> df = pd.DataFrame(
        {'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
    >>> df
       col1  col2
    a     1   0.1
    b     2   0.2
    >>> df.to_dict()
    {'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}
    

    See this Documentation for details

提交回复
热议问题