Python-根据另一个列表从列表中选择一个值
我有一个数据帧。在列Python-根据另一个列表从列表中选择一个值,python,pandas,Python,Pandas,我有一个数据帧。在列A中有一个整数列表,在列B中有一个整数。我想选取列A列表的第n个值,其中n是列B中的数字。因此,如果列A中有[1,5,6,3,4],列B中有[2],我想得到'6' 我试过这个: result = [y[x] for y in df['A'] for x in df['B'] 但它不起作用。请帮忙。你可以去申请,即 df = pd.DataFrame({'A':[[1,2,3,4,5],[1,2,3,4]],'B':[1,2]}) A B
A
中有一个整数列表,在列B
中有一个整数。我想选取列A
列表的第n个值,其中n是列B
中的数字。因此,如果列A
中有[1,5,6,3,4],列B
中有[2],我想得到'6'
我试过这个:
result = [y[x] for y in df['A'] for x in df['B']
但它不起作用。请帮忙。你可以去申请,即
df = pd.DataFrame({'A':[[1,2,3,4,5],[1,2,3,4]],'B':[1,2]})
A B
0 [1, 2, 3, 4, 5] 1
1 [1, 2, 3, 4] 2
# df.apply(lambda x : np.array(x['A'])[x['B']],1)
# You dont need np.array here, use it when the column B is also a list.
df.apply(lambda x : x['A'][x['B']],1) # Thanks @Zero
0 2
1 3
dtype: int64
将
zip
与列表理解一起使用
:
df['new'] = [y[x] for x, y in zip(df['B'], df['A'])]
print (df)
A B new
0 [1, 2, 3, 4, 5] 1 2
1 [1, 2, 3, 4] 2 3
df['A'][df['B']]
?在你的代码中,你陈述了你所尝试的,你在y
之前有一个开头[/code>,但是没有结尾]
。猜猜,你不需要np.array
df.apply(lambda x:x.A[x.B],1)