Builiding a selection from a Dataframe - python-3.x

i want to build a selection from a dataframe based on double search-arguments. In detail:
I have build a search within a given Dataframe based on one value. This value can be given multiple times. The difference can be found in the row of the value. Here is a example:
TECHNIKART FSZ BEZEICHNUNG FIRMA PRODUKT_SPANNUNG KLIMA EW_KW MENGE_KW LEISTUNG_KW Ü
I get this Dataframe from following search in a bigger Dataframe:
key = '71E'
try:
geraet_dat2 = geraet_dat[geraet_dat.FSZ == key]
lang = len(geraet_dat2.index)
print(geraet_dat2)
My idea is now to have a if-else-query based on the length of the Dataframe. If the Dataframe has the lenght 1 i will print the values of the needed cells. If the Dataframe is longer than 1 the following popup appears:
def abfrage_selektion():
popup_selektion = Tk()
frame_selek = Frame(popup_selektion)
frame_selek.pack()
popup_selektion.configure(bg="Snow2")
popup_selektion.geometry('300x250')
popup_selektion.title('Bitte Gerät auswählen!')
LABEL_SELEKTION = LabelFrame(popup_selektion, text="Bitte Gerät auswählen: ")
LABEL_SELEKTION.place(x = 2, y = 2, width = 296, height = 246)
INFO = ttk.Label(LABEL_SELEKTION, justify=CENTER, text="Diese FSZ ist mehrfach verfügbar! \nBitte das entsprechende Gerät wählen!")
INFO.place(x = 50, y = 5)
SEPTR_1 = ttk.Separator(LABEL_SELEKTION, orient=HORIZONTAL)
SEPTR_1.place(x = 5, y = 40, width = 280)
GERAET = ttk.LabelFrame(LABEL_SELEKTION, text="Geräte: ")
GERAET.place(x = 15, y = 50, width = 260, height = 120)
LISTE = Listbox(GERAET, yscrollcommand=True)
LISTE.insert(1, '1')
LISTE.insert(2, '2')
LISTE.insert(3, '3')
LISTE.insert(4, '4')
LISTE.place(x = 5, y = 2, width = 240, height = 90)
SEPTR_2 = ttk.Separator(LABEL_SELEKTION, orient=HORIZONTAL)
SEPTR_2.place(x = 5, y = 180, width = 280)
BUTTON_OK = ttk.Button(LABEL_SELEKTION, text="OK")
BUTTON_OK.place(x = 5, y = 190, width = 280, height = 30)
that far everything is nice an clear for me.
But now the point i dont know how to solve:
In the popup i want a selection from the given Dataframe with more than one Dataset to select the wanted Data. The criteria for the selection should be 'BEZEICHNUNG' and 'PRODUKT_SPANNUNG'.
Do you have any ideas how i can do this? I searched in the web but didnt find a good solution for that.
Thank you for you help!

Related

How to change color of mark on topoplot interactively?

