简体   繁体   English

创建选择框以基于Excel列中的唯一性传递字符串值

[英]Create selection box to pass string value based on uniques in Excel column

New to python but I'm trying, all advice is appreciated. python的新手,但是我正在尝试,所有建议都值得赞赏。

I have a master data sheet which I have loaded into a data frame. 我有一个主数据表,已将其加载到数据框中。 I have then been able to hard-code a value from the "Delivery BA" column in to return a data frame with only that value. 这样,我就可以将“ Delivery BA”列中的值硬编码为仅返回具有该值的数据帧。 I have also been able to list and count the unique values in the column. 我还能够列出并计算列中的唯一值。 I currently have a cell which displays a string value of the filter criteria selected for the "Delivery BA" column. 我目前有一个单元格,其中显示为“交付BA”列选择的过滤条件的字符串值。

What I would IDEALLY like to do is to be able to prompt the user with a selection box containing all the unique values in the column, and then, upon the user selecting a value, pass that value to the dataframe parameters so that it creates a dataframe with only that "Delivery BA" for entries, preferably without needing to access the value passed in the filter string cell. 我最想做的就是能够通过一个包含该列中所有唯一值的选择框来提示用户,然后在用户选择一个值时,将该值传递给dataframe参数,以便它创建一个仅具有条目“交付BA”的数据帧,最好无需访问在过滤字符串单元格中传递的值。

I have searched and searched so I apologize if this has been answered already, or something similar. 我进行了搜索,因此对是否已经回答或类似的内容表示歉意。

Please see what little code I have so far. 请看看我到目前为止有什么小代码。

Explanation of variables: 变量说明:
d: The number of entries in the column "Delivery BA" d:“交货BA”列中的条目数
g: Not sure what I was doing here; 克:不确定我在这里做什么; I believe trying to identify the column as "Delivery BA" 我相信尝试将该列标识为“投放BA”
h: Entries for a particular company in the column h:列中特定公司的条目
j: Accessing the cell containing the string value of the selected filter criteria j:访问包含所选过滤条件的字符串值的单元格
q: This didn't do what I wanted; 问:这没有实现我想要的; I'm not sure now what I wanted 我现在不确定我想要什么
x: Unique values in "Delivery BA" column x:“交货BA”列中的唯一值
y: The number of unique values in "Delivery BA" column. y:“投放BA”列中的唯一值数量。 At time of writing, it sits at 739. 在撰写本文时,它位于739。

Apologies if I've posted anything arbitrary or not enough information. 抱歉,如果我发布了任何随意的或不足的信息。 Thank you again. 再次感谢你。

EDIT: After spending ALL DAY on it, I have finally made a python program that works. 编辑:花了整天的时间之后,我终于制作了一个有效的python程序。 I feel stupid proud. 我感到愚蠢的骄傲。 A lot of it is code snippets compiled and tweaked but it finally all works together. 其中很多是经过编译和调整的代码片段,但最终它们可以一起工作。

import pandas

data = pandas.read_excel('****', header = None).values

df = pandas.DataFrame(data)
new_header = df.iloc[0]
df = df[0:]
df.columns = new_header

d = df['Delivery BA'].value_counts()

g = df.groupby('Delivery BA', as_index = False)

x = df['Delivery BA'].unique()
y = df['Delivery BA'].nunique()

xd = pandas.DataFrame(x)

xdList = x.tolist()

xdLists = sorted(xdList, key = str.lower)

import tkinter
from tkinter import *

class simpleapp_tk(tkinter.Tk):

    def __init__(self, parent):
        tkinter.Tk.__init__(self, parent)
        self.part = parent
        self.initialize()
        self.update_list()

    def initialize(self):        
        self.grid()
        self.create_widgets()
        self.lbox.bind('<ButtonRelease-1>', self.selecting)
        button = tkinter.Button(self, text=u"Confirm Selection",command=self.OnButtonClick)
        button.grid(column=0,row=2)
        self.labelVariable = tkinter.StringVar()
        label = tkinter.Label(self,textvariable=self.labelVariable,anchor="center",fg="white",bg="blue")
        label.grid(column=0,row=3,columnspan=2,sticky='EW')
        self.grid_columnconfigure(0,weight=1)
        self.resizable(False,False)

    def create_widgets(self):
        self.search_var = StringVar()
        self.search_var.trace("w", lambda name, index, mode: self.update_list())
        self.entry = Entry(self, textvariable = self.search_var, width = 26)
        self.yScroll = tkinter.Scrollbar(self, orient=VERTICAL)
        self.yScroll.grid(row=1,column=1, sticky=N+S)
        self.lbox = Listbox(self, width=45, height=15, yscrollcommand=self.yScroll.set)        
        self.entry.grid(row=0, column = 0, padx = 10, pady = 3)
        self.lbox.grid(row=1, column=0, padx=10, pady=3)
        self.yScroll['command'] = self.lbox.yview
        self.update_list()

    def update_list(self):
        search_term = self.search_var.get()

        lbox_list = [*xdLists]

        self.lbox.delete(0, END)

        for item in lbox_list:
            if search_term.lower() in item.lower():
                self.lbox.insert(END, item)

    def selecting(self,event):
        sel = self.lbox.curselection()
        seltext = self.lbox.get(sel)
        self.labelVariable.set(seltext)

    def OnButtonClick(self):
        global confirmedsel
        confirmedsel = ""
        sel = self.lbox.curselection()
        seltext = self.lbox.get(sel)
        confirmedsel = seltext
        print(confirmedsel)
        app.destroy()

if __name__=="__main__":

    app = simpleapp_tk(None)
    app.title('Please choose a company!')
    print ('Starting mainloop()')
    app.mainloop()

from shutil import copyfile
import datetime
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import *

template_file = '***'
output_file = confirmedsel + " " + "-" + " " + datetime.datetime.today().strftime('%Y-%m-%d') + ".xlsx"
print(output_file)

h = df.loc[df['Delivery BA'] == confirmedsel]

wb = openpyxl.load_workbook(template_file)
ws = wb.get_sheet_by_name('Sheet1')

ws['A1']

for r in dataframe_to_rows(h, index=False, header=True):
    ws.append(r)

ws.delete_rows(1, amount=1)    
attachment = str(output_file)
attachpath = "***"
attachfull = attachpath+attachment
attachf = str(attachfull)
wb.save(attachf)

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
attachment = str(output_file)
attachpath = "***"
attachfull = attachpath+attachment
attachf = str(attachfull)
print(attachf)
mail.Attachments.Add(Source=attachf)
mail.Display(True)

You can do something like this, add it at the end of the code. 您可以执行类似的操作,并将其添加到代码末尾。 If you run python and type d,g,h etc. and enter the select values will be print 如果您运行python并输入d,g,h等并输入选择值,则将打印

def menu():
    choice = input("""What variable do you want to see?
(Choose between: d, g, h, j, q, x and y)

Enter your choice:""")
    if choice == "d":
        print(d)
    elif choice == "g":
        print(g)
    #Etc...

menu()

Got some inspiration at this link, maybe its helpfull http://www.teachingcomputing.com/learn.p..._Functions 在此链接上获得了一些启发,也许对您有所帮助http://www.teachingcomputing.com/learn.p..._函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据列值和字符串命名写入excel文件 - Writing to excel file based on column value & string naming 根据选择的行子集添加列值 - Add a column value based on selection of a subset of rows 基于分隔符拆分字符串列并为 Pyspark 中的每个值创建列 - Split string column based on delimiter and create columns for each value in Pyspark 大熊猫:根据其他列中的条件创建具有字符串值的列 - pandas: create column with string value based on conditions in other columns 用唯一列表中的后一个替换列值 - replace column value with subsequent one from list of uniques Excel 创建一个在 Excel 列中产生值为 1 的 IF 语句 - Excel Create a IF statement that produces a value of 1 in Excel column 基于字符串创建新列 - Create New Column Based On String 如何创建选择框? - how to create a selection box? Python pandas:根据组内的最大值创建新列,但使用来自附加(字符串)列的值 - Python pandas: create new column based on max value within group, but using value from additional (string) column 如何根据Tkinter中的组合框选择值(列表框)动态显示label(文本)值? - How to display the label ( text) value dynamically based on combo box selection value ( List box) in Tkinter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM