Convert a Pandas DataFrame to a dictionary

前端 未结 7 873
悲哀的现实
悲哀的现实 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:38

    should a dictionary like:

    {'red': '0.500', 'yellow': '0.250, 'blue': '0.125'}
    

    be required out of a dataframe like:

            a      b
    0     red  0.500
    1  yellow  0.250
    2    blue  0.125
    

    simplest way would be to do:

    dict(df.values.tolist())
    

    working snippet below:

    import pandas as pd
    df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
    dict(df.values.tolist())
    

    0 讨论(0)
提交回复
热议问题