New to python but I'm trying, all advice is appreciated.
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. 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.
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.
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"
g: Not sure what I was doing here; I believe trying to identify the column as "Delivery BA"
h: Entries for a particular company in the column
j: Accessing the cell containing the string value of the selected filter criteria
q: This didn't do what I wanted; I'm not sure now what I wanted
x: Unique values in "Delivery BA" column
y: The number of unique values in "Delivery BA" column. At time of writing, it sits at 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. 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.