pandas Datarame决定 [英] Pandas Datarame to dict

查看:54
本文介绍了 pandas Datarame决定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

pd.DataFrame([[1,2,3],[111,222,333]], columns=['A', 'B', 'C'])

     A    B    C
0    1    2    3
1  111  222  333
2   11   22   33

我需要将A和C中的每一行转换为dict.
我应该能够得到这个:

I need to convert each row in A and C to dict.
I should be able to get this:

{'1':'3',
 '111':'333',
 '11':'33'}

到目前为止,我还无法找到如何选择应包含哪些列以及如何不包含标题的方法

So far, I have not been able to find how to chose which columns should be included and how to not include the headers

推荐答案

来自 zip

dict(zip(df.A,df.C))
Out[1073]: {1: 3, 11: 33, 111: 333}

更新

from collections import defaultdict
d = defaultdict(dict)
for _,x in df.iterrows():
    d[x['A']][x['B']] = x['C']


d
Out[74]: defaultdict(dict, {1: {2: 3}, 11: {22: 33}, 111: {222: 333}})

这篇关于 pandas Datarame决定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