2

I have more than 15 dataframes and one list. Given the sample below

unit_list = ['%','umol/l','mmol/l','mmol/l','g/dL','mmol/l','umol/l','','mg/mmol','mg/L','','mg/mmol','g/L'
        'g/day','','mg/L','','mg/day','','mmol/l','','cells/uL','','','cells/uL']

#TWO DATAFRAME for sample

dataframesdict[hbA1c] = pd.DataFrame({'person_id':[1,2,3],'Date': ['2009-01-05 00:00:00','2009-01-05 00:00:00','2013-01-31 00:00:00'],'Value': [9.6,9.6,10]})
dataframesdict[Creatinine]   = pd.DataFrame({'person_id':[1,2,3],'Date': ['2119-01-05 00:00:00','2129-01-05 00:00:00','2113-01-31 00:00:00'],'Value': [19.6,29.6,210]})

What I would like to do is create a new column called unit in each dataframe present under the dataframesdict and fill the value from unit_list

I have got the unit_list ordered, so its like 0th element from unit_list should be filled in as value for unit column under 0th key (0th dataframe) in dataframesdict

Similarly dataframesdict[1]['unit] = unit_list[1]

I tried the below but it doesn't work due to the use of Index as key.

for i in range(len(key_list)):
    dataFramesDict[i]['unit'] = unit_list[i]

How can I make use of index to access and assign values at the same time? Below screenshot shows the expected output. Hba1c is the first index item in dict, so the corresponding first index item from unit_list is filled in as value in 'unit' column of the dataframe

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
The Great
  • 7,215
  • 7
  • 40
  • 128

2 Answers2

1

To start with, unless you are on python 3.6=>, dict will not guarantee you the order. In order words, hdA1c will not always be the first key.

If you were to maintain the order, use collections.OrderedDict.

As for the actual problem, enumerate would do the job:

for i, (k, v) in enumerate(dataframesdict.items()):
    v['unit'] = unit_list[i]

print(dataframesdict['hbA1c'])

Output:

                  Date  Value  person_id unit
0  2009-01-05 00:00:00    9.6          1    %
1  2009-01-05 00:00:00    9.6          2    %
2  2013-01-31 00:00:00   10.0          3    %
Chris
  • 29,127
  • 3
  • 28
  • 51
0

I am using Python 3.7.1 (it retains dict order) and the below answer works.However I welcome any better and efficient answer and looking forward to it

for i in range(len(key_list)):
    a = list(dataFramesDict)[i]
    dataFramesDict[a]['unit'] = unit_list[i]
The Great
  • 7,215
  • 7
  • 40
  • 128