I want to create interactive line- and topoplot depending on menu. I figured out how to make red the line chosen in menu, but it doesn't work for topoplot marks (black circles inside topoplot). I can change it manually (cmap[][4] = RGB{N0f8}(1.0,0.0,0.0)), but how to do that interactively?
f = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98), resolution = (1500, 700))
ax = Axis(f[1:3, 1], xlabel = "Time [s]", ylabel = "Voltage amplitude [µV]")
N = 1:length(pos) #1:4
hidespines!(ax, :t, :r)
GLMakie.xlims!(-0.3, 1.2)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
times = range(-0.3, length=size(dat_e,2), step=1 ./ 128)
lines = Dict()
for i in N
mean_trial = mean(dat_e[i,:,:],dims=2)[:,1]
line = lines!(times, mean_trial, color = "black")
lines[i] = line
end
hidedecorations!(ax, label = false, ticks = false, ticklabels = false)
topo_axis = Axis(f[2, 2], width = 178, height = 178, aspect = DataAspect())
Makie.xlims!(low = -0.2, high = 1.2)
Makie.ylims!(low = -0.2, high = 1.2)
topoMatrix = eegHeadMatrix(pos[N], (0.5, 0.5), 0.5)
cmap = Observable(collect(ColorScheme(range(colorant"black", colorant"black", length=30))))
#cmap[][4] = RGB{N0f8}(1.0,0.0,0.0)
topo = eeg_topoplot!(topo_axis, N, # averaging all trial of 30 participants on Xth msec
raw.ch_names[1:30];
positions=pos, # produced automatically from ch_names
interpolation=NullInterpolator(),
enlarge=1,
#colorrange = (0, 1), # add the 0 for the white-first color
colormap = cmap[],
label_text=false)
hidedecorations!(current_axis())
hidespines!(current_axis())
num_prev = 0
menu = Menu(f[3, 2], options = raw.ch_names[1:30], default = nothing)#, default = "second")
on(menu.selection) do selected
if selected != nothing
num = findall(x->x==menu.selection[], raw.ch_names[1:30])[]
if num_prev != 0
lines[num_prev].color = "black"
cmap[][num] = RGB{N0f8}(1.0,0.0,0.0)
end
lines[num].color = "red"
cmap[][num] = RGB{N0f8}(1.0,0.0,0.0)
num_prev = num
end
end
notify(menu.selection)
#print(cmap[])
f
We solved this by putting this string at the end of the menu.selection section:
notify(lines)
It works, because lines() automatically creates Observable.

How to arrange text annotations in julia makie in one row at the top?

I want to put text annotations along a line on the top. If I write same numbers (no matter which) in y array text will be aligned across center.
let
f = Figure()
ch = ["Ch2", "Ch3", "Ch17", "Ch18", "Ch19"]
x = Array(0:100:400)
y = [100, 100, 100, 100, 100]
ax = Axis(f[1, 1])
text!(x, y, text = ch, align = (:center, :center),
offset = (0, 0),
color = :black)
f
end
but if I change one item in y array
y = [10, 100, 100, 100, 100]
this happens:
How could I put "Ch2" to the same position on the top with other annotations?
Use ylims!(ax,0,110); to configure your axis.
let
f = Figure(;ylim=[0,110])
ch = ["Ch2", "Ch3", "Ch17", "Ch18", "Ch19"]
x = Array(0:100:400)
y = [100, 100, 100, 100, 100]
ax = Axis(f[1, 1]);
text!(x, y, text = ch, align = (:center, :center),
offset = (0, 0),color = :black)
ylims!(ax,0,110)
f
end

Problem with dynamically changing which command a button calls in tkinter

