将大 pandas 转换为字典,定义用于键值的列 [英] Convert pandas to dictionary defining the columns used fo the key values

查看:65
本文介绍了将大 pandas 转换为字典,定义用于键值的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个熊猫数据框 test_df。我的目的是将其转换为字典。因此,我运行以下命令:

There's the pandas dataframe 'test_df'. My aim is to convert it to a dictionary. Therefore I run this:

   id   Name   Gender  Age  
0  1  'Peter'   'M'     32    
1  2  'Lara'    'F'     45   

因此我运行此命令:

test_dict = test_df.set_index('id').T.to_dict()

输出是这样的:

{1: {'Name': 'Peter', 'Gender': 'M', 'Age': 32}, 2: {'Name': 'Lara', 'Gender': 'F', 'Age': 45}}

现在,我只想选择名称和性别列作为字典键的值。我正在尝试将上面的脚本修改成这样:

Now, I want to choose only the 'Name' and 'Gender' columns as the values of dictionary's keys. I'm trying to modify the above script into sth like this:

test_dict = test_df.set_index('id')['Name']['Gender'].T.to_dict()

没有成功!

有任何建议吗?!

推荐答案

您非常亲密,请使用<$列 [[''Name','Gender']] 的c $ c>子集:

You was very close, use subset of columns [['Name','Gender']]:

test_dict = test_df.set_index('id')[['Name','Gender']].T.to_dict()
print (test_dict)
{1: {'Name': 'Peter', 'Gender': 'M'}, 2: {'Name': 'Lara', 'Gender': 'F'}}

也不需要 T ,请使用参数 orient ='index'

Also T is not necessary, use parameter orient='index':

test_dict = test_df.set_index('id')[['Name','Gender']].to_dict(orient='index')
print (test_dict)
{1: {'Name': 'Peter', 'Gender': 'M'}, 2: {'Name': 'Lara', 'Gender': 'F'}}

这篇关于将大 pandas 转换为字典,定义用于键值的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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