Applied Data Science with Python - Assignment 2.3: clicking on chart to select Y values
Hey all, I have the following code below: import pandas as pd import numpy as np from scipy import stats np.random.seed(12345) scores = [np.random.normal(32000,20,3650).mean(), np.random.normal(43000,10,3650).mean(),np.random.normal(43500,14,3650).mean(), np.random.normal(48000,7,3650).mean()] standarderrors1992 = stats.sem(np.random.normal(32000,20,3650)) standarderrors1993 = stats.sem(np.random.normal(43000,10,3650)) standarderrors1994 = stats.sem(np.random.normal(43500,14,3650)) standarderrors1995 = stats.sem(np.random.normal(48000,7,3650)) add1992 = 1.96*standarderrors1992 add1993 = 1.96*standarderrors1993 add1994 = 1.96*standarderrors1994 add1995 = 1.96*standarderrors1995 mean1992 = np.random.normal(32000,20,3650).mean() mean1993 = np.random.normal(43000,10,3650).mean() mean1994 = np.random.normal(43500,14,3650).mean() mean1995 = np.random.normal(48000,7,3650).mean() labels = [1992,1993,1994,1995] add = [add1992,add1992,add1994,add1995] 1. This first part organises the raw data. limits = [] def onclick(event): plt.cla() plt.bar(df["index"].values,df["values"].values,align='center', alpha=0.5,yerr=add) plt.xticks(labels) limit = event.ydata limits.append(limit) if len(limits) >= 1: plt.gcf().canvas.mpl_disconnect(plt.gcf().canvas.mpl_connect('button_press_event', onclick)) plt.gcf().canvas.mpl_connect('button_press_event', onclick) 2. This next part allows the user to press on the graph to select a Y value. This should be assigned to the variable 'limits' dict = {mean1992:add1992,mean1993:add1993,mean1994:add1994,mean1995:add1995} colourofbars = [] for key,value in dict.items(): if limits[0] > (key+(value)): colour = 1 colourofbars.append(colour) elif limits[0] < (key-(value)): colour = 0 colourofbars.append(colour) elif (limits[0] < (key+(value))) & (limits[0] > (key-(value))): colour = ((key+(value))-limits[0])/((key+value)-(key-value)) colourofbars.append(colour) df["colourofbars"] = colourofbars 3. Here, the list 'colourofbars' is appended based on the data above, and added as a column to the dataframe 'df'. cmap = plt.cm.rainbow norm = matplotlib.colors.Normalize(vmin=1.5, vmax=4.5) plt.bar(df.index,df.values,color=cmap(norm(df.colourofbars.values)),align='center', alpha=0.5,yerr=add) plt.xticks(labels) sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) plt.gcf().colorbar(sm) plt.show() 4. Here, a different colour is assigned to each bar in the bar chart depending on the values in the column 'colourofbars'. I then try to plot a legend showing this colour gradient scale. *However,* I keep getting the error: IndexError: list index out of range. Could anyone give me a helping hand as to where I am going wrong? Am I on the right lines? -- https://mail.python.org/mailman/listinfo/python-list
Re: Applied Data Science with Python - Assignment 2.3: clicking on chart to select Y values
On Sat, Jun 6, 2020 at 7:26 PM Caledonian26 wrote: > *However,* I keep getting the error: IndexError: list index out of range. > Could anyone give me a helping hand as to where I am going wrong? Am I on the > right lines? > Python always gives you a wealth of information with an exception. Most notably, you get a traceback, which tells you where the error happened, where that was called from, where THAT was called from, etc, all the way to the start of the program. In order to track down this error, you'll need the traceback. I would recommend copying and pasting it in its entirety; even if you don't (yet) understand how to interpret it, we can help you with that. All the best! ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Applied Data Science with Python - Assignment 2.3: clicking on chart to select Y values
On Saturday, June 6, 2020 at 10:29:46 AM UTC+1, Chris Angelico wrote: > On Sat, Jun 6, 2020 at 7:26 PM Caledonian26 wrote: > > *However,* I keep getting the error: IndexError: list index out of range. > > Could anyone give me a helping hand as to where I am going wrong? Am I on > > the right lines? > > > > Python always gives you a wealth of information with an exception. > Most notably, you get a traceback, which tells you where the error > happened, where that was called from, where THAT was called from, etc, > all the way to the start of the program. In order to track down this > error, you'll need the traceback. I would recommend copying and > pasting it in its entirety; even if you don't (yet) understand how to > interpret it, we can help you with that. > > All the best! > > ChrisA Hey, Here is the full error message: Traceback (most recent call last): File "", line 45, in IndexError: list index out of range -- https://mail.python.org/mailman/listinfo/python-list
Shared library missing from wheel (custom build)
Hi, I'm playing around with generating extension moudle to Python in Go. This is for a blog post - not production ready. The Go code is compiled to a shared library and the Python module is using ctypes to call the Go code in the shared library. I know it's know a classic extension module with PyModule_Create and friends, but that's for later... maybe. The setup.py is defined as --- from subprocess import call from setuptools import Extension, setup from setuptools.command.build_ext import build_ext class build_go_ext(build_ext): def build_extension(self, ext): ext_path = self.get_ext_filename(ext.name) cmd = ['go', 'build', '-buildmode=c-shared', '-o', ext_path] cmd += ext.sources out = call(cmd) if out != 0: raise RuntimeError('Go build failed') setup( name='checksig', version='0.1.0', py_modules=['checksig'], ext_modules=[ Extension('_checksig', ['checksig.go', 'export.go']) ], cmdclass={'build_ext': build_go_ext}, ) --- When I run "python setup.py bdist_wheel", I see that that _checksig.cpython-38-x86_64-linux-gnu.so is being built. But when I look at the content of dist/checksig-0.1.0-cp38-cp38-linux_x86_64.whl it's not there. What am I missing? You can view the whole (WIP) project at https://github.com/ardanlabs/python-go/tree/master/pyext Thanks, Miki -- https://mail.python.org/mailman/listinfo/python-list
Re: Shared library missing from wheel (custom build)
Changed to self.get_ext_full_path(ext.name) and it works now. -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange use of Lambda arrow
Have a look at: https://docs.python.org/3/library/typing.html Il giorno venerdì 5 giugno 2020 18:35:10 UTC+2, Agnese Camellini ha scritto: > Hello to everyone, lately i building up an open source project, with some > collaborator, but one of them cannot contribute any more. He is a solution > architect so he is very skilled (much more than me!). I am now analysing > his code to finish the job but i don't get this use of the lambda arrow, > it's like he is deplaring the returned tipe in the function signature (as > you would do in Java). I have never seen something like this in python.. > > Can someone please explain to me this usage (the part regarding the > question is highlighted in yellow): > > @classmethod > def extract_document_data(cls, file_path : str) -> DocumentData: > """ > Entry point of the module, it extracts the data from the document > whose path is passed as input. > The extraction strategy is automatically chosen based on the MIME > type > of the file. > > @type file_path: str > @param file_path: The path of the document to be parsed. > @rtype: DocumentData > @returns: An object containing the data of the parsed document. > """ > > mime = magic.Magic(mime=True) > mime_type = mime.from_file(file_path) > document_type = DocumentType.get_instance(mime_type) > strategy = cls.strategies[document_type] > return strategy.extract_document_data(file_path) > > > To be more verbose, this is the whole script: > > from enum import Enum > import json > import magic > > import docx > from pdfminer.converter import PDFPageAggregator > from pdfminer.layout import LAParams, LTContainer, LTTextContainer > from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines > from pdfminer.pdfinterp import PDFPageInterpreter > from pdfminer.pdfinterp import PDFResourceManager > from pdfminer.pdfpage import PDFPage > from pdfminer.pdfparser import PDFParser > > > class DocumentType(Enum): > """ > Defines the handled document types. > Each value is associated to a MIME type. > """ > > def __init__(self, mime_type): > self.mime_type = mime_type > > @classmethod > def get_instance(cls, mime_type : str): > values = [e for e in cls] > for value in values: > if value.mime_type == mime_type: > return value > raise MimeNotValidError(mime_type) > > PDF = 'application/pdf' > DOCX = > 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' > > > class MimeNotValidError(Exception): > """ > Exception to be raised when a not valid MIME type is processed. > """ > > pass > > > class DocumentData: > """ > Wrapper for the extracted document data (TOC and contents). > """ > > def __init__(self, toc : list = [], pages : list = [], document_text : > str = None): > self.toc = toc > self.pages = pages > if document_text is not None: > self.document_text = document_text > else: > self.document_text = ' '.join([page.replace('\n', ' ') for page > in pages]) > > def toc_as_json(self) -> str: > return json.dumps(self.toc) > > > class ExtractionStrategy: > """ > Base class for the extraction strategies. > """ > > @staticmethod > def extract_document_data(file_path : str) -> DocumentData: > pass > > > class DOCXExtractionStrategy(ExtractionStrategy): > """ > It implements the TOC and contents extraction from a DOCX document. > """ > > @staticmethod > def extract_document_data(file_path : str) -> DocumentData: > document = docx.Document(file_path) > body_elements = document._body._body > # Selecting only the elements from DOCX XML, > # as they're the only to contain some text. > text_elems = body_elements.xpath('.//w:t') > return DocumentData(document_text = ' '.join([elem.text for elem in > text_elems])) > > > class PDFExtractionStrategy(ExtractionStrategy): > """ > It implements the TOC and contents extraction from a PDF document. > """ > > @staticmethod > def parse_toc(doc : PDFDocument) -> list: > raw_toc = [] > try: > outlines = doc.get_outlines() > for (level, title, dest, a, se) in outlines: > raw_toc.append((level, title)) > except PDFNoOutlines: > pass > return PDFExtractionStrategy.build_toc_tree(raw_toc) > > @staticmethod > def build_toc_tree(items : list) -> list: > """ > Builds the TOC tree from a list of TOC items. > > @type items: list > @param items: The TOC items. > Each item must have the following format: (, description>). > E.g: [(1, 'Contents'), (2, 'Chapter 1'), (2, 'Chapter 2')] > @rtype: list >
Re: Can't download Pygame and Pgzero
Il giorno venerdì 5 giugno 2020 18:35:10 UTC+2, Lily Sararat ha scritto: > To whom it may concern, > I have trouble installing the Pygame and Pgzero on Window. I based on the > instruction on the "Computer Coding Python Games for Kids" by Carol > Vorderman. Nothing works. > I tried Python 3.6.2 as describe in the book and the latest version 3.8.3 > still encounter on the same problem. I really need to get this sorted so my > kid can spend his summer break mastering the coding. > Brgs, Hi Lily, on windows I prefer to start from a complete python distribution where most of the packages are already installed. One possibility is WinPython http://winpython.github.io/ You can install that in a directory without a full system installation. you can find there a "WinPython command Prompt" if you open it you can issue there the command: pip install pgzero pygame should be already installed. Cheers -- https://mail.python.org/mailman/listinfo/python-list
Re: Can't download Pygame and Pgzero
Stop all the message and mails On Sat, 6 Jun 2020, 6:03 pm , wrote: > Il giorno venerdì 5 giugno 2020 18:35:10 UTC+2, Lily Sararat ha scritto: > > To whom it may concern, > > I have trouble installing the Pygame and Pgzero on Window. I based on > the instruction on the "Computer Coding Python Games for Kids" by Carol > Vorderman. Nothing works. > > I tried Python 3.6.2 as describe in the book and the latest version > 3.8.3 still encounter on the same problem. I really need to get this > sorted so my kid can spend his summer break mastering the coding. > > Brgs, > > Hi Lily, > on windows I prefer to start from a complete python distribution where > most of the packages are already installed. > One possibility is WinPython > > http://winpython.github.io/ > > You can install that in a directory without a full system installation. > you can find there a "WinPython command Prompt" if you open it you can > issue there the command: > > pip install pgzero > > pygame should be already installed. > > Cheers > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Can't download Pygame and Pgzero
What? Souvik flutter dev On Sat, Jun 6, 2020, 8:11 PM Tushar Upadhyay wrote: > Stop all the message and mails > > On Sat, 6 Jun 2020, 6:03 pm , wrote: > > > Il giorno venerdì 5 giugno 2020 18:35:10 UTC+2, Lily Sararat ha scritto: > > > To whom it may concern, > > > I have trouble installing the Pygame and Pgzero on Window. I based on > > the instruction on the "Computer Coding Python Games for Kids" by Carol > > Vorderman. Nothing works. > > > I tried Python 3.6.2 as describe in the book and the latest version > > 3.8.3 still encounter on the same problem. I really need to get this > > sorted so my kid can spend his summer break mastering the coding. > > > Brgs, > > > > Hi Lily, > > on windows I prefer to start from a complete python distribution where > > most of the packages are already installed. > > One possibility is WinPython > > > > http://winpython.github.io/ > > > > You can install that in a directory without a full system installation. > > you can find there a "WinPython command Prompt" if you open it you can > > issue there the command: > > > > pip install pgzero > > > > pygame should be already installed. > > > > Cheers > > > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Applied Data Science with Python - Assignment 2.3: clicking on chart to select Y values
On 2020-06-06 10:34, Caledonian26 wrote: On Saturday, June 6, 2020 at 10:29:46 AM UTC+1, Chris Angelico wrote: On Sat, Jun 6, 2020 at 7:26 PM Caledonian26 wrote: > *However,* I keep getting the error: IndexError: list index out of range. Could anyone give me a helping hand as to where I am going wrong? Am I on the right lines? > Python always gives you a wealth of information with an exception. Most notably, you get a traceback, which tells you where the error happened, where that was called from, where THAT was called from, etc, all the way to the start of the program. In order to track down this error, you'll need the traceback. I would recommend copying and pasting it in its entirety; even if you don't (yet) understand how to interpret it, we can help you with that. All the best! ChrisA Hey, Here is the full error message: Traceback (most recent call last): File "", line 45, in IndexError: list index out of range Which is line 45? Are you entering the code at the Python prompt? -- https://mail.python.org/mailman/listinfo/python-list
ElementNotInteracable Exception for Selenium Chrome webdriver
I'm using latest python and latest Selenium chrome webdriver. I'm trying to have a simple code to search in youtube but I'm getting the below error. Can anyone help me? File "search.py", line 8, in searchBox.click() Selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable #MyCodeStartsHere from selenium import webdriver driver = webdriver.Chrome() driver.get('https://youtube.com') searchBox = driver.find_element_by_xpath('//*[@id="search"]') if searchBox.is_enabled(): searchBox.click() searchBox.send_keys("youtube test") searchButton = driver.find_element_by_xpath('//*[@id="search-icon-legacy"]/yt-icon') searchButton.click() else: print("What the heck") #MyCodeEndsHere -- https://mail.python.org/mailman/listinfo/python-list
Re: I was really uncomfort with any programming...
> I was really uncomfort with any programming,but I need to become efficient in python coding please give any tips to make interest in programming.hope your words will helpful to me.thank you Often the best way to make programming interesting is to use it to build something you care about! There are a number of books that can help with this, such as "Invent Your Own Computer Games with Python" by Al Sweigart (through No Starch Press, or free on his website). In the end, programming isn't "for everyone". Anyone may theoretically learn how to do it, even do it well, but that doesn't mean they'll necessarily enjoy it. I'm actually rather curious why you *need* to become "efficient" (proficient?) in Python? Work requirement? By the way, you should put your message the the BODY of the email, not in the subject line. Keep subject lines short. -- Jason C. McDonald (CodeMouse92) Author | Speaker | Hacker | Time Lord Contact info at: https://indeliblebluepen.com PGP key: https://keyserver.pgp.com id="-x-evo-selection-start-marker"> signature.asc Description: This is a digitally signed message part -- https://mail.python.org/mailman/listinfo/python-list
Re: Can I have a class with property named "from"
On 6/5/2020 6:59 PM, Ethan Furman wrote: On 06/05/2020 03:15 PM, MRAB wrote: On 2020-06-05 22:50, Ethan Furman wrote: There is no workaround that allows a keyword to be used except as a keyword, other than making it a string. When faced with this kind of situation myself I use a synonym, like "since", or a translation, like "desde". The usual workaround is to append an underscore: 'from_'. True, but ick. ;-) It's like a dangling preposition. It is, in a sense, standard practice. It is used, for instance, for tcl/tk names that are python keywords. The option / argument name 'in' is written 'in_' when written without quotes in a call. f(in_='.') and f(**{'in':'.'}) have the same effect. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
When creating a nested dictionary of dataframes, how can I name a dictionary based on a list name of the dataframe?
When creating a nested dictionary of dataframes, how can I name a dictionary based on a list name of the dataframe? Given the following: # START CODE import pandas as pd cars = {'Brand': ['Honda Civic','Toyota Corolla'], 'Price': [22000,25000] } df_cars = pd.DataFrame(cars, columns = ['Brand','Price']) trucks = {'Brand': ['GMC Sierra','Ford F-150'], 'Price': [5,48000] } df_trucks = pd.DataFrame(trucks, columns = ['Brand','Price']) list_of_dfs = [df_cars, df_trucks] # Not exactly sure how this code should be: dict_of_dfs = {} for df in list_of_dfs: dict_of_dfs[name_of_df] = {} # Not sure here dict_of_dfs[name_of_df]['results'] = df # Not sure here # END CODE I am trying to use a for loop that performs the following: # START CODE dict_of_dfs['df_cars'] = {} dict_of_dfs['df_cars']['results'] = df_cars dict_of_dfs['df_trucks'] = {} dict_of_dfs['df_trucks']['results'] = df_trucks # END CODE The above code should produce the following desired output: { 'df_cars': { 'results': Brand Price 0 Honda Civic 22000 1 Toyota Corolla 25000}, 'df_trucks': { 'results': Brand Price 0 GMC Sierra 5 1 Ford F-150 48000} } I've read multiple threads, used the module varname, and tried using enumerate() but have been unsuccessful. Thank you! -- https://mail.python.org/mailman/listinfo/python-list
Re: ElementNotInteracable Exception for Selenium Chrome webdriver
emagnun writes: > I'm using latest python and latest Selenium chrome webdriver. I'm > trying to have a simple code to search in youtube but I'm getting the > below error. Can anyone help me? > > File "search.py", line 8, in searchBox.click() > Selenium.common.exceptions.ElementNotInteractableException: Message: > element not interactable > Try checking what kind of element it finds for you (perhaps by logging searchBox.tag_name). There might be multiple elements matching the search criteria. > #MyCodeStartsHere > from selenium import webdriver > > driver = webdriver.Chrome() > driver.get('https://youtube.com') > > searchBox = driver.find_element_by_xpath('//*[@id="search"]') > if searchBox.is_enabled(): > searchBox.click() > searchBox.send_keys("youtube test") > searchButton = > driver.find_element_by_xpath('//*[@id="search-icon-legacy"]/yt-icon') > searchButton.click() > else: > print("What the heck") > #MyCodeEndsHere -- regards, kushal -- https://mail.python.org/mailman/listinfo/python-list