In this simple calculator GUI, I'm creating a frame template using classes. The frame has 2 labels, 2 entry boxes, and a button. I'd like the button to run a specific command depending on the function_call variable passed when initializing - but this doesn't work. The two_points function should be called for the first object, and one_point should be called for the second. How do I dynamically change which command is called based on which object I'm using? Thank you for taking the time to read this.
from tkinter import *
root = Tk()
root.title("Simple Slope Calculator")
class Slope_Calc:
# Variable info that changes within the frame
def __init__(self, master, num_1, num_2, frame_name, label_1_name, label_2_name, function_call):
self.num_1 = int(num_1)
self.num_2 = int(num_2)
self.frame_name = frame_name
self.label_1_name = label_1_name
self.label_2_name = label_2_name
self.function_call = function_call
# Frame template
self.frame_1 = LabelFrame(master, text = self.frame_name, padx = 5, pady = 5)
self.frame_1.grid(row = self.num_1, column = self.num_2, padx = 10, pady = 10)
self.label_1 = Label(self.frame_1, text = self.label_1_name)
self.label_1.grid(row = 0, column = 0)
self.entry_1 = Entry(self.frame_1)
self.entry_1.grid(row = 0, column = 1)
self.label_2 = Label(self.frame_1, text = self.label_2_name)
self.label_2.grid(row = 1, column = 0)
self.entry_2 = Entry(self.frame_1)
self.entry_2.grid(row = 1, column = 1)
self.calc_button = Button(self.frame_1, text = "Calculate", command = self.function_call) # This is what doesn't work
self.calc_button.grid(row = 1, column = 2, padx = 5)
# Strips string of spaces and parentheses
# Returns a list of relevant ordered pair
def strip_string(self, entry_num):
ordered_pair = entry_num.get().split(", ")
ordered_pair[0] = ordered_pair[0].replace("(", "")
ordered_pair[1] = ordered_pair[1].replace(")", "")
return(ordered_pair)
# Calculates slope based on one point and y-intercept
def one_point(self):
pair_1 = self.strip_string(self.entry_1)
b = int(self.entry_2.get())
m = (int(pair_1[1]) - b)/(float(pair_1[1]))
label_3 = Label(self.frame_1, text = "SLOPE-INTERCEPT EQUATION: y = " + str(m) + "x + " + str(b))
label_3.grid(row = 2, column = 0, columnspan = 2)
# Calculates slope based on two points given
def two_points(self):
pair_1 = self.strip_string(self.entry_1)
pair_2 = self.strip_string(self.entry_2)
m = (int(pair_2[1]) - int(pair_1[1]))/float(int(pair_2[0]) - int(pair_1[0]))
b = (int(pair_1[1])) - (m*int(pair_1[0]))
label_3 = Label(self.frame_1, text = "SLOPE-INTERCEPT EQUATION: y = " + str(m) + "x + " + str(b))
label_3.grid(row = 2, column = 0, columnspan = 2)
# Calling each object
two_p = Slope_Calc(root, 0, 0, "Two Points", "First Ordered Pair", "Second Ordered Pair", "two_points")
one_p = Slope_Calc(root, 0, 1, "One Point and Y-Intercept", "Ordered Pair", "Y-intercept", "one_point")
root.mainloop()
The command keyword argument of the Button constructor is supposed to be a function.
Here you give it instead a string which is the name of the method of self that should be called. So you must first get this method using setattr to be able to call it. This should do it:
def call():
method = getattr(self, self.function_call)
method()
self.calc_button = Button(
self.frame_1,
text = "Calculate",
command = call)
You then have an error in strip_string but that's another story.

Python random forest ML model wth tkinter gui

