简体   繁体   中英

How can I create a dictionary with 2 keys where the the first key is the index, the second key is from a list and the values from columns of a df?

I have a data frame (small example below) with columns t and Machine 1 - 5.

speed_dict = {'Machine 1': {1: 3, 2: 2, 3: 2, 4: 3, 5: 0, 6: 1, 7: 5, 8: 5, 9: 5, 10: 5},
              'Machine 2': {1: 1, 2: 6, 3: 5, 4: 1, 5: 3, 6: 3, 7: 5, 8: 3, 9: 2, 10: 5},
              'Machine 3': {1: 1, 2: 5, 3: 0, 4: 4, 5: 2, 6: 6, 7: 2, 8: 2, 9: 2, 10: 5},
              'Machine 4': {1: 3, 2: 2, 3: 1, 4: 4, 5: 2, 6: 4, 7: 0, 8: 0, 9: 2, 10: 2},
              'Machine 5': {1: 1, 2: 4, 3: 4, 4: 4, 5: 7, 6: 7, 7: 7, 8: 0, 9: 3, 10: 8}}

speed = pd.DataFrame.from_dict(speed_dict)

I want to create a dictionary with 2 keys, one being the time and the other the machines but only 1 to 4. It should look as follows:

{(1, 'm1'): 3,
 (2, 'm1'): 2,
.
.
.
(9, 'm4'): 2,
(10, 'm4'): 2}

I can create separate dictionaries for each machine using dictionary comprehensions:

# Machines
machines = ['m1', 'm2', 'm3', 'm4']    
# Running time
time = speed.index.to_list()
# Speed
# Machine 1
speed_M1 = speed['Machine 1'].to_list()
speed_time_M1 = {time[i]: speed_M1[i] for i in range(len(time))}

But this gives the output as: {1: 3, 2: 2, 3: 2, 4: 3, 5: 0, 6: 1, 7: 5, 8: 5, 9: 5, 10: 5} which is close but not exactly there yet.

Is there a way to do this?

Thanks go out to @It_is_Chris for commenting the answer.

The following works perfectly:

speed[speed.columns[:-1]].stack().to_dict()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM