pandas 数据框到有序字典 [英] panda dataframe to ordered dictionary
问题描述
有一篇文章,其中将熊猫数据帧转换为字典以进行进一步处理.
There is a post in which a panda dataframe is converted in to a dictionary for further processing.
执行此操作的代码是:
df = pd.read_excel(open('data/file.xlsx', 'rb'), sheetname="Sheet1")
dict = df.set_index('id').T.to_dict('dict')
会产生如下内容:{column -> {index -> value}}
是否有代替此{column -> {index -> value}}
的快速方法来获得此信息:OrderedDict(column, value)
作为返回值?
Is there a quick way to instead of this {column -> {index -> value}}
get this: OrderedDict(column, value)
as a return value?
当前,我正在使用从熊猫生成的字典,并将这些值一个接一个地分配到有序字典"中.这不是最佳方式,因为订单被打乱了
Currently, I am using the dictionary generated from pandas and assign those values in to an Ordered Dictionary, one by one. This is not the optimum way, as the order is scrambled
示例输入: 像这样的Excel文件:
Example input: An Excel file like this:
Unique_id | column1 | column2 | column3 | column 4
1 | 3 | 4 | 43 | 90
2 | 54 | 6 | 43 | 54
,输出应为有序字典,如下所示:
and the output should be an ordered dictionary like this:
{1:[3,4,43,90], 2:[54,6,43,54]}
推荐答案
通过使用OrderedDict
和Unique_id
列中的键,可以按期望的顺序获取字典.以下应作为说明:
You can get the dictionary in the desired order by using an OrderedDict
with keys from the Unique_id
column. The following should serve as an illustration:
from collections import OrderedDict
# Get the unordered dictionary
unordered_dict = df.set_index('Unique_id').T.to_dict('list')
# Then order it
ordered_dict = OrderedDict((k,unordered_dict.get(k)) for k in df.Unique_id)
# OrderedDict([(1, [3, 4, 43, 90]), (2, [54, 6, 43, 54])])
谢谢!
这篇关于 pandas 数据框到有序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!