0

I want to insert dictionaries within a list of dictionaries as rows in a dataframe with the indices equal to the values found in every key 'index' while moving the rows previously occupying those indices 1 step down so they don't get overwritten.

ex.

List:

rows=
 [{'Abbreviation': u'3-HYDROXY-3-METHYL-GLUTARYL-COA_m',
  'Charge': -5.0,
  'Charged Formula': u'C27H39N7O20P3S1',
  'Neutral Formula': u'C27H44N7O20P3S1',

  'index': 101},

 {'Abbreviation': u'5-METHYL-THF_c',
  'Charge': -2.0,
  'Charged Formula': u'C20H23N7O6',
  'Neutral Formula': u'C20H25N7O6',

  'index': 204}]

DataFrame: df

Before:

index   Abbreviation   
101     foo        
204     bar        

After:

index   Abbreviation  | etc.. 
101     3-HYDROXY-3-METHYL-GLUTARYL-COA_m .
102     foo
204     5-METHYL-THF_c
205     bar     

Any help is appreciated. Thank you very much!

sirpeanut
  • 1
  • 1
  • Possible duplicate of [Add one row to pandas DataFrame](https://stackoverflow.com/questions/10715965/add-one-row-to-pandas-dataframe) – Itamar Mushkin Jul 22 '19 at 07:42

1 Answers1

0

Regular list insertion should work here. Posting some sample code below:

d1 = { 'index' : 101 }
d2 = { 'index' : 102 }
d4 = { 'index' : 104 }
l = [d1, d4]

# assuming elements of l have the key 'index' and
# are sorted in the ascending order of 'index'

# inserting d2 in l
for i, v in enumerate(l):
  if v['index'] > d2['index']:
    break
l.insert(i, d2)

List contents:

Before inserting d2
[{'index': 101}, {'index': 104}]

After inserting d2
[{'index': 101}, {'index': 102}, {'index': 104}]
gsr
  • 91
  • 5