2017-04-19 68 views
2

假设我的数据帧df有两列:块,试用。每块有10个试验。现在我想从列表“my_response”中创建一个新的列“响应”。我似乎无法做类似如下:为熊猫数据帧的子集设置多个值

my_response = [1,5,2,4,3,1,4,2,3,4] 
df.loc[df['block'] == 0, 'response'] = my_response 

我知道,如果它是一个标量值

df.loc[df['block'] == 0, 'response'] = 1 

我可以设置的值有什么办法,我可以把值的列表中数据框的子集?

谢谢!

回答

1

您可以使用map和字典

df = pd.DataFrame(dict(block=[0, 0, 1, 1], trial=[0, 1, 0, 1])) 

my_response = {0: [1,5,2,4,3,1,4,2,3,4]} 

df.assign(response=df.block.map(my_response)) 

    block trial      response 
0  0  0 [1, 5, 2, 4, 3, 1, 4, 2, 3, 4] 
1  0  1 [1, 5, 2, 4, 3, 1, 4, 2, 3, 4] 
2  1  0        NaN 
3  1  1        NaN 

你甚至可以通过默认的空列表

df.assign(response=df.block.map(lambda x: my_response.get(x, []))) 

    block trial      response 
0  0  0 [1, 5, 2, 4, 3, 1, 4, 2, 3, 4] 
1  0  1 [1, 5, 2, 4, 3, 1, 4, 2, 3, 4] 
2  1  0        [] 
3  1  1        []