将pandas数据帧转换为字典

sin*_*ngh 4 python dictionary dataframe python-3.x pandas

我有一个pandas数据帧如下:

df=pd.DataFrame({'a':['red','yellow','blue'], 'b':[0,0,1], 'c':[0,1,0], 'd':[1,0,0]})
df
Run Code Online (Sandbox Code Playgroud)

看起来像

    a       b   c   d
0   red     0   0   1
1   yellow  0   1   0
2   blue    1   0   0
Run Code Online (Sandbox Code Playgroud)

我想将它转换为字典,以便我得到:

red     d
yellow  c
blue    b
Run Code Online (Sandbox Code Playgroud)

如果数据集非常大,请避免使用任何迭代方法.我还没有找到解决方案.任何帮助表示赞赏.

PaS*_*STE 8

首先,如果你真的想将它转换为字典,那么将你想要的值转换为DataFrame的索引会更好一些:

df.set_index('a', inplace=True)
Run Code Online (Sandbox Code Playgroud)

这看起来像:

        b  c  d
a              
red     0  0  1
yellow  0  1  0
blue    1  0  0
Run Code Online (Sandbox Code Playgroud)

您的数据似乎采用"一热"编码.您首先必须使用此处详述的方法将其反转:

series = df.idxmax(axis=1)
Run Code Online (Sandbox Code Playgroud)

这看起来像:

a
red       d
yellow    c
blue      b
dtype: object
Run Code Online (Sandbox Code Playgroud)

差不多了!现在使用to_dict'value'列(这是设置列a作为索引帮助的地方):

series.to_dict()
Run Code Online (Sandbox Code Playgroud)

这看起来像:

{'blue': 'b', 'red': 'd', 'yellow': 'c'}
Run Code Online (Sandbox Code Playgroud)

我认为这就是你要找的东西.作为单线:

df.set_index('a').idxmax(axis=1).to_dict()
Run Code Online (Sandbox Code Playgroud)