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}更多推荐
发布评论