我们说我的数据框df有两列:block,trial。每个区块有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
我有什么办法可以为数据框的子集添加值列表吗?
谢谢!
答案 0 :(得分: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 []