2017-04-19 66 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        []