Pandas DataFrame作为具有嵌入式列表的查找表

问题描述

我有一个具有以下结构的数据框:

abort-column-resize
accept-position
activate
activate-current
activate-cursor-item
activate-default
activate-focus
backspace
cancel
cancel-position
change-current-page
change-focus-row-expansion
change-value
clicked
close
composited-changed
copy-clipboard
cut-clipboard
cycle-focus
delete-from-cursor
end-selection
expand-collapse-cursor-row
extend-selection
focus-home-or-end
focus-tab
grab-focus
insert-at-cursor
kill-char
kill-line
kill-word
move
move-active
move-current
move-cursor
move-focus
move-focus-out
move-handle
move-page
move-scroll
move-slider
move-to-column
move-to-row
move-viewport
move-word
page-horizontally
paste-clipboard
popdown
popup
popup-menu
reorder-tab
row-activated
scroll-child
scroll-horizontal
scroll-vertical
select-all
select-cursor-item
select-cursor-parent
select-cursor-row
select-page
set-anchor
set-editable
set-scroll-adjustments
show-help
start-interactive-search
start-selection
toggle-add-mode
toggle-cursor-item
toggle-cursor-row
toggle-cursor-visible
toggle-focus-row
toggle-overwrite
undo-selection
unselect-all

我想查询数据框,以便在输入 A B [1,2,3] [a,b,c] [4,5,6] [d,e,f] 时返回1。同样,查询[a,c]应该返回6。最具可读性的方法是什么?

解决方法

使用maploc

n = 1
df.loc[df.A.map(lambda x: n in x),'B']

Out[209]:
0    [a,b,c]
Name: B,dtype: object
,

我会爆炸您的数据框:

df = df.explode('A').set_index('A')

n = 1
print(df.loc[n,'B'])

打印:

['a','b','c']