Q:

Extending a pandas dataframe

I generated a pandas dataframe df (see example below). As a next step, my task is to extend this dataframe with values from specific rows and columns and generate a new dataframe df2 (see example below). 
How can I generate df2 with code and not manually? 
import pandas as pd
df = pd.DataFrame([[0, 0, 45, 1, 0, 0, 0, 0, 0, 0],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                   [2, 0, 45, 1, 0, 0, 0, 0, 0, 0],
                   [3, 0, 135, 2, 0, 0, 0, 0, 0, 0],
                   [4, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                   [5, 0, 135, 2, 0, 0, 0, 0, 0, 0]],
           columns=['trial_nr', 'mini_block_nr', 'stimulus_nr', 'CorResp', 'SR0', 'SR1', 'SR2', 'SR3', 'SR4', 'SR5'])
print(df)

df2 = pd.DataFrame([[0, 0, 45, 1, 0, 45, 135, 0, 0, 0],
                    [1, 0, 0, 0, 0, 45, 135, 0, 0, 0],
                    [2, 0, 45, 1, 0, 45, 135, 0, 0, 0],
                    [3, 0, 135, 2, 0, 45, 135, 0, 0, 0],
                    [4, 0, 0, 0, 0, 45, 135, 0, 0, 0],
                    [5, 0, 135, 2, 0, 45, 135, 0, 0, 0]],
                   columns=['trial_nr', 'mini_block_nr', 'stimulus_nr', 'CorResp', 'SR0', 'SR1', 'SR2', 'SR3', 'SR4', 'SR5'])
print(df2)

For example, the column SR0 represents the stimulus_nr that is associated with CorResp = 0 and mini_block_nr = 0, in this case stimulus_nr = 0. Likewise, the column SR1 represents the stimulus_nr that is associated with CorResp = 1 and mini_block_nr = 0, in this case stimulus_nr = 45.
I hope these examples illustrate what I am trying to achieve.
I really appreciate your help, many thanks! 
Chris

A:

Hey @Christina IIUC this is what you're trying to achieve:
for i in sorted(df.CorResp.unique()):
    mask=(df.CorResp==i)&(df.mini_block_nr==0)

    df['SR'+i]=df.loc[mask].stimulus_nr[0]

This will fill columns SR1 SR5 in your DataFrame, with the values you're looking for. If there's more CorResp values it will still work. It's not clear if you need a more general answer or if mini_block_nr can take different values, though, so I can edit if that's the case

