Python正在查找datafram中存在的多个列标题

2024-04-24 23:02:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从数据帧中存在的列标题列表中查找所有列标题(并输出所有作为字典存在的列标题,以便在tkinter下拉菜单中使用)

例如,假设我有一个列列表:

Options = ['title3', 'title5', 'title6']

数据帧有以下列:

title1   title4   title3    title6

我需要输出为:

choices = {'title3', 'title6'}.

我现在唯一的工作方式就是不雅观:

if 'title1' in df1:
    choices = { 'title1'}

if 'title1' in df1 and 'title5' in df1:
    choices = { 'title1', 'title5'}

等等

如果有人知道一个更好的方法让我得到的结果,我将非常感谢任何帮助

谢谢


Tags: 数据in标题列表if字典tkinterchoices
1条回答
网友
1楼 · 发布于 2024-04-24 23:02:37

我认为需要^{}

df = pd.DataFrame(columns=['title1','title4','title3','title6'])
Options = ['title3', 'title5', 'title6']
choices = df.columns.intersection(Options).tolist()
print (choices)
['title3', 'title6']

相关问题 更多 >