I am very new to programming would really appreciated some help. I have developed a ML model using RandomForest. My code works fine when I run my model standalone, but when I try to send data to my code using Tkinter wrapper function I get the value error.
My model code is as follows
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from joblib import dump, load
from sklearn.ensemble import RandomForestRegressor
housing = pd.read_csv("housing_data.csv")
train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
splitter = StratifiedShuffleSplit(n_splits = 1, test_size = 0.2, random_state=42)
for train_index, test_index in splitter.split(housing, housing['CHAS']):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
median = housing["RM"].median()
housing["RM"].fillna(median)
housing = strat_train_set.drop("MEDV", axis = 1)
housing_labels = strat_train_set["MEDV"].copy()
my_pipeline = Pipeline([
('imputer', SimpleImputer(strategy = "median")), #imputer takes the median value and fills all the blank fields
('std_scaler', StandardScaler()),
])
housing_pip = my_pipeline.fit_transform(housing)
print(housing_pip.shape)
model_random_forest = RandomForestRegressor()
model_random_forest.fit(housing_pip, housing_labels)
dump(model_random_forest, 'Dragon.joblib')
I am using a fucntion to enter the values and get the predictions. Function code is as follows
a=[]
b=[]
c=[]
d=[]
e=[]
f=[]
g=[]
h=[]
i=[]
j=[]
k=[]
l=[]
m=[]
def predictor(array = np.array([[a],[b],[c],[d],[e],[f],[g],[h],[i],[j],[k],[l],[m]])):
print(model_random_forest.predict(array))
predictor([[1,2,3,4,5,6,7,8,9,10,11,12,13]])
Code works absolutely fine but when I use Tkinter GUI wrapper function to send the values to this function it gives ValueError: Number of features of the model must match the input. Model n_features is 13 and input n_features is 1
My Tkinter wrapper function is as follows
def make_predict():
test.predictor([[crim.get()],[zn.get()],[indus.get()],[chas.get()],[nox.get()],[rm.get()],[age.get()],[dis.get()],[rad.get()],[tax.get()],[ptratio.get()],[b.get()],[lstat.get()]])
crim.get, zn.get etc. are entry boxes in tkinter. Guys I would really appreciate your help. I am new to programming and have already spen lots of time solving this error.
Just in case I am also pasting my complete Tkinter code below
from tkinter import*
import numpy as np
import test
window = Tk()
def make_predict():
test.predictor([[crim.get()],[zn.get()],[indus.get()],[chas.get()],[nox.get()],[rm.get()],[age.get()],
[dis.get()],[rad.get()],[tax.get()],[ptratio.get()],[b.get()],[lstat.get()]])
#t1.delete(0,END)
#t1.insert(END,(model_random_forest.predict(features)))
window.title("Property Price Predictor")
window.geometry('500x800')
mainLabel = Label(window, text="Property Price Predictor", font=("Arial Bold", 20))
mainLabel.grid(row=2, columnspan=8)
crim=StringVar()
e1 = Entry(window, width = 25, textvariable=crim) #crim
e1.grid(row = 3, column = 2)
l1 = Label(window, text = 'PER CAPITA CRIME RATE BY TOWN')
l1.grid(row = 4, column = 2)
zn = StringVar()
e2 = Entry(window, width = 25, textvariable=zn) #ZN
e2.grid(row = 6, column = 2)
l2 = Label(window, text = 'PROPORTION OF RESIDENTIAL LAND ZONED FOR LOTS OVER 25,000 SQ.FT.')
l2.grid(row = 7, column = 2)
indus=StringVar()
e3 = Entry(window, width = 25, textvariable=indus) #INDUS
e3.grid(row = 9, column = 2)
l3 = Label(window, text = 'PROPORTION OF NON-RETAIL BUSINESS ACRES PER TOWN')
l3.grid(row = 10, column = 2)
chas=StringVar()
e4 = Entry(window, width = 25, textvariable=chas) #CHAS
e4.grid(row = 12, column = 2)
l4 = Label(window, text = 'CHARLES RIVER DUMMY VARIABLE (= 1 IF TRACT BOUNDS RIVER; 0 OTHERWISE)')
l4.grid(row = 13, column = 2)
nox=StringVar()
e5 = Entry(window, width = 25, textvariable=nox) #NOX
e5.grid(row = 15, column = 2)
l5 = Label(window, text = 'NITRIC OXIDES CONCENTRATION (PARTS PER 10 MILLION)')
l5.grid(row = 16, column = 2)
rm=StringVar()
e6 = Entry(window, width = 25, textvariable=rm) #RM
e6.grid(row = 18, column = 2)
l6 = Label(window, text = 'AVERAGE NUMBER OF ROOMS PER DWELLING')
l6.grid(row = 19, column = 2)
age=StringVar()
e7 = Entry(window, width = 25, textvariable=age) # AGE
e7.grid(row = 21, column = 2)
l7 = Label(window, text = 'PROPORTION OF OWNER-OCCUPIED UNITS BUILT PRIOR TO 1940')
l7.grid(row = 22, column = 2)
dis=StringVar()
e8 = Entry(window, width = 25, textvariable=dis) #DIS
e8.grid(row = 24, column = 2)
l8 = Label(window, text = 'WEIGHTED DISTANCES TO FIVE BOSTON EMPLOYMENT CENTRES')
l8.grid(row = 25, column = 2)
rad=StringVar()
e9 = Entry(window, width = 25, textvariable=rad) #RAD
e9.grid(row = 27, column = 2)
l9 = Label(window, text = 'INDEX OF ACCESSIBILITY TO RADIAL HIGHWAYS')
l9.grid(row = 28, column = 2)
tax=StringVar()
e10 = Entry(window, width = 25, textvariable=tax ) #TAX
e10.grid(row = 30, column = 2)
l10 = Label(window, text = 'FULL-VALUE PROPERTY-TAX RATE PER $10,000')
l10.grid(row = 31, column = 2)
ptratio=StringVar()
e11 = Entry(window, width = 25, textvariable=ptratio) #PTRATIO
e11.grid(row = 33, column = 2)
l11 = Label(window, text = 'PUPIL-TEACHER RATIO BY TOWN')
l11.grid(row = 34, column = 2)
b=StringVar()
e12 = Entry(window, width = 25, textvariable=b) #B
e12.grid(row = 36, column = 2)
l12 = Label(window, text = '1000(BK - 0.63)^2 WHERE BK IS THE PROPORTION OF BLACKS BY TOWN')
l12.grid(row = 37, column = 2)
lstat=StringVar()
e13 = Entry(window, width = 25, textvariable=lstat) #LSTAT
e13.grid(row = 39, column = 2)
l13 = Label(window, text = '% LOWER STATUS OF THE POPULATION')
l13.grid(row = 40, column = 2)
t1 = Text(window, height = 1, width = 20)
t1.grid(row = 45, column = 2)
l15 = Label(window, text = 'PREDICTION')
l15.grid(row = 46, column = 2)
db1 = Button(window, text = 'PREDICT', width=20, command = make_predict)
db1.grid(row=48, column=2)
window.mainloop()
Your housing dataset most probably has missing values
you need to drop the columns with missing values instead of imputing them.
Here is the code:
First check for the missing values in your dataset
housing_train = X_train
missing_values_columns = [col for col in housing_train.columns
if housing_train[col].isnull().any()]
housing_transformed = X_test.drop(missing_values_columns, axis=1
model_random_forest = RandomForestRegressor()
model_random_forest.fit(housing_transformed, housing_labels)

Attaching a scrollbar to a listbox

I know that there have been some other questions about this, but was hoping to get some help with my current frame configuration as seen below in the code snippet. I have also attached some images, first is with no scrollbar set up. Second is when I uncommented out my scrollbar code.
Frame setup:
# -- Top Frame -- #
self.top = Frame(master, height = 71, bg = self.topColor)
self.top.pack(fill = X)
self.bottom = Frame(master, height = 650, bg = self.bottomColor)
self.bottom.pack(fill = X)
Listbox setup:
# myscroll = Scrollbar(self.bottom, orient = VERTICAL)
Label(self.bottom, text = 'Files Chosen:', bg = self.bottomColor).place(x = 4, y = 110)
self.qListBox = Listbox(self.bottom, width = 30, selectmode = SINGLE) # I did have yscrollcommand = myscroll
# myscroll.config(command = self.qListBox.yview)
# myscroll.pack(side = RIGHT, fill = Y)
self.qListBox.place(x = 4, y = 130)
Label(self.bottom, text = 'Deployment Queue:', bg = self.bottomColor).place(x = 360, y = 110)
self.dListBox = Listbox(self.bottom, width = 30, selectmode = MULTIPLE)
self.dListBox.place(x = 360, y = 130)
Figured out how to resolve this. Created three frames that are inside of my master frame as seen below:
my_frame = Frame(self.master)
my_secondF = Frame(self.master)
my_thirdF = Frame(self.master)
Once I did this I simply put my Lisboxes inside of those frames and placed them accordingly and configured my scrollbars
self.qListBox = Listbox(my_frame, yscrollcommand=myscroll_bar, width = 32, selectmode = SINGLE)
I still, however, appreciate all the replies :)

Resources