【问题标题】:create nested dict from pandas dataframe从熊猫数据框创建嵌套字典
【发布时间】:2019-01-11 18:49:31
【问题描述】:

我有一个 pandas 数据框,我想从中提取信息并创建一个嵌套字典以供下游使用,但是,我还不太擅长使用 pandas,我需要一些帮助!

我的数据框看起来像这样:

    Sequence    A_start A_stop  B_start B_stop
0   sequence_1  1   25  26  100
1   sequence_2  1   31  32  201
2   sequence_3  1   27  28  231
3   sequence_4  1   39  40  191

我想把它写到字典里,这样它就有这种形式:

d = {‘Sequnce: {(‘A_start’, ‘A_stop’) : [{'repeat_region':{'rpt_type':'long_terminal_repeat', 'note':"5'LTR"}}], ('B_start', 'B_stop): [{'misc_feature':{'gene': 'Gag', 'note': 'deletion of start codon'}}]}}

生成后是这样的:

{‘sequence_1’: {(‘1’, ‘25’) : [{'repeat_region':{'rpt_type':'long_terminal_repeat', 'note':"5'LTR"}}], (‘26’, '100’): [{'misc_feature':{'gene': 'Gag', 'note': 'deletion of start codon'}}]}, 
‘sequence_2’: {(‘1’, ‘31’) : [{'repeat_region':{'rpt_type':'long_terminal_repeat', 'note':"5'LTR"}}], ('32', '201’): [{'misc_feature':{'gene': 'Gag', 'note': 'deletion of start codon'}}]}, ...}

我认为列表推导式可能是解决此问题的一种简单方法,但它最终可能看起来过于复杂。这是我迄今为止所拥有的,显然还没有奏效。我不确定是否可以使用 iteritems() 或 groupby() 以外的东西来识别字典中条目的结构。任何帮助将不胜感激!

LTR_sub_features = [{'repeat_region':{'rpt_type':'long_terminal_repeat', 'note':"5'LTR"}}]
gag_sub_features = [{'misc_feature':{'gene': 'Gag', 'note': 'deletion of start codon'}}]

ltr_gag_dict = {
Sequence: {(A_start,A_end): LTR_sub_features, (B_start,B_end):gag_sub_features} 
for Sequence, A_start, A_end, B_start, B_end in ltr_gag_df.groupby('Sequence')}

【问题讨论】:

  • 试试 pandas.DataFrame.to_dict

标签: python-3.x pandas dictionary nested list-comprehension


【解决方案1】:

您可以使用 iterrows() 随时更新字典:
iterrows() 为每一行创建一个元组,其中第一个元素(即 row[0])是行的索引,第二个元素是行中所有值的 pd.Serie 对象。

<input>
            A_start A_end   B_start     B_end
sequence_1  0.1     0.025   0.030303    0.001
sequence_2  0.2     0.050   0.060606    0.002
sequence_3  0.3     0.075   0.090909    0.003
sequence_4  0.4     0.100   0.121212    0.004

A_value = 'some value'
B_value = 'other value'
d = dict()


for row in df.iterrows():  
    d[row[0]] = {(row[1]['A_start'], row[1]['A_end']): A_value, (row[1]['B_start'], row[1]['B_end']): B_value}

<output>
{'sequence_1': {(0.10000000000000001, 0.025000000000000001): 'some value', (0.030303030303030304, 0.001): 'other value'}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-14
    • 2017-01-01
    • 2021-02-04
    • 2021-11-28
    • 2021-09-27
    • 2016-01-14
    相关资源
    最近更新 更多