i want to delete dataframe unnamed in red arrow , and the i want to add some text when i click submit i have index from 1 not in 0 like this
Data_entry.xlsx
can you give me solution about this problem ?
in above my code in python 3
import PySimpleGUI as sg
import pandas as pd
# importing openpyxl module
import openpyxl
# Give the location of the file
path = "C:\\Users\\Admin\\Desktop\\WEB\\PYTHON_PYSIMPLEGUI\\Data_Entry.xlsx"
sg.theme('DarkGreen7')
EXCEL_FILE = 'Data_Entry.xlsx'
df = pd.read_excel(EXCEL_FILE)
my_img = sg.Image(r'C:\Users\master\Desktop\WEB\PYTHON_PYSIMPLEGUI\logo.png')
"""
# Template Taskbar
menu_def = [['File', ['Open', 'Save', 'Exit',]],
['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
['Help', 'About...'],]
"""
menu_def = [['File', ['Exit']],['Help', 'About...'],]
layout = [
[sg.Menu(menu_def)],
[sg.Column([[my_img]], justification='center')],
[sg.Text('Simacan ( SIstem Monitoring And Controling Absen Nilai')],
[sg.Text('Nama', size=(15,1)), sg.InputText(key='Nama')],
[sg.Text('Kehadiran', size=(15,1)), sg.Combo(['Hadir', 'Sakit', 'Tidak Masuk'], key='Keterangan')],
[sg.Submit(), sg.Exit()]
]
window =sg.Window('Aplikasi Simacan versi 1.2', layout,size=(800, 600), font='Courier 12')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'Submit':
df = df.append(values, ignore_index=True)
df.to_excel(EXCEL_FILE, index=True)
sg.popup('Data saved !')
print(event, values)
window.close()
There's are some issues here.
Create a blank excel file to store your data.
Open excel file as a dataframe, option index_col set the index column or you may get Unnamed: 0 column as index in your dataframe.
df = pd.read_excel(EXCEL_FILE, index_col=[0])
There's one extra item 0 in dictionary values, it is the key of sg.Menu, should remove it before you append the values to your dataframe by
del values[0]
You can re-index your dataframe by
df.index = np.arange(1, len(df)+1)
You can save dataframe to your excel file only before end of you script, of course, write each new record to your excel file is still fine.
Related
I'm trying to export in an existing file a row of datas in sheet1 every time a person complete the form but I also have a button to visualize some cells in sheet2. Every time I try to entry information the file got corrupted and tries to save the most data and no info is exported. Maybe I need to active 2 sheets at different times?
EXCEL_FILE = 'example.xlsx'
df = pd.read_excel(EXCEL_FILE)
workbook = load_workbook(filename='example.xlsx')
workbook.sheetnames
workbook.active = workbook['sheet2']
sheet = workbook.active
layout = [
[sg.Text('Por favor rellenar los siguientes campos:')],
[sg.Text('Fecha de Inicio', size=(15,1)), sg.InputText(key='Fecha de Inicio')],
[sg.Text('Hora de Inicio', size=(15,1)), sg.InputText(key='Hora de Inicio')]]
def clear_input():
for key in values:
window[key]('')
return None
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Salir':
break
if event == 'Limpiar':
clear_input()
if event == 'Confirmar':
wb = load_workbook('example.xlsx')
df = df.append(values, ignore_index=True)
df.to_excel('example.xlsx', index=False)
wb.save('example.xlsx')
sg.popup('Informe enviado!')
clear_input()
if event == 'Visualizar':
for value in sheet.iter_rows(min_row=1,
max_row=20,
min_col=1,
max_col=3,
values_only=True):
sg.Print(value)
window.close()
I am New in pandas and streamlit , What I am trying is to filter such a dataframe using streamlit selectbox
but unfortunately everything is going well except that when changing the filter value it does not reflect on the shown table
as you could see the name in the filter does not update the table
here is the code I have used:
import xlrd
import pandas as pd
import os
from datetime import datetime
import streamlit as st
# import plotly_express as px
# to refer to the file
# change the current directory
currentDir = os.chdir('C:\\Users\\user\\Desktop\\lists');
files=os.listdir(currentDir)
columns=['Name','status','memorize-from-surah','memorize-from-ayah','memorize-to-surah','memorize-to-ayah','memorization-grade','words-meaning-grade','revision-from-surah','revision-from-ayah','revision-to-surah','revision-to-ayah','revision-grade']
folderDF=pd.DataFrame()
for file in files:
# get the file name without extension for the sheikh name
sheikh=os.path.splitext(file)[0]
sheetDF=pd.DataFrame()
workbook = pd.ExcelFile(f'C:\\users\\user\\Desktop\\lists\\{file}')
sheets_numbers = len(workbook.sheet_names)
print(sheets_numbers)
for i in range(1, sheets_numbers-1):
# print(workbook.sheet_by_index(i).name)
current_sheet = pd.read_excel(file,sheet_name=i,header=None,index_col=1)
date= current_sheet.iloc[6, 10]
# for j in range(7,current_sheet.nrows):
# if current_sheet.cell(j,3).value=="غاب" or current_sheet.cell(j,3).value=="عذر":
# for k in range(4,current_sheet.ncols):
# current_sheet.cell(j,k).value=""
sheets=pd.read_excel(file,sheet_name=i,skiprows=11,header=None,index_col=1)
# df = pd.DataFrame(sheets.iloc[:,1:], index=index)
#remove the first col
df=pd.DataFrame(sheets.iloc[:,1:])
#remove empty rows
df=df[df.iloc[:,0].notna()]
#rename the columns
df.columns = columns
#get the nrows
nrows= len(df.index)
sheikhCol=pd.Series(nrows*sheikh)
dateCol=pd.Series(nrows*date)
halkaCol=pd.Series(nrows*i)
# df.insert(1,"sheikh",sheikhCol)
df.insert(1,"halka",halkaCol)
df.insert(2,"sheikh",sheikhCol)
df.insert(3,"date",dateCol)
df["sheikh"]=sheikh
df['date']=date
df['halka']=i
if i == 1:
sheetDF=pd.DataFrame(df)
datatoexcel = pd.ExcelWriter('C:\\users\\user\\Desktop\\dataOut.xlsx')
sheetDF.to_excel(datatoexcel)
datatoexcel.save()
else:
sheetDF = pd.concat([sheetDF, df], axis=0)
folderDF=pd.concat([folderDF,sheetDF],axis=0)
datatoexcel=pd.ExcelWriter('C:\\users\\user\\Desktop\\dataOut.xlsx')
folderDF.to_excel(datatoexcel)
datatoexcel.save()
#
# setting up the streamlit page
st.set_page_config(page_title='makraa reports',layout='wide')
# make filteration
#
st.sidebar.header("make filtration criteria")
nameFilter= folderDF['Name'].unique()
halkaFilter= folderDF['halka'].unique()
sheikhFilter= folderDF['sheikh'].unique()
student_choice= st.sidebar.selectbox("select the student Name",nameFilter)
halka_choice= st.sidebar.selectbox("select the halka Number",halkaFilter)
sheikh_choice= st.sidebar.selectbox("select the sheikh Number",sheikhFilter)
# student_choice2= st.sidebar.multiselect("select the student Name",options=nameFilter,default=nameFilter)
# filteredDf=folderDF[folderDF["Name"]== student_choice]
filteredDf = folderDF[(folderDF["Name"] == student_choice) & (folderDF["halka"] == halka_choice)]
# filteredDf=folderDF.query('Name==#student_choice')
st.write(filteredDf)
note st.dataframe(filteredDf) does not make any difference
the streamlit version I used is 0.75 , since the recent version gave me the StreamlitAPIException like that enter link description here
could you give a hand in this
Here is a sample code with example data.
Code
import streamlit as st
import pandas as pd
data = {
'Name': ['a', 'b', 'c'],
'halka': [1, 2, 3]
}
st.set_page_config(page_title='makraa reports',layout='wide')
folderDF = pd.DataFrame(data)
# make filteration
#
st.sidebar.header("make filtration criteria")
nameFilter = folderDF['Name'].unique()
halkaFilter = folderDF['halka'].unique()
# sheikhFilter = folderDF['sheikh'].unique()
student_choice = st.sidebar.selectbox("select the student Name", nameFilter)
halka_choice = st.sidebar.selectbox("select the halka Number", halkaFilter)
# sheikh_choice= st.sidebar.selectbox("select the sheikh Number",sheikhFilter)
# student_choice2= st.sidebar.multiselect("select the student Name",options=nameFilter,default=nameFilter)
filteredDf = folderDF[(folderDF["Name"] == student_choice) & (folderDF["halka"] == halka_choice)]
# filteredDf = filteredDf[filteredDf["halka"] == halkaFilter]
st.write(filteredDf)
Output
Hi I am in process of writing a python code to input search and edit data into excel.
my chosen format for the UI is PySimpleGUI and my xlsx package is openpyxl.
I have been coding for approximately 3 weeks.
I probably bit off more than I can chew but I won't give up.
I need to know why my for loop won't work so I can fix it.
here is the offending code:
import PySimpleGUI as sg
import pandas as pd
import openpyxl as op
def weekly_wage():
filename = 'Payroll.xlsx'
wb = op.load_workbook(filename, data_only=True)
ws = wb.worksheets[0]
ws_tables = []
layout = [
[sg.Text('Employee Name', size=(15,1), font=('ariel', 16)), sg.InputText(key='-Name-', font=('ariel',16))],
[sg.Text('Week Ending', size=(15,1), font=('ariel',16)), sg.InputText(key='-Date-', font=('ariel',16))],
[sg.Submit(font=('ariel', 16))],
[sg.Text('The Weekly Wage is:', font=('ariel', 16))],
[sg.Output(size=(10, 1))]
]
window = sg.Window('Gross Wages Search', layout, size=(450,250))
# Event Loop
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
if event == 'Submit':
if event == 'Submit':
key1 = window['-Name-'] # this gives a callable object to the Input keys
key2 = window['-Date-']
rows = ws.iter_rows()
name = []
date = []
gross = []
for a,b,aw in rows:
name.append(a)
date.append(b)
gross.append(aw)
if a.value == key1 and b.value == key2:
print (aw.value)
break
else:
print('Try Again')
break
window.close()
weekly_wage()
I have poored over the openpyxl docs for hours per night, and I have performed that many google searches I now have shares!!
I have created a small form with ipywidgets. The sample code can be run in Jupyter or Google colab.
Each time the form is filled and the button is clicked a row gets added to a dataframe. Subsequently the dataframe gets displayed.
My problem is that the output displays the new updated dataframe on top of the old one. What I want is that the new display output overwrites the old one. See image description here.
import ipywidgets as widgets
from ipywidgets import HBox, Label
from ipywidgets import Layout, Button, Box, FloatText, Textarea, Dropdown, Label, IntSlider
import time
import pandas as pd
#Create DF
df = df = pd.DataFrame(columns = ['Dropdown_column', 'Float_column'])
df
# Layout
form_item_layout = Layout(
display='flex',
flex_flow='row',
justify_content='space-between',
)
button_item_layout = Layout(
display='flex',
flex_flow='row',
justify_content='center',
padding = '5%'
)
# Dropdown item
drop_down_input = 'Dropdown_input_1'
drop_down = widgets.Dropdown(options=[('Dropdown_input_1', 'Dropdown_input_1'), ('Dropdown_input_2','Dropdown_input_2'), ('Dropdown_input_3', 'Dropdown_input_3')])
def dropdown_handler(change):
global drop_down_input
print('\r','Dropdown: ' + str(change.new),end='')
drop_down_input = change.new
drop_down.observe(dropdown_handler, names='value')
# FloatText item
float_input = 0
FloatText = widgets.FloatText()
def IntText_handler(change):
global float_input
print('\r','Float text:' + str(change.new),end='')
float_input = change.new
FloatText.observe(IntText_handler, names='value')
# Button
button = widgets.Button(description='Add row to dataframe')
out = widgets.Output()
def on_button_clicked(b):
global df
button.description = 'Row added'
time.sleep(1)
with out:
new_row = {'Dropdown_column': drop_down_input, 'Float_column': float_input}
df = df.append(new_row, ignore_index=True)
button.description = 'Add row to dataframe'
display(df)
button.on_click(on_button_clicked)
# Form items
form_items = [
Box([Label(value='Dropdown'),
drop_down], layout=form_item_layout),
Box([Label(value='FloatText'),
FloatText], layout=form_item_layout),
Box([Label(value=''), button],
layout=button_item_layout),
]
form = Box(form_items, layout=Layout(
display='flex',
flex_flow='column',
border='solid 1px',
align_items='stretch',
width='30%',
padding = '1%'
))
display(form)
display(out)
I have tried using the print() function in combination with '/r' and changing #button part of my code.
Change:
display(df)
to
print('\r',str(df), end='')
or
print(str(df), end='\r')
But this does not work either.
Does somebody have any idea what to do?
\r works only for single line of normal text but df is not displayed as normal text (and it is not single line) but as HTML code.
You have to use out.clear_output() to remove previous content.
with out:
new_row = {'Dropdown_column': drop_down_input, 'Float_column': float_input}
df = df.append(new_row, ignore_index=True)
button.description = 'Add row to dataframe'
out.clear_output() # <---
display(df)
You can see more about out.clear_output() in documentation:
Output widgets: leveraging Jupyter’s display system
I would like for tab 2 to show a table of all existing reservations.
I have tried making the dataframe a string and then a list.
import pandas as pd
from pandas import DataFrame
#create dataframe to simulate databse with names and dates
data = {'Name': ['Joe Smith', 'Jason Leary','Bill Murray'],
'Start Date': ['2019/10/01', '2019/11/01','2019/12/01'],
'End Date': ['2019/10/15', '2019/11/15','2019/12/15']
}
df = pd.DataFrame (data, columns = ['Name','Start Date','End Date'])
Data_Table = df.to_string()
# Stuff inside window
tab1_layout = [
[sg.Text('The Scheduler')],
[sg.Combo(name, size=(30,4), enable_events=True)],
[sg.Combo(reason, size=(30,4), enable_events=True)],
[sg.T('Start Date')],
[sg.In('', size=(10,1), key='input1')],
[sg.CalendarButton('Choose Start Date', target='input1', key='date1',format='%Y/%m/%d')],
[sg.T('End Date')],
[sg.In('', size=(10,1), key='input2')],
[sg.CalendarButton('Choose End Date', target='input2', key='date2', format='%Y/%m/%d')],
[sg.Button('Submit')]]
# create a table to show names and dates with an export to CSV button
tab2_layout = [[sg.Table(values=Data_Table, max_col_width=25, background_color='lightblue',
auto_size_columns=True, justification='right', alternating_row_color='blue', key='_table_')],
[sg.Button('Update')]]
tab3_layout = [[sg.T('This is inside tab 3')],
[sg.In(key='_in3_')]]
# create the window
layout = [[sg.TabGroup([[sg.Tab('Scheduler', tab1_layout, key='_mykey_'),
sg.Tab('Schedule', tab2_layout),
sg.Tab('Admin', tab3_layout)]],
key='_group2_', title_color='darkgrey',
selected_title_color='black', tab_location='topleft')]]
window = sg.Window('My window with tabs', default_element_size=(30,1)).Layout(layout)
# event loop to process events and get the values of inputs
while True:
event, values = window.Read()
print(event, values)
if event in (None, 'Exit'):
break
if event == 'Update':
window.FindElement('_table_').Update( row_colors=((8,'white', 'red'), (9,'black')))
window.Close()
I would like for a table to show on tab 2 with existing reservations. Ultimately this will come from a db but for now I have created a pd.DataFrame.
The error is
TclError: Invalid column index
But I have tried strings and lists.
In sg.table you need to include:
headings = header_list
header_list = [str(x) for x in range(len(data[0]))]
tab2_layout = [[sg.Table(values=Data_Table, max_col_width=25,
background_color='lightblue',
auto_size_columns=True,
justification='right',alternating_row_color='blue',
key='_table_', headings = header_list)]
[sg.Button('Update')]]
For more Details See:
https://repl.it/#PySimpleGUI/Table-Element