python数据帧到字典,键值问题(python dataframe to dictionary, key value issue)

编程入门 行业动态 更新时间:2024-10-18 08:24:51
python数据帧到字典,键值问题(python dataframe to dictionary, key value issue)

我正在创建一个数据帧,然后转换为字典,如下所示

data = {'ID': [1,2,3,4,5], 'A':['1','2','1','3','2'], 'B':[4,6,8,2,4]} frame = pd.DataFrame(data) dict_obj = dict(frame[['A','B']].groupby('A').median().sort_values(by='B'))

我的问题是我希望列A作为键,列B作为值,但不知何故,我得到一个奇怪的字典

dict_obj {'B': A 3 2 2 5 1 6 Name: B, dtype: int64}

我想要字典对象

{1:6,2:5,3:2}

有人可以帮忙吗?

I am creating a dataframe and then converting to a dictionary as below

data = {'ID': [1,2,3,4,5], 'A':['1','2','1','3','2'], 'B':[4,6,8,2,4]} frame = pd.DataFrame(data) dict_obj = dict(frame[['A','B']].groupby('A').median().sort_values(by='B'))

My problem is that I want column A as Key and column B as values but somehow I am getting a weird dictionary

dict_obj {'B': A 3 2 2 5 1 6 Name: B, dtype: int64}

i want dictionary object as

{1:6,2:5,3:2}

Could someone help please?

最满意答案

使用pd.Series.to_dict方法

frame.groupby('A').B.median().to_dict() {'1': 6, '2': 5, '3': 2}

Use the pd.Series.to_dict method

frame.groupby('A').B.median().to_dict() {'1': 6, '2': 5, '3': 2}

更多推荐

本文发布于:2023-07-16 12:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:键值   字典   数据   python   issue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!