content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Iterating through all files in a root folder to search for specific files using os.walk() I've tried to search previous questions but I couldn't figure out a solution to my problem. I have a root folder that has many different subfolders and files. Each subfolder also has files within them and possibly even anothe...
Iterating through all files in a root folder to search for specific files using os.walk()
I've tried to search previous questions but I couldn't figure out a solution to my problem. I have a root folder that has many different subfolders and files. Each subfolder also has files within them and possibly even another subfolder within that subfolder. I want to iterate through all files in this root folder to f...
[ "Instead of os.walk(), use glob.glob(). It has an option to search recursively through subdirectories.\nfrom glob import glob\nimport os\n\nfor filename in glob.glob(os.path.join(rootFolderPath, \"**\", \"*.xlsx\"), recursive=True):\n xlsx = pd.excelFile(filename)\n counter += 1\n\n" ]
[ 1 ]
[]
[]
[ "os.path", "os.walk", "python" ]
stackoverflow_0074553881_os.path_os.walk_python.txt
Q: Button to next display in matplotlib I have a class object with an attribute display(self): import matplotlib.pyplot as plt class Obj: def display(self) -> None: fig = plt.figure() sub = fig.add_subplot() sub.plot(...) plt.show() def dostuff(self) -> 'stuff': ...
Button to next display in matplotlib
I have a class object with an attribute display(self): import matplotlib.pyplot as plt class Obj: def display(self) -> None: fig = plt.figure() sub = fig.add_subplot() sub.plot(...) plt.show() def dostuff(self) -> 'stuff': ... self.display() ...
[ "plt.show has parameter block. If you set it to False, then the execution is not blocked. Hope this helps.\n" ]
[ 0 ]
[]
[]
[ "class", "debugging", "interface", "matplotlib", "python" ]
stackoverflow_0074553555_class_debugging_interface_matplotlib_python.txt
Q: Gtk has no attribute 'DIALOG_DESTROY_WITH_PARENT' I am trying to create a working dialog box in Python 2.7/GTK+ 3 (PyGObject). I found an online tutorial which offered the following code... md = Gtk.MessageDialog(window, Gtk.DIALOG_DESTROY_WITH_PARENT, Gtk.MESSAGE_INFO, Gtk.BUTTONS_CLOSE, ...
Gtk has no attribute 'DIALOG_DESTROY_WITH_PARENT'
I am trying to create a working dialog box in Python 2.7/GTK+ 3 (PyGObject). I found an online tutorial which offered the following code... md = Gtk.MessageDialog(window, Gtk.DIALOG_DESTROY_WITH_PARENT, Gtk.MESSAGE_INFO, Gtk.BUTTONS_CLOSE, msg) response = md.run() However, running this...
[ "After a little bit of research, I found that, yes, this is due to a change in library structure from PyGTK to PyGObject. (Read the documentation for how to work with dialogs, and see line 27 of the example at that link's bookmark.)\nThe enumeration Gtk.DIALOG_DESTROY_WITH_PARENT does not appear to exist in PyGObje...
[ 10, 0 ]
[]
[]
[ "pygobject", "python" ]
stackoverflow_0027008201_pygobject_python.txt
Q: headless_ie_selenium not working with python I'm trying to change my code to use an IE headless browser. The automation I'm doing is in a website that only works in internet explorer My code was working great until I tried to use a headless browser When I run this code, absolutely nothing happens, no error is thro...
headless_ie_selenium not working with python
I'm trying to change my code to use an IE headless browser. The automation I'm doing is in a website that only works in internet explorer My code was working great until I tried to use a headless browser When I run this code, absolutely nothing happens, no error is thrown # selenium 4 from selenium import webdriver fro...
[ "I believe the reason why it seems nothing is happening is because you have no output (not printing anything). I'm not familiar with your process, but I tried it out with mine also using chrome and it worked fine. Context:\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n driver=...
[ 0 ]
[]
[]
[ "headless_ie_selenium", "headless_selenium_for_win", "python" ]
stackoverflow_0074553201_headless_ie_selenium_headless_selenium_for_win_python.txt
Q: Returning value after recursively iterating through XML I'm working with a very nested XML file and the path is critical for understanding. This answer enables me to print both the path and value: Python xml absolute path What I can't figure out is how to output the result in a more usable way (trying to construct...
Returning value after recursively iterating through XML
I'm working with a very nested XML file and the path is critical for understanding. This answer enables me to print both the path and value: Python xml absolute path What I can't figure out is how to output the result in a more usable way (trying to construct a dataframe listing Path and Value). For example, from the l...
[ "You need to pass the values yielded by the recursive call back to the original caller. So change:\nyield_path_of_elems(child, \"%s/%s\" % (elem_path, child.tag))\n\nto\nyield from yield_path_of_elems(child, \"%s/%s\" % (elem_path, child.tag))\n\nThis is analogous to the way you have to use return recursive_call(.....
[ 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0074553850_elementtree_python_xml.txt
Q: Measure integral between 2 curves (linear func & arbitrary curve) In the img. below my goal is to locate the integral in area 1 / 2 / 3. In that way that I know how much area below the linear line (area 1 / 3), and how much area that are above the linear line (area 2) Im not looking for the exact integral, just an...
Measure integral between 2 curves (linear func & arbitrary curve)
In the img. below my goal is to locate the integral in area 1 / 2 / 3. In that way that I know how much area below the linear line (area 1 / 3), and how much area that are above the linear line (area 2) Im not looking for the exact integral, just an approximately value to measure on. an approx that would work in the sa...
[ "Perhaps you can integrate the absolute difference of both arrays:\n>>> np.trapz(np.abs(y2 - y1))\n7.1417718350001\n\n", "Here is a little bit of code that calculates exactly all the areas, and does so in a vectorized way (fast):\ndef areas(x, y1, y2, details=None):\n dy = y1 - y2\n b0 = dy[:-1]\n b1 = d...
[ 0, 0 ]
[]
[]
[ "area", "curve", "integral", "numpy", "python" ]
stackoverflow_0074549674_area_curve_integral_numpy_python.txt
Q: I want to create a nested dictionary from a csv file with headers as keys This is my csv file: Player Name,2022 Cap Number,Rating,Position Poona Ford,"10,075,000",74,DT Tyler Lockett,"10,050,000",90,WR D.K. Metcalf,"8,838,827",89,WR Gabe Jackson,"7,237,778",79,G Uchenna Nwosu,"6,295,000",79,LB Quandre Diggs,"5,800...
I want to create a nested dictionary from a csv file with headers as keys
This is my csv file: Player Name,2022 Cap Number,Rating,Position Poona Ford,"10,075,000",74,DT Tyler Lockett,"10,050,000",90,WR D.K. Metcalf,"8,838,827",89,WR Gabe Jackson,"7,237,778",79,G Uchenna Nwosu,"6,295,000",79,LB Quandre Diggs,"5,800,000",85,FS I want my output to be: {'Poona Ford': {'2022 Cap Number': '"10075...
[ "Try this:\ncsv_list = [['Player Name', '2022 Cap Number', 'Rating', 'Position'], ['Poona Ford', '\"10075000\"', '74', 'DT'], ['Tyler Lockett', '\"10050000\"', '90', 'WR'], ['D.K. Metcalf', '\"8838827\"', '89', 'WR'], ['Gabe Jackson', '\"7237778\"', '79', 'G'], ['Uchenna Nwosu', '\"6295000\"', '79', 'LB'], ['Quandr...
[ 1 ]
[]
[]
[ "csv", "dictionary", "python" ]
stackoverflow_0074553953_csv_dictionary_python.txt
Q: How do I mock methods of a decorated class in python? Having trouble with applying mocks to a class with a decorator. If I write the class without a decorator, patches are applied as expected. However, once the class is decorated, the same patch fails to apply. What's going on here, and what's the best way to ap...
How do I mock methods of a decorated class in python?
Having trouble with applying mocks to a class with a decorator. If I write the class without a decorator, patches are applied as expected. However, once the class is decorated, the same patch fails to apply. What's going on here, and what's the best way to approach testing classes that may be decorated? Here's a mini...
[ "So, as I stated in the comment, your wrapper function replaces Something in the module module namespace. So, putting your code in module.py on my computer, observe:\n>>> import module\n>>> type(module.Something)\n<class 'function'>\n\nSince you used the functools.wraps decorator, the object being wrapped is added ...
[ 1 ]
[]
[]
[ "patch", "python", "python_unittest" ]
stackoverflow_0074553493_patch_python_python_unittest.txt
Q: Per line index url in requirements.txt Suppose I have the following PyPIs: public PyPi (standard packages) gitlab pypi (because internal team ABC wanted to use this) artifactory PyPi (because contractor team DEF wanted to use this) Now suppose package titled "ABC" exists on all of them, but are not the same thin...
Per line index url in requirements.txt
Suppose I have the following PyPIs: public PyPi (standard packages) gitlab pypi (because internal team ABC wanted to use this) artifactory PyPi (because contractor team DEF wanted to use this) Now suppose package titled "ABC" exists on all of them, but are not the same thing (for instance, "apples," which are 3 entir...
[ "The question gets back to the idea that a package dependency specification usually is a state of need that is independent of how that need should be satisfied.\nSo the dependency declaration “foo==1.0.0” (the thing declared as part of the package metadata) means “I need the package named foo with version 1.0.0\" a...
[ 0 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0074538877_pip_python_python_3.x.txt
Q: Xpath returns empty array - lxml I'm trying to write a program that scrapes https://www.tcgplayer.com/ to get a list of Pokemon TCG prices based on a specified list from lxml import etree, html import requests import string def clean_text(element): all_text = element.text_content() cleaned = ' '.join(all_...
Xpath returns empty array - lxml
I'm trying to write a program that scrapes https://www.tcgplayer.com/ to get a list of Pokemon TCG prices based on a specified list from lxml import etree, html import requests import string def clean_text(element): all_text = element.text_content() cleaned = ' '.join(all_text.split()) return cleaned pag...
[ "Question answered above by @Grismar:\n\nWhen you test the XPath on a site, you probably do this in the Developer Console in the browser, after the page has loaded. At that point in time, any JavaScript will have already executed and completed and the page may have been updated or even been constructed from scratch...
[ 0 ]
[]
[]
[ "lxml", "python", "web_scraping", "xpath" ]
stackoverflow_0074440794_lxml_python_web_scraping_xpath.txt
Q: Pandas - Create multiple new columns if str.contains return multiple value I have some data like this: 0 Very user friendly interface and has 2FA support 1 The trading page is great though with allot o... 2 Widget support 3 But it’s really only for serious ...
Pandas - Create multiple new columns if str.contains return multiple value
I have some data like this: 0 Very user friendly interface and has 2FA support 1 The trading page is great though with allot o... 2 Widget support 3 But it’s really only for serious traders with... 4 The KYC and AML process is painful - it took ... ...
[ "The issue is that you are not actually extracting any of the words. You need to pull the words you want out of the text and then cat them into a new column.\nimport pandas as pd\nfrom io import StringIO\nimport re\n\nTESTDATA = StringIO(\"\"\"Index,reviews,\n0, Very user friendly interface and has 2FA suppor...
[ 0 ]
[]
[]
[ "contains", "pandas", "python" ]
stackoverflow_0074553856_contains_pandas_python.txt
Q: Python monkey patching: instance creation in method of library/object what is the easiest way to solve the following problem in extending/altering the functionality of a third party library? The library offers a class LibraryClass with a function func_to_be_changed. This function has a local variable internal_vari...
Python monkey patching: instance creation in method of library/object
what is the easiest way to solve the following problem in extending/altering the functionality of a third party library? The library offers a class LibraryClass with a function func_to_be_changed. This function has a local variable internal_variable which is the instance of another class SimpleCalculation of that libra...
[ "Some context\nThe first string argument in the patch function can have two different meanings depending on the situation. In the first situation the described object has not been imported and is unavailable to the program which would, therefore, result in a NameError without the mocking. However, in the question, ...
[ 1 ]
[]
[]
[ "mocking", "monkeypatching", "python", "python_3.x" ]
stackoverflow_0074536960_mocking_monkeypatching_python_python_3.x.txt
Q: How to programmatically generate the CREATE TABLE SQL statement for a given model in Django? I need to programmatically generate the CREATE TABLE statement for a given unmanaged model in my Django app (managed = False) Since i'm working on a legacy database, i don't want to create a migration and use sqlmigrate. T...
How to programmatically generate the CREATE TABLE SQL statement for a given model in Django?
I need to programmatically generate the CREATE TABLE statement for a given unmanaged model in my Django app (managed = False) Since i'm working on a legacy database, i don't want to create a migration and use sqlmigrate. The ./manage.py sql command was useful for this purpose but it has been removed in Django 1.8 Do yo...
[ "As suggested, I post a complete answer for the case, that the question might imply.\nSuppose you have an external DB table, that you decided to access as a Django model and therefore have described it as an unmanaged model (Meta: managed = False).\nLater you need to be able to create it in your code, e.g for some ...
[ 15, 6, 0 ]
[]
[]
[ "django", "migration", "python", "sql" ]
stackoverflow_0048666334_django_migration_python_sql.txt
Q: PyPy memory leak with custom C++ extension? I am trying to write a C++ extension with support for CPython and PyPy. My extension involves creating some custom types that support the call interface. However, I appear to be getting memory leaks in PyPy when I raise Python exceptions. I am not getting any memory leak...
PyPy memory leak with custom C++ extension?
I am trying to write a C++ extension with support for CPython and PyPy. My extension involves creating some custom types that support the call interface. However, I appear to be getting memory leaks in PyPy when I raise Python exceptions. I am not getting any memory leaks with regular CPython. I have isolated the leaki...
[ "Hmm, looks like this is a bug in PyPy: https://foss.heptapod.net/pypy/pypy/-/issues/3854\n" ]
[ 0 ]
[]
[]
[ "c++", "pypy", "python", "python_extensions" ]
stackoverflow_0074553376_c++_pypy_python_python_extensions.txt
Q: How to sort lists that contain letters and numbers? I have tried lots of different ways to sort the list, but it never sorts it. list = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american d...
How to sort lists that contain letters and numbers?
I have tried lots of different ways to sort the list, but it never sorts it. list = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP1...
[ "I suggest to use re module to extract name, episode, season etc. The key_function will sort the list by Name, Season, Episode:\nimport re\n\npat = re.compile(r\"(.*) S(\\d+)-EP(\\d+)\")\n\n\ndef key_function(value):\n name, season, episode = pat.search(value).groups()\n return name, int(season), int(episode)...
[ 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0074553992_python_sorting.txt
Q: RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1) Im using a Pytorch Unet model to which i am feeding in a image as input and along with that i am feeding the label as the input image mask and traning the dataset on it. The Unet model i have picked up from somewhere else, and i a...
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
Im using a Pytorch Unet model to which i am feeding in a image as input and along with that i am feeding the label as the input image mask and traning the dataset on it. The Unet model i have picked up from somewhere else, and i am using the cross-entropy loss as a loss function but i get this dimension out of range er...
[ "According to your code:\nprobs_flat = probs.view(-1)\ntargets_flat = targets.view(-1)\nreturn self.crossEntropy_loss(probs_flat, targets_flat)\n\nYou are giving two 1d tensor to nn.CrossEntropyLoss but according to documentation, it expects:\nInput: (N,C) where C = number of classes\nTarget: (N) where each value i...
[ 34, 12, 0, 0 ]
[]
[]
[ "machine_learning", "python", "pytorch" ]
stackoverflow_0048377214_machine_learning_python_pytorch.txt
Q: How can I reset password in django by sending code to the user? How can I implement password reset in django, in a safe and secure way by sending a code to the user's email/phone? I emphasise that I want to do this by sending a code to the user, not a link or anything else. Something like what microsoft or google ...
How can I reset password in django by sending code to the user?
How can I implement password reset in django, in a safe and secure way by sending a code to the user's email/phone? I emphasise that I want to do this by sending a code to the user, not a link or anything else. Something like what microsoft or google accounts does. I've searched a lot for this problem but I've never fo...
[ "I'm not really sure, but I think you can do it with django-phone-verify\nThe example on the website is about first authenticating, but modules API can be reused/extended.\n" ]
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074549054_django_django_rest_framework_python.txt
Q: Getting missing positional parameter errors when using scipy odeint I am attempting to code a basic gravitational 2 body problem (2 bodies of equal mass), by using scipy odeint to solve the differential equations. Code below #N Body test case #%% #import modules import numpy as np import matplotlib.pyplot as pl...
Getting missing positional parameter errors when using scipy odeint
I am attempting to code a basic gravitational 2 body problem (2 bodies of equal mass), by using scipy odeint to solve the differential equations. Code below #N Body test case #%% #import modules import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint #%% #define constants G=6.67e-11 ...
[ "Firstly odeint is old, SciPy recommends using solve_ivp(). Your function should look something like func(y, t, ...) where y is the initial condition array, and t is an array containing time points to calculate. All the other parameters you have to provide yourself through the args parameter of odeint(). With what ...
[ 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0074553893_numpy_python_scipy.txt
Q: Auto expand table range in excel Tying to find to an Excel VBA equivalent to sheet.range('A1').expand('table') #https://docs.xlwings.org/en/stable/datastructures.html I've tried to create a xlwings func like this : @xw.func def expand(rng, caller): sht = caller.sheet return sht.range(rng).expand().addres...
Auto expand table range in excel
Tying to find to an Excel VBA equivalent to sheet.range('A1').expand('table') #https://docs.xlwings.org/en/stable/datastructures.html I've tried to create a xlwings func like this : @xw.func def expand(rng, caller): sht = caller.sheet return sht.range(rng).expand().address =expand("C7") returns "$C$7:$E$8" (w...
[ "You need to call the function directly instead of using xlwings way as they need to correct the code in order to support calling from another function/sub.\nUse this in your function instead of calling expand\n rng_s = Py.CallUDF(\"udftest\", \"expand\", Array(\"C7\", Nothing), ThisWorkbook, ThisWorkbook.ActiveShe...
[ 0 ]
[]
[]
[ "excel", "python", "vba", "xlwings" ]
stackoverflow_0073940796_excel_python_vba_xlwings.txt
Q: Is there a more efficient way to represent my string containing image pixel data as an image mask? I'm representing image pixel data as a string. For example, let's say an image is 2x2 pixels, the string would be 4 characters long since we have 4 pixels. So if the string is 0100 (where 1 is a white pixel), what I ...
Is there a more efficient way to represent my string containing image pixel data as an image mask?
I'm representing image pixel data as a string. For example, let's say an image is 2x2 pixels, the string would be 4 characters long since we have 4 pixels. So if the string is 0100 (where 1 is a white pixel), what I basically want to achieve is to create an image mask from this string. NOTE: I do not have to use 1's an...
[ "To answer the your question of the comments\na = \"0 1 1 0\"\nb = np.fromstring(a, dtype=int, sep=\" \")\nb.reshape(int(len(b)/2), int(len(b)/2))\n\nsomething like this e.g --> results in:\narray([[0, 1], [1, 0]]) \n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074554083_python.txt
Q: Python Data Structure to pop anywhere and push to the end in O(1) I was wondering, is there any python data structure to pop from anywhere (using an object), remove from the front and push to the back in O(1)? To prove its even possible lets look at the next data structure that can be implemented in C: (Notice al...
Python Data Structure to pop anywhere and push to the end in O(1)
I was wondering, is there any python data structure to pop from anywhere (using an object), remove from the front and push to the back in O(1)? To prove its even possible lets look at the next data structure that can be implemented in C: (Notice all the pointers are 2 way) Thus we can: pop(object) - lookup the object ...
[]
[]
[ "Thanks to the comments.\nJust use a regular dict.\nPython dicts keep the order of insertion so:\npop(object) - del dict[Int]\n\npopFront - dict.pop(next(iter(dict.items())))\n\nPushBack - dict[Int] = Object\n\n" ]
[ -1 ]
[ "data_structures", "python" ]
stackoverflow_0074554058_data_structures_python.txt
Q: Registration form is not submitting After trying multiple solutions from other stack overflows, I cannot seem to get my registration form to work in Django. This is the registration form <h1>Register</h1> <div> <form method="POST" action="{% url 'register' %}"></form> {% csrf_token %} ...
Registration form is not submitting
After trying multiple solutions from other stack overflows, I cannot seem to get my registration form to work in Django. This is the registration form <h1>Register</h1> <div> <form method="POST" action="{% url 'register' %}"></form> {% csrf_token %} {{ form.as_p}} <input type="sub...
[ "I think saving the form instance doesn't actually make user an authenticatable User object\nTry this\n if form.is_valid():\n #You are not doing anything to user, so no need to commit=False\n #user = form.save(commit=False)\n form.save()\n username = form.cleaned_data.get('username')\...
[ 0 ]
[]
[]
[ "css", "django", "forms", "html", "python" ]
stackoverflow_0074553017_css_django_forms_html_python.txt
Q: Python and Beautiful Soup nested values I have the following html: <label class="cOpt" for="prod_1234_rMon_3"> <span>12 M <span>+300 €</span></span> </label> How can I get the 12 M and +300 €? Edit: So I tried this to get alle the data I need, but find just picks the first value. vObj_detail = bsObj.find('labe...
Python and Beautiful Soup nested values
I have the following html: <label class="cOpt" for="prod_1234_rMon_3"> <span>12 M <span>+300 €</span></span> </label> How can I get the 12 M and +300 €? Edit: So I tried this to get alle the data I need, but find just picks the first value. vObj_detail = bsObj.find('label', attrs={'class': 'cOpt'}).get_text(strip=T...
[ "You can use .get_text() with separator= and then str.split:\nfrom bs4 import BeautifulSoup\n\n\nhtml_doc = \"\"\"\\\n<label class=\"cOpt\" for=\"prod_1234_rMon_3\"> <span>12 M <span>+300 €</span></span> </label>\"\"\"\n\nsoup = BeautifulSoup(html_doc, \"html.parser\")\n\na, b = soup.find(\"span\").get_text(strip=T...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "web_scraping" ]
stackoverflow_0074554264_beautifulsoup_html_python_web_scraping.txt
Q: How to Shorten a lot of Repetition I am trying to make a game of Tic Tac Toe, and I ran into this problem. I have to store a lot of different variables with very similar characters. Currently, I have a solution, but it seems ineffective. I am trying to find a quicker and easier way of accomplishing the same task. ...
How to Shorten a lot of Repetition
I am trying to make a game of Tic Tac Toe, and I ran into this problem. I have to store a lot of different variables with very similar characters. Currently, I have a solution, but it seems ineffective. I am trying to find a quicker and easier way of accomplishing the same task. Below is a solution I currently have, bu...
[ "Perhaps something like this:\nc = []\np = []\nfor x in range(1,10):\n c.append(PlayerX.count(x))\n p.append(computer0.count(x))\n\n" ]
[ 0 ]
[]
[]
[ "count", "for_loop", "list", "python" ]
stackoverflow_0074554335_count_for_loop_list_python.txt
Q: Linear Regression without Sklearn I am trying to write a class LinearModel, representing a linear regression model. it gives an error for def predict class LinearModel: def __init__(self, X, y): self.X = X self.y = y #X columns of 1s appended on its left, X = np.vstack((np.ones(...
Linear Regression without Sklearn
I am trying to write a class LinearModel, representing a linear regression model. it gives an error for def predict class LinearModel: def __init__(self, X, y): self.X = X self.y = y #X columns of 1s appended on its left, X = np.vstack((np.ones((X.shape[0], )), X.T)).T ...
[ "\nYou can't use a method name as an attribute. Is self.fit supposed to be a method to fit? Or the coefficients?\n\nYou can't test if that attribute (let's call it beta) is assigned simply by saying if self.beta or something similar. First of all, if it is not, you'll get an error for trying to read an unassigned v...
[ 2 ]
[]
[]
[ "linear_regression", "numpy", "python" ]
stackoverflow_0074554177_linear_regression_numpy_python.txt
Q: How to read a parquet file into a PCollection from s3? My problem is simple: I want to read a parquet file from s3 into a PCollection in Apache Beam using the Python Sdk. I know of the apache_beam.io.parquetio module but this one does not seem to be able to read from s3 directly (or does it?). I know of the apache...
How to read a parquet file into a PCollection from s3?
My problem is simple: I want to read a parquet file from s3 into a PCollection in Apache Beam using the Python Sdk. I know of the apache_beam.io.parquetio module but this one does not seem to be able to read from s3 directly (or does it?). I know of the apache_beam.io.aws.s3io module but this one seems to return an s3 ...
[ "if you install beam with the aws requirement\npip install 'apache-beam[aws]'\nYou can just pass in an s3 filename to read from it\nfilename = \"s3://bucket-name/...\nbeam.io.ReadFromParquet(filenam)\n\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "apache_beam", "parquet", "python" ]
stackoverflow_0073283594_amazon_s3_apache_beam_parquet_python.txt
Q: Replace Items in List with Random Items from Dictionary of Lists I have a list of items that may repeat multiple times. Let us say for example list = ['a', 'b', 'c', 'd', 'b', 'a', 'c', 'a'] I also have a dictionary of lists that defines multiple values for each key. Suppose: dict = {'a':[1, 2], 'b':[3, 4], 'c':[...
Replace Items in List with Random Items from Dictionary of Lists
I have a list of items that may repeat multiple times. Let us say for example list = ['a', 'b', 'c', 'd', 'b', 'a', 'c', 'a'] I also have a dictionary of lists that defines multiple values for each key. Suppose: dict = {'a':[1, 2], 'b':[3, 4], 'c':[5, 6], 'd':[7, 8]} I want to be able to: randomly select a value fro...
[ "You can simply use the built-in random.choice and a list comprehension:\n>>> import random\n>>>\n>>> my_list = ['a', 'b', 'c', 'd', 'b', 'a', 'c', 'a']\n>>> my_dict = {'a':[1,2], 'b':[3,4], 'c':[5,6], 'd':[7,8]}\n>>>\n>>> [(key, random.choice(my_dict[key])) for key in my_list]\n[('a', 2), ('b', 3), ('c', 6), ('d',...
[ 0 ]
[]
[]
[ "list", "python", "random" ]
stackoverflow_0074554351_list_python_random.txt
Q: Alien Invasion AttributeError: 'Scoreboard' object has no attribute 'level_img' I can't find the problem in my code, it says that there is an attribute error but i can't find the problem. I need help Here is a github repository link https://github.com/Hunty405/Alien-Invasion the book I'm using "python crash course...
Alien Invasion AttributeError: 'Scoreboard' object has no attribute 'level_img'
I can't find the problem in my code, it says that there is an attribute error but i can't find the problem. I need help Here is a github repository link https://github.com/Hunty405/Alien-Invasion the book I'm using "python crash course" has what it should be and i've tried to fix the code by using the code in it but i ...
[ "The error AttributeError: 'Scoreboard' object has no attribute 'level_image' is saying that your Scoreboard class has no attribute 'level_image'.\nSo, you'll need to add the attribute it to your __init__ function for the that class. You also need to call the function self.prep_level() as it appears that is the fu...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074551618_python.txt
Q: Flask-WTForms: populating a FileField field I have a form using WTF-Forms on Flask such as: class ImageForm(FlaskForm): """Form used for image uploading""" image = FileField( validators=[ FileRequired(), FileAllowed(["png", "jpg", "jpeg"], "This file is not a valid image !"...
Flask-WTForms: populating a FileField field
I have a form using WTF-Forms on Flask such as: class ImageForm(FlaskForm): """Form used for image uploading""" image = FileField( validators=[ FileRequired(), FileAllowed(["png", "jpg", "jpeg"], "This file is not a valid image !",), ], render_kw={"class": "form-...
[ "I know that this is very late, but I'm writing this answer cause I was stuck on the same issue. for security reasons, the browser doesn't accept a prefilled FileField. You need to show the image with html and the keep the FileField for updating the image.\nTo know if the FileField contains a new file storage you c...
[ 0 ]
[]
[]
[ "flask", "flask_wtforms", "python", "werkzeug" ]
stackoverflow_0069312929_flask_flask_wtforms_python_werkzeug.txt
Q: How to merge two dataframes as like "vlookup" with index in pandas df1 index A B C No1 - - - No2 - - - No3 - - - df2 index X Y Z No1 - - z1 No2 - - z2 No3 - - z3 In this case, I would like to make df3 as below df3 index A B C Z No1 - - - z1 No2 - - - z2 No3 - - - z3 I tried that df3 = pd.merge(df1,d...
How to merge two dataframes as like "vlookup" with index in pandas
df1 index A B C No1 - - - No2 - - - No3 - - - df2 index X Y Z No1 - - z1 No2 - - z2 No3 - - z3 In this case, I would like to make df3 as below df3 index A B C Z No1 - - - z1 No2 - - - z2 No3 - - - z3 I tried that df3 = pd.merge(df1,df2["Z"], left_on=True) However, I coul...
[ "what I understood is you want to join the two data frames by their index. if so, then you can use this\ndf1.join(df2)\n\nor simply by\ndf3 = pandas.merge(df1, df2['z'], left_index=True, right_index=True)\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074554423_pandas_python.txt
Q: How do I output a string of characters based on some rules and an initial string of characters? Basically, I want to know how to replace every A, + and - in a string of A's,+'s and -'s based on rules inputted. So if I have a chain of the characters mentioned above, and I input that every A will become A+A, every -...
How do I output a string of characters based on some rules and an initial string of characters?
Basically, I want to know how to replace every A, + and - in a string of A's,+'s and -'s based on rules inputted. So if I have a chain of the characters mentioned above, and I input that every A will become A+A, every - will become -+-, every + will become A-+. How do I "choose" every single one of the characters in th...
[ "You could just make a blank output string variable and then loop through the characters of the initial chain\nIf the character at any given position is 'A', then concatenate the output string with 'A+A'.\nElse if it is '-' concatenate '-+-'.\nElse if it is '+' concatenate 'A-+'.\nElse just add the original charact...
[ 0 ]
[ "Something like this?\noriginal = input(\"Initial Chain: \")\nin1 = input(\"What does A become? \")\nin2 = input(\"What does + become? \")\nin3 = input(\"What does - become? \")\n\nprint(original.replace(\"A\",in1).replace(\"+\",in2).replace(\"-\",in3))\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074554371_python.txt
Q: Sagemaker Local Mode: RuntimeError: Giving up, endpoint: didn't launch correctly While running sagemaker in local mode. I am experimenting with an inference endpoint in local mode using docker container. But as soon as my model.tar.gz file exceeds a certain size i.e. around 200 mb, the deployment fails and returns...
Sagemaker Local Mode: RuntimeError: Giving up, endpoint: didn't launch correctly
While running sagemaker in local mode. I am experimenting with an inference endpoint in local mode using docker container. But as soon as my model.tar.gz file exceeds a certain size i.e. around 200 mb, the deployment fails and returns the error: RuntimeError: Giving up, endpoint: didn't launch correctly When I deploy i...
[ "Instead of using SageMaker SDK Local Mode, you can also run vanilla docker commands yourself to imitate the hosted environment:\nSuch as:\n\nStart \"local endpoint\"\n\nimage=$1\n\ndocker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve\n\n\nInvoke \"local endpoint\"\n\npayload=$1\ncontent=${2:-text...
[ 0 ]
[]
[]
[ "amazon_sagemaker", "amazon_sagemaker_studio", "docker", "docker_compose", "python" ]
stackoverflow_0074453608_amazon_sagemaker_amazon_sagemaker_studio_docker_docker_compose_python.txt
Q: How to disable the header with filename and date when converting .ipynb to pdf with nbconvert? I am using nbconvert for converting my .ipynb into an .pdf file. When doing so the resulting .pdf file contains a header with the filename and the current date below. How can I disable that? I was looking in the docs but...
How to disable the header with filename and date when converting .ipynb to pdf with nbconvert?
I am using nbconvert for converting my .ipynb into an .pdf file. When doing so the resulting .pdf file contains a header with the filename and the current date below. How can I disable that? I was looking in the docs but cannot find how to do it. CLI command jupyter nbconvert --to pdf filename.ipynb Actual Wanted
[ "I found some helpful pointer in the docs. Just follow these steps:\n\nRun jupyter --paths in your command-line.\nCopy the path who looks like /Users/username/.venv/venvName/share/jupyter (I run nbconvert from a venv. Could be different for you).\nGo to the path and duplicate the folder latex\nName the folder hide_...
[ 0 ]
[]
[]
[ "jupyter_notebook", "nbconvert", "python" ]
stackoverflow_0074554325_jupyter_notebook_nbconvert_python.txt
Q: Python slice and delete function I do not understand the slice function. I want to delete all columns from a certain number. data = np.delete(data, slice(1344,-1), axis = 1) print(data.shape) print(data[0,1340:1345]) data = np.delete(data,1344, axis =1 ) print(data.shape) print(data[0,1340:1345]) If I do so, data...
Python slice and delete function
I do not understand the slice function. I want to delete all columns from a certain number. data = np.delete(data, slice(1344,-1), axis = 1) print(data.shape) print(data[0,1340:1345]) data = np.delete(data,1344, axis =1 ) print(data.shape) print(data[0,1340:1345]) If I do so, data.shape somehow does not delete the las...
[ "For a simple 1d array:\nIn [170]: x=np.arange(10) \nIn [171]: x[slice(5,-1)]\nOut[171]: array([5, 6, 7, 8])\n\nThe slice by itself is:\nIn [172]: slice(5,-1)\nOut[172]: slice(5, -1, None)\n\nwhich is the equivalent of:\nIn [173]: x[5:-1]\nOut[173]: array([5, 6, 7, 8])\n\nTo get values starting from the end:\nIn...
[ 0 ]
[]
[]
[ "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074553523_numpy_numpy_ndarray_python.txt
Q: Pandas Split Columns in Columns different sizes --Edited--['SOLVED'] I am using tabula to convert pdf invoices to pandas dataframe, but the last column isn't in the good way. I want to split the last row named 'PVF c/ IVA PVA s/Tx Desc% Tx Inf. IVA% P.Unit. Total Liq.' I want to split, in each space, and have new ...
Pandas Split Columns in Columns different sizes
--Edited--['SOLVED'] I am using tabula to convert pdf invoices to pandas dataframe, but the last column isn't in the good way. I want to split the last row named 'PVF c/ IVA PVA s/Tx Desc% Tx Inf. IVA% P.Unit. Total Liq.' I want to split, in each space, and have new columns ['PVFc/IVA', 'PVAs/Tx', 'Desc%' 'TxInf.', 'I...
[ "So the problem here is the cells do not have an equal number of values in that column, we can address this by counting the number of values and wherever we see a missing value, we can add a dummy 00 at the beginning so it is easier for us to split later.\nfirst, let's create a column with the number of spaces. Thi...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "tabula" ]
stackoverflow_0074554396_dataframe_pandas_python_tabula.txt
Q: change the color of a tkinter widget with command I'm trying to make gui with tkinter (I also use customtkinter to have a good design) and I'm trying to make categories, I created for this a margin (with a frame) in which I have place buttons for the different categories, I would like the button of the current cat...
change the color of a tkinter widget with command
I'm trying to make gui with tkinter (I also use customtkinter to have a good design) and I'm trying to make categories, I created for this a margin (with a frame) in which I have place buttons for the different categories, I would like the button of the current category to be colored blue, and the other buttons to be g...
[ "Try looking at the tkinter documentation for coloring GUI elements.\nIn short, to color a GUI button, use the following code:\nl1 = tkinter.Label(text=\"Test\", fg=\"black\", bg=\"white\")\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074554018_python_tkinter.txt
Q: What's the most efficient way to resample from an array many times and take the mode of each sample? So bootstrapping, but for modes. The end goal is to create a probability distribution out of these modes. I need to create a test statistic that compares these distributions (and then perform a permutation test), s...
What's the most efficient way to resample from an array many times and take the mode of each sample?
So bootstrapping, but for modes. The end goal is to create a probability distribution out of these modes. I need to create a test statistic that compares these distributions (and then perform a permutation test), so the initial bootstrapping needs to be as quick as possible so that creating the null distribution doesn'...
[ "Adapting from Using bootstrapping random.choice\nimport scipy.stats as ss\n\narray = ...\nnum_samples = 1000\n\nsample_size = 100\n\nReplications = np.array([np.random.choice(array, sample_size, replace = True) for _ in range(num_samples)])\nmode_result = ss.mode(Replications, axis=1)\n\nmode = mode_result.mode\n\...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074554393_numpy_python.txt
Q: Python AttributeError: 'Page' object has no attribute 'insertImage' I'am trying to add a png sign to the PDF by using a python code and the code that i am running is I am using PyMuPDF and have used fitz library. import fitz input_file = "example.pdf" output_file = "example-with-sign.pdf" barcode_file = "sign.png...
Python AttributeError: 'Page' object has no attribute 'insertImage'
I'am trying to add a png sign to the PDF by using a python code and the code that i am running is I am using PyMuPDF and have used fitz library. import fitz input_file = "example.pdf" output_file = "example-with-sign.pdf" barcode_file = "sign.png" # define the position (upper-right corner) image_rectangle = fitz.Rect...
[ "Thank you for 'insert_image' correction. It currently works as follows:\nimport fitz\n\ninput_file = \"example.pdf\"\noutput_file = \"example-with-sign.pdf\"\n\n\n# define the position (upper-right corner)\nimage_rectangle = fitz.Rect(450,20,550,120)\n\n# retrieve the first page of the PDF\nfile_handle = fitz.open...
[ 1, 1 ]
[]
[]
[ "compiler_errors", "pdf", "pymupdf", "python" ]
stackoverflow_0073633334_compiler_errors_pdf_pymupdf_python.txt
Q: ValueError: Unknown loss function: categorical crossentropy. Please ensure this object is passed to the `custom_objects` argument I am trying to build a chatbot for a University project, by following a youtube tutorial and basically having zero experience. Everything worked fine until now, and I get a ValueError. ...
ValueError: Unknown loss function: categorical crossentropy. Please ensure this object is passed to the `custom_objects` argument
I am trying to build a chatbot for a University project, by following a youtube tutorial and basically having zero experience. Everything worked fine until now, and I get a ValueError. This is what I receive when I run the code: C:\Users\Kimbe\.conda\envs\tf.2\python.exe C:\Users\Kimbe\PycharmProjects\chatbot\training....
[]
[]
[ "you may need to consider the input format as float or int.\n\nSample: Calculation is beneficial when the sequence is in format, passthrough possible but no meaning when it cannot have a load of functions.\n\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\n\nimport tensorflow as tf\n\nimport json\n\n\"\"\"\"\...
[ -1 ]
[ "chatbot", "keras", "python", "tensorflow", "valueerror" ]
stackoverflow_0074552911_chatbot_keras_python_tensorflow_valueerror.txt
Q: Reading Multiple S3 Folders / Paths Into PySpark I am conducting a big data analysis using PySpark. I am able to import all CSV files, stored in a particular folder of a particular bucket, using the following command: df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true...
Reading Multiple S3 Folders / Paths Into PySpark
I am conducting a big data analysis using PySpark. I am able to import all CSV files, stored in a particular folder of a particular bucket, using the following command: df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('file:///home/path/datafolder/data2014/*.csv')...
[ "You can read in multiple paths with wildcards as long as the files are all in the same format.\nIn your example:\n.load('file:///home/path/SFweather/data2014/*.csv')\n.load('file:///home/path/SFweather/data2015/*.csv')\n.load('file:///home/path/NYCweather/data2014/*.csv')\n.load('file:///home/path/NYCweather/data2...
[ 7, 0 ]
[]
[]
[ "amazon_s3", "jupyter_notebook", "pyspark", "python" ]
stackoverflow_0046240271_amazon_s3_jupyter_notebook_pyspark_python.txt
Q: Get Youtube's most replayed data through web scraping I want to get data out of youtube's "heat-map" feature, which is present in videos with certain features. This is an example. I want to retrieve this data somehow yet Youtube API's don't provide it and, this api doesn't always work. I'm aware they probably use ...
Get Youtube's most replayed data through web scraping
I want to get data out of youtube's "heat-map" feature, which is present in videos with certain features. This is an example. I want to retrieve this data somehow yet Youtube API's don't provide it and, this api doesn't always work. I'm aware they probably use the same approach, but I want to be able to have a reliable...
[ "That desired data is under an attribute value of d with path tag. So you can try the next example.\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.chrome.service import Service\n\n#You change this portion into Firefox instead\nwebdriver_service = Service(\"./chr...
[ 1, 1, 0 ]
[]
[]
[ "python", "web_scraping", "youtube", "youtube_api" ]
stackoverflow_0074464780_python_web_scraping_youtube_youtube_api.txt
Q: Pandas; Trying to split a string in a column with | , and then list all strings, removing all duplicates I'm working on a data frame for a made up TV show. In this dataframe, are columns: "Season","EpisodeTitle","About","Ratings","Votes","Viewership","Duration","Date","GuestStars",Director","Writers", With rows li...
Pandas; Trying to split a string in a column with | , and then list all strings, removing all duplicates
I'm working on a data frame for a made up TV show. In this dataframe, are columns: "Season","EpisodeTitle","About","Ratings","Votes","Viewership","Duration","Date","GuestStars",Director","Writers", With rows listed as ascending numerical values. In this data frame, my problem relates to two columns; 'Writers' and 'View...
[ "# I believe in newer versions of pandas you can split cells to multiple rows like this\n# here is a reference https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.25.0.html#series-explode-to-split-list-like-values-to-rows\n\ndf2 =df.assign(Writers=df.Writers.str.split('|')).explode('Writers').reset_index(drop=...
[ 1 ]
[]
[]
[ "dataframe", "iteration", "multiple_columns", "pandas", "python" ]
stackoverflow_0074554643_dataframe_iteration_multiple_columns_pandas_python.txt
Q: Python traitlets package warring and permission denied in vscode interactive windows OS: Arch linux(termux proot) Python version: 3.10.8 My error message as follow Visual Studio Code (1.73.1, undefined, desktop) Jupyter Extension Version: 2022.9.1303220346. Python Extension Version: 2022.18.2. Workspace folder /ho...
Python traitlets package warring and permission denied in vscode interactive windows
OS: Arch linux(termux proot) Python version: 3.10.8 My error message as follow Visual Studio Code (1.73.1, undefined, desktop) Jupyter Extension Version: 2022.9.1303220346. Python Extension Version: 2022.18.2. Workspace folder /home/jack/Documents/Medical-segmentation info 15:00:11.430: ZMQ install verified. User belo...
[ "\nOpen your vscode and reinstall the Python and Jupyter Notebook extensions.\nReinstall ipykernel package in the terminal.\n\nAt the same time, this issue also proposes other solutions.\nAdded:\nI encountered the same problem with traitlets==4.3.3. I updated it by using pip install traitlets and it's version is 5....
[ 0 ]
[]
[]
[ "python", "termux", "visual_studio_code" ]
stackoverflow_0074549086_python_termux_visual_studio_code.txt
Q: Save a text file replacing the regular expression from variable in python I am using this code to save in a text file a ping command: from subprocess import * def run_cmd(cmd): p = Popen(cmd, shell=True, stdout=PIPE) output = p.communicate()[0] return output test = run_cmd('ping www.googl...
Save a text file replacing the regular expression from variable in python
I am using this code to save in a text file a ping command: from subprocess import * def run_cmd(cmd): p = Popen(cmd, shell=True, stdout=PIPE) output = p.communicate()[0] return output test = run_cmd('ping www.google.com') print(test) with open('sample.txt', 'w', encoding='utf-8') as f: ...
[ "I found this solution\nimport io\nimport subprocess\n\ndef commandP(command):\n output = subprocess.getoutput(command)\n return output\n\ndef recordV(file, output):\n with io.open(f'{file}.txt', 'w') as f:\n f.write(output)\n\n\noutput = commandP('ping www.google.com')\nrecordV('test', output)\n\n"...
[ 1 ]
[]
[]
[ "cmd", "expression", "ping", "python" ]
stackoverflow_0074532148_cmd_expression_ping_python.txt
Q: Installed package was successful outside virtual env but errors inside virtual env I have a package "fretboardgtr" successfully installed outside virtual env using pip. The modules work without any errors. I started a django project inside a virtual env and tried to install the same package inside the virtual env ...
Installed package was successful outside virtual env but errors inside virtual env
I have a package "fretboardgtr" successfully installed outside virtual env using pip. The modules work without any errors. I started a django project inside a virtual env and tried to install the same package inside the virtual env but it errors with the following error: Collecting fretboardgtr Using cached fretboar...
[ " sudo apt-get install libfreetype6-dev\n\nProbably your are missing this dependency\n" ]
[ 0 ]
[]
[]
[ "django", "pip", "pypi", "python", "virtualenv" ]
stackoverflow_0074010991_django_pip_pypi_python_virtualenv.txt
Q: Printing website scrape loop directly into Google Sheets I'm scraping a bunch of website data and am able to print to terminal, but having real trouble pushing it directly to a sheet. I can confirm Gspread connection is working - my code loops through the names, but doesn't touch the sheet. I thought the last line...
Printing website scrape loop directly into Google Sheets
I'm scraping a bunch of website data and am able to print to terminal, but having real trouble pushing it directly to a sheet. I can confirm Gspread connection is working - my code loops through the names, but doesn't touch the sheet. I thought the last line of code (append) would place the results. Ultimately, I just ...
[ "Modification points:\n\nWhen I saw your script, I thought that data of data = get_links(url) is an array including JSON object. In the current stage, append_row cannot directly use the JSON object. I thought that this is the reason for your current issue.\nIn your script, append_row is used in the loop. In this ca...
[ 2 ]
[]
[]
[ "beautifulsoup", "google_sheets", "google_sheets_api", "gspread", "python" ]
stackoverflow_0074552515_beautifulsoup_google_sheets_google_sheets_api_gspread_python.txt
Q: python with sympy I am trying to make matrix with unknown numbers, and instead of showing it as matrix its saying Matrix and than putting all in 1 line. Matrix([[cos(t2(t)), 0, sin(t2(t)), 0], [sin(t2(t)), 0, -cos(t2(t)), 0], [0, 1, 0, d2(t)], [0, 0, 0, 1]]) In the pic you can see its showing the matrix in 1 line...
python with sympy
I am trying to make matrix with unknown numbers, and instead of showing it as matrix its saying Matrix and than putting all in 1 line. Matrix([[cos(t2(t)), 0, sin(t2(t)), 0], [sin(t2(t)), 0, -cos(t2(t)), 0], [0, 1, 0, d2(t)], [0, 0, 0, 1]]) In the pic you can see its showing the matrix in 1 line. this is my good for t...
[ "The \"one line matrix\" is a compact method of representing the matrix. It is the form given by the \"str\" function (which apparently is the default method of printing in your context). By using init_printing() at the outset you will get better looking output (probably); I rarely use it.\nsample IDE session showi...
[ 0 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0074552877_python_sympy.txt
Q: Ignore path does not exist in pyspark I want ignore the paths that generate the Error: 'Path does not exist' when I read parquet files with pyspark. For example I have a list of paths: list_paths = ['path1','path2','path3'] and read the files like: dataframe = spark.read.parquet(*list_paths) but the path path...
Ignore path does not exist in pyspark
I want ignore the paths that generate the Error: 'Path does not exist' when I read parquet files with pyspark. For example I have a list of paths: list_paths = ['path1','path2','path3'] and read the files like: dataframe = spark.read.parquet(*list_paths) but the path path2 does not exist. In general, I do not kno...
[ "You can use Hadoop FS API to check if the files exist before you pass them to spark.read:\nconf = sc._jsc.hadoopConfiguration()\nPath = sc._gateway.jvm.org.apache.hadoop.fs.Path\n\n\nfiltered_paths = [p for p in list_paths if Path(p).getFileSystem(conf).exists(Path(p))]\n\ndataframe = spark.read.parquet(*filtered_...
[ 1, 0, 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "parquet", "pyspark", "python" ]
stackoverflow_0070367863_apache_spark_apache_spark_sql_parquet_pyspark_python.txt
Q: Compact way of writing (a + b == c or a + c == b or b + c == a) Is there a more compact or pythonic way to write the boolean expression a + b == c or a + c == b or b + c == a I came up with a + b + c in (2*a, 2*b, 2*c) but that is a little strange. A: If we look at the Zen of Python, emphasis mine: The Zen o...
Compact way of writing (a + b == c or a + c == b or b + c == a)
Is there a more compact or pythonic way to write the boolean expression a + b == c or a + c == b or b + c == a I came up with a + b + c in (2*a, 2*b, 2*c) but that is a little strange.
[ "If we look at the Zen of Python, emphasis mine:\n\nThe Zen of Python, by Tim Peters\nBeautiful is better than ugly.\n Explicit is better than implicit.\nSimple is better than complex.\n Complex is better than complicated.\n Flat is better than nested.\n Sparse is better than dense.\nReadability counts.\n Spec...
[ 206, 101, 54, 40, 16, 12, 10, 9, 6, 6, 4, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "boolean", "python" ]
stackoverflow_0032085675_boolean_python.txt
Q: python convert dataframe to json with \n We converted dataframe to json using to_json(), but \n disappears in the string. How can I convert while keeping \n? Before conversion, dataframe has \n, which disappears when converted now: companyId:"ckurudq3r00efkakh4hgu33pn" tagName: contact:"0336443303" phone:"01066449...
python convert dataframe to json with \n
We converted dataframe to json using to_json(), but \n disappears in the string. How can I convert while keeping \n? Before conversion, dataframe has \n, which disappears when converted now: companyId:"ckurudq3r00efkakh4hgu33pn" tagName: contact:"0336443303" phone:"01066449675" virtualNumber:"050413736583" partner:fals...
[ "I was running through something similar to this and I do not remember that I could figure it out so I came up with a workaround.\n#replace '\\n' with '\\\\n'\ndf.replace('\\n', '\\\\n', inplace= True)\n# export normally\ndf.to_json('path')\n\nwhenever you want to open it back, just read the file and again replace ...
[ 1 ]
[]
[]
[ "dataframe", "json", "python" ]
stackoverflow_0074554714_dataframe_json_python.txt
Q: How to apply a function element-wise with inputs from multiple numpy masked arrays to create a new masked array? I have a function that takes in 4 single value inputs to return a singular float output, for example: from scipy.stats import multivariate_normal grid_step = 0.25 #in units of sigma grid_x, grid_y = np...
How to apply a function element-wise with inputs from multiple numpy masked arrays to create a new masked array?
I have a function that takes in 4 single value inputs to return a singular float output, for example: from scipy.stats import multivariate_normal grid_step = 0.25 #in units of sigma grid_x, grid_y = np.mgrid[-2:2+grid_step:grid_step, -2:2+grid_step:grid_step] pos = np.dstack((grid_x, grid_y)) rv = multivariate_normal(...
[ "A test of np.vectorize with a masked array input:\nIn [180]: def foo(x):\n ...: print(x)\n ...: return 2*x\n ...: \n\nIn [181]: np.vectorize(foo)(np.ma.masked_array([1,2,3],[True,False,True]))\n1\n1\n2\n3\nOut[181]: \nmasked_array(data=[--, 4, --],\n mask=[ True, False, True],\...
[ 0 ]
[]
[]
[ "masked_array", "numpy", "python", "vectorization" ]
stackoverflow_0074554618_masked_array_numpy_python_vectorization.txt
Q: Pandas Dataframe to Code If I have an existing pandas dataframe, is there a way to generate the python code, which when executed in another python script, will reproduce that dataframe. e.g. In[1]: df Out[1]: income user 0 40000 Bob 1 50000 Jane 2 42000 Alice In[2]: someFunToWriteDfCode(df) Ou...
Pandas Dataframe to Code
If I have an existing pandas dataframe, is there a way to generate the python code, which when executed in another python script, will reproduce that dataframe. e.g. In[1]: df Out[1]: income user 0 40000 Bob 1 50000 Jane 2 42000 Alice In[2]: someFunToWriteDfCode(df) Out[2]: df = pd.DataFrame({'use...
[ "You could try to use the to_dict() method on DataFrame:\nprint \"df = pd.DataFrame( %s )\" % (str(df.to_dict()))\n\nIf your data contains NaN's, you'll have to replace them with float('nan'):\nprint \"df = pd.DataFrame( %s )\" % (str(df.to_dict()).replace(\" nan\",\" float('nan')\"))\n\n", "I always used this co...
[ 30, 1, 1, 0, 0 ]
[ "You can first save the dataframe you have, and then load in another python script when necessary. You can do it with two packages: pickle and shelve.\nTo do it with pickle:\nimport pandas as pd\nimport pickle\ndf = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], \n 'income': [40000, 50000, 42000]...
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0041769882_pandas_python.txt
Q: Why is my Python program returning empty instead of printing out my file? My Code File From Teacher I've tried anything I can think of for "Task 1" which is written in the green comment. Also, when I downloaded "sample.txt" it downloaded as "sample-1.txt" as its name but I'm not sure if it needs the second ".txt" ...
Why is my Python program returning empty instead of printing out my file?
My Code File From Teacher I've tried anything I can think of for "Task 1" which is written in the green comment. Also, when I downloaded "sample.txt" it downloaded as "sample-1.txt" as its name but I'm not sure if it needs the second ".txt" in the code. Thank you. Code: """Task 1: Write a program to read each line from...
[ "file is a file object, not the text contained in the file. If you just want to print the contents of the file use print(file.read())\nIf you want to iterate over every line in the file then this is a very common way of doing so:\nwith open(\"sample-1.txt.txt\", \"r+\") as file:\n for line in file:\n # do...
[ 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074554723_file_python.txt
Q: Multiple serial connections in separate dedicated threads with Tkinter using serial ReaderThread I want to create and maintain multiple non-blocking serial connections with some peripherals over UART. Truthfully, this is an expansion of this question about tkinter and multithreading Domarm suggests the following a...
Multiple serial connections in separate dedicated threads with Tkinter using serial ReaderThread
I want to create and maintain multiple non-blocking serial connections with some peripherals over UART. Truthfully, this is an expansion of this question about tkinter and multithreading Domarm suggests the following as a solution to the original question of creating a new thread to handle receiving serial data without...
[ "You can pass the instance of MainFrame to SerialReaderProtocolLine class and use functools.partial to pass this extra argument in ReaderThread(...).\nBelow is the updated code (note that my platform is Windows, so the com ports used are \"COM1\" and \"COM3\", change them to the com ports in your platform):\nfrom f...
[ 0 ]
[]
[]
[ "class", "multithreading", "pyserial", "python", "tkinter" ]
stackoverflow_0074552205_class_multithreading_pyserial_python_tkinter.txt
Q: How to compare two different true or false columns and get a confusion matrix? Python So I have 2 different true or false results that tested the same column. So test 1 has the wrong results and test 2 has the correct results. Is there python code that can compare these two results and obtain a confusion matrix re...
How to compare two different true or false columns and get a confusion matrix? Python
So I have 2 different true or false results that tested the same column. So test 1 has the wrong results and test 2 has the correct results. Is there python code that can compare these two results and obtain a confusion matrix result (true positives, false positives, false negatives, and true negatives)? For example: T...
[ "You can do this with numpy\nI will ignore the fact that the tests have letters, and just use an array instead\n#assume: \n#reponses = [...list of booleans...]\n#ground_truth = [...list of booleans...]\n\nimport numpy as np\nresponses = np.array(responses)\nground_truth = np.array(ground_truth)\n\ntrue_positives = ...
[ 1, 1 ]
[]
[]
[ "boolean", "confusion_matrix", "python" ]
stackoverflow_0074554750_boolean_confusion_matrix_python.txt
Q: Read txt file from specific of line to a certain line base on string I am trying to write some function of data, however, my data is like this: noms sommets 0000 Abbesses 0001 Alexandre Dumas 0002 Paris 0004 Nice ... coord sommets 0000 308 536 0001 472 386 0002 193 404 What I want to is to access from nom sommets...
Read txt file from specific of line to a certain line base on string
I am trying to write some function of data, however, my data is like this: noms sommets 0000 Abbesses 0001 Alexandre Dumas 0002 Paris 0004 Nice ... coord sommets 0000 308 536 0001 472 386 0002 193 404 What I want to is to access from nom sommets to 0004 Nice without knowing the number of line but base on the string va...
[ "Read text file to list split based on key word sommets\nwith open('text.txt') as file:\n lines = [line.rstrip() for line in file]\n\ntest_loop = []\nfor item in lines:\n if 'sommets' in item: \n test_loop.append([item])\n else: \n test_loop[-1].append(item)\nprint(test_loop)\n\nwhich gives ...
[ 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074541919_python_string.txt
Q: How to replace original values in list according to the indexed values of the original values I have these indexed values like these: {0:0, 22:1 , 334: 2 , 6666:3} And have a 2D list: [[0,22],[22,334,6666],[22,334],[0,6666]] I am expecting something like this: [[0,1],[1,2,3],[1,2],[0,3]] A: Sure! Try something l...
How to replace original values in list according to the indexed values of the original values
I have these indexed values like these: {0:0, 22:1 , 334: 2 , 6666:3} And have a 2D list: [[0,22],[22,334,6666],[22,334],[0,6666]] I am expecting something like this: [[0,1],[1,2,3],[1,2],[0,3]]
[ "Sure! Try something like:\nindexes = {0: 0, 22: 1, 334: 2, 6666: 3}\n\nsrc = [[0,22],[22,334,6666],[22,334],[0,6666]]\nresult = [[indexes.get(key) for key in sublst] for sublst in src]\n\nUnwrapping the list comprehension you've got something like:\nresult = []\nfor sublst in src:\n result_sublst = []\n for ...
[ 1 ]
[]
[]
[ "dictionary", "numpy", "python" ]
stackoverflow_0074554834_dictionary_numpy_python.txt
Q: get text files name(number) from a directory, and use the file name(number) to look for data in a separate text file I am new to python. I have a few text files in a directory, and a seperate textfile maintained the original links for each of the text files. Ie, I have 1.txt,2.txt and 3.txt saved in the directory,...
get text files name(number) from a directory, and use the file name(number) to look for data in a separate text file
I am new to python. I have a few text files in a directory, and a seperate textfile maintained the original links for each of the text files. Ie, I have 1.txt,2.txt and 3.txt saved in the directory, and I have weblink text file(line 1(wiki.com/a) is the link for 1.txt, line 2(wiki.com/b is the link for 2.txt...). I am ...
[ "Hope this helps.\n\nTry printing pos, I see its 0 based so you may want to offset pos\nTry converting the pos from integer to string before searching\n\nimport os\n\npath = '.'\nfiles = [os.path.splitext(filename)[0] for filename in os.listdir(path)]\nprint(files) #result from here is ['1', '2', '3']\n\n#second pa...
[ 1 ]
[]
[]
[ "directory", "list", "python", "text_files" ]
stackoverflow_0074554395_directory_list_python_text_files.txt
Q: Python kivy [CRITICAL] [Clock ] Warning, too much iteration done before the next frame I'm making a calendar app in for mobile in kivy and wantto make a scrollview for a stack layout but keep getting this error and I don't know why python code ` from kivymd.app import MDApp from kivy.uix.button import Button from ...
Python kivy [CRITICAL] [Clock ] Warning, too much iteration done before the next frame
I'm making a calendar app in for mobile in kivy and wantto make a scrollview for a stack layout but keep getting this error and I don't know why python code ` from kivymd.app import MDApp from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.stackla...
[ "Because you are using height: self.minimum_height in your LayoutExample, you must provide definite sizes for its children.\nThe Buttons that you add to LayoutExample have the default size_hint of (1,1), so that causes an infinite loop in the LayoutExample layout calculations. It is trying to calculate its minimum_...
[ 1 ]
[]
[]
[ "kivy", "kivy_language", "kivymd", "python", "python_3.x" ]
stackoverflow_0074553574_kivy_kivy_language_kivymd_python_python_3.x.txt
Q: Retain strings in a column using a dictionary's value I want to retain the string with the largest value based on a dictionary's key and value. Any suggestion to how to do it effectively? fruit_dict = { "Apple": 10, "Watermelon": 20, "Cherry": 30 } df = pd.DataFrame( { "ID": [1, 2, 3, 4, 5], ...
Retain strings in a column using a dictionary's value
I want to retain the string with the largest value based on a dictionary's key and value. Any suggestion to how to do it effectively? fruit_dict = { "Apple": 10, "Watermelon": 20, "Cherry": 30 } df = pd.DataFrame( { "ID": [1, 2, 3, 4, 5], "name": [ "Apple, Watermelon", ...
[ "One way it to use apply with max and fruit_dict.get as key:\nnew_df = (df.assign(name=df['name'].str.split(', ')\n .apply(lambda l: max(l, key=fruit_dict.get)))\n )\n\nor, if you expect some names to be missing from the dictionary:\nnew_df = (df.assign(name=df['name'].str.split(', ')\n ...
[ 2, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0070200649_pandas_python.txt
Q: Writing to row using openpyxl? I am trying to write a list to a row in Python using openpyxl, but to no avail. The list contains say for example ten values. I need to open an existing worksheet, and write those ten values to their own cell, along one row. I need to use openpyxl due to its functionality of overwrit...
Writing to row using openpyxl?
I am trying to write a list to a row in Python using openpyxl, but to no avail. The list contains say for example ten values. I need to open an existing worksheet, and write those ten values to their own cell, along one row. I need to use openpyxl due to its functionality of overwriting existing worksheets compared to ...
[ "Have a look here, scroll down to the heading Writing Values to Cells.\nTLDR:\n>>> import openpyxl\n>>> wb = openpyxl.Workbook()\n>>> sheet = wb['Sheet']\n>>> sheet['A1'] = 'Hello world!'\n>>> sheet['A1'].value\n'Hello world!\n\nor if you prefer\nsheet.cell(row=2, column=3).value = 'hello world'\n\nUpdate: changed ...
[ 8, 2, 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0033920108_excel_openpyxl_python.txt
Q: Converting dates with condition I'm trying to convert a column of dates. There are dates in 'ms' unit and Timestamp, I want to convert these dates in 'ms' unit in Timestamp too. So, I created this function: def convert(df): if df[df['Timestamp'].str.contains(':') == False]: df.Timestamp = pd.to_datetime(df....
Converting dates with condition
I'm trying to convert a column of dates. There are dates in 'ms' unit and Timestamp, I want to convert these dates in 'ms' unit in Timestamp too. So, I created this function: def convert(df): if df[df['Timestamp'].str.contains(':') == False]: df.Timestamp = pd.to_datetime(df.Timestamp, unit='ms') return df df =...
[ "Your == False statement is applying to the whole dataframe/series, not just the row you want. What you could do instead is just apply your function to those rows using .loc, which will return the rows set by a condition, and the column/s you request:\ndef convert(df):\n condition = ~df.Timestamp.str.contains(\":\...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074554938_pandas_python.txt
Q: How to produce a stacked bar plot for the value counts of all columns My dataframe has more than 10 columns and each column has values like yes/no/na/not specified. And I want to calculate the count of occurrences in each column and create stacked bar graph. Below is the image that I need: A: Yes, this is possib...
How to produce a stacked bar plot for the value counts of all columns
My dataframe has more than 10 columns and each column has values like yes/no/na/not specified. And I want to calculate the count of occurrences in each column and create stacked bar graph. Below is the image that I need:
[ "Yes, this is possible. But you'll need to re-format your data a little first.\nHere's the dataset I'm using in this example. It has the labels in the columns, and 1000 random Yes, No or Maybe responses as values.\n asthma boneitis diabetes pneumonia\n0 No No Yes Maybe\n1 No No ...
[ 1 ]
[]
[]
[ "pandas", "python", "stacked_bar_chart" ]
stackoverflow_0074554788_pandas_python_stacked_bar_chart.txt
Q: How do you increment list string elements in a for loop in python? How can I increment these list string elements in a for loop? mylist = ['and1', 'hello', 'world'] #some for loop for i in np.linspace(start,stop,num_samples) print('This is %s' % mylist[0]) This gives output: This is and1 This is and1 This is ...
How do you increment list string elements in a for loop in python?
How can I increment these list string elements in a for loop? mylist = ['and1', 'hello', 'world'] #some for loop for i in np.linspace(start,stop,num_samples) print('This is %s' % mylist[0]) This gives output: This is and1 This is and1 This is and1 My desired output is: This is and1 This is hello This is world Is...
[ "mylist[0] always refers to the initial index in the list, while you probably meant mylist[i]\nHowever, you can directly iterate over lists\nfor value in mylist:\n print(f\"This is {value}\")\n\n" ]
[ 2 ]
[]
[]
[ "for_loop", "increment", "list", "python", "string" ]
stackoverflow_0074554983_for_loop_increment_list_python_string.txt
Q: Safest way to generate a unique hash? I need to produce unique identifiers that can be used in filenames and can be reproduced given the same input values. I need to produce millions of these identifiers as the source input has millions of combinations. For simplicity's sake, I will use a small set in the example...
Safest way to generate a unique hash?
I need to produce unique identifiers that can be used in filenames and can be reproduced given the same input values. I need to produce millions of these identifiers as the source input has millions of combinations. For simplicity's sake, I will use a small set in the example, but the actual sets can be rather large (...
[ "The odds that you'd get an SHA1 collision from strings is astoundingly low. Currently there are less than 63 known collisions for SHA1.\nFirst ever SHA1 collision found\n\nFirst ever' SHA-1 hash collision calculated. All it took were five clever brains... and 6,610 years of processor time\n\nSHA1 is no longer cons...
[ 6, 5, 0 ]
[]
[]
[ "python", "uuid" ]
stackoverflow_0047601592_python_uuid.txt
Q: Function equivalent to (python) seaborn's "set_context()" in (R) ggplot2? A quite neat function of python's library seaborn is to be able to all the sizes of the plots, labels and the majority of graph elements with a single command: set_context(context), for different contexts the sizes of figures are resized acc...
Function equivalent to (python) seaborn's "set_context()" in (R) ggplot2?
A quite neat function of python's library seaborn is to be able to all the sizes of the plots, labels and the majority of graph elements with a single command: set_context(context), for different contexts the sizes of figures are resized accordingly, so if context is talk everything is larger, but for paper they are sc...
[ "I'm not too familiar with seaborn, but based on your description I think there are two features in {ggplot2} that might suit your needs.\nIf you want all your plots to use the same theme, you can run theme_set() at the top of your script/document to use the same theme for all your plots. Here you can declare a spe...
[ 2 ]
[]
[]
[ "ggplot2", "python", "r", "tidyverse" ]
stackoverflow_0074554829_ggplot2_python_r_tidyverse.txt
Q: What is the best way to get a client ip in python? I am building an application that requires the client ip for geolocation purposes. I am using python, flask, and nginx to serve. From what I have read, common ip address capturing happens in the actual server. Any python script I use inevitably just returns my ser...
What is the best way to get a client ip in python?
I am building an application that requires the client ip for geolocation purposes. I am using python, flask, and nginx to serve. From what I have read, common ip address capturing happens in the actual server. Any python script I use inevitably just returns my servers ip. What is the best way to get a client's ip addre...
[]
[]
[ "Although you're required to share part of your code to get help, I'm gonna answer your question: You can use Flask request.\nfrom flask import request\n\n...\n\nclient_ip = request.environ['REMOTE_ADDR']\nclient_port = request.environ['REMOTE_PORT']\n\n" ]
[ -1 ]
[ "flask", "nginx", "python" ]
stackoverflow_0074555025_flask_nginx_python.txt
Q: Changing specific values in a python dictionary I have the following dictionary in python: dict={('M1 ', 'V1'): 5, ('M1 ', 'V2'): 5, ('M1 ', 'V3'): 5, ('M1 ', 'V4'): 5, ('M2', 'V1'): 5, ('M2', 'V2'): 5, ('M2', 'V3'): 5, ('M2', 'V4'): 5, ('M3', 'V1'): 5, ('M3', 'V2'): 5, ('M3', 'V3'): 5, ('M3', 'V4'): 5}...
Changing specific values in a python dictionary
I have the following dictionary in python: dict={('M1 ', 'V1'): 5, ('M1 ', 'V2'): 5, ('M1 ', 'V3'): 5, ('M1 ', 'V4'): 5, ('M2', 'V1'): 5, ('M2', 'V2'): 5, ('M2', 'V3'): 5, ('M2', 'V4'): 5, ('M3', 'V1'): 5, ('M3', 'V2'): 5, ('M3', 'V3'): 5, ('M3', 'V4'): 5} For contextualization, "dict" is a matrix distance ...
[ "What you are doing here is you want to filter dictionary keys based on a value. the keys here are of tuple type. so basically you need to iterate the keys and check if they have the needed value.\n#let's get a list of your keys first\nl = [] #a placeholder for the dict keys that has 'M1' in source\nfor k in dict...
[ 1, 1, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074555003_dictionary_python.txt
Q: Are you able to pass uri_file Inputs into an Azure ML Sweep Job? I've recently started working with the Azure ML python SDKv2. I'm looking to fine-tune models with my sample of data and was hoping to incorporate different pre-trained models as starting points in my fine-tuning sweep job. I have a normal fine-tunin...
Are you able to pass uri_file Inputs into an Azure ML Sweep Job?
I've recently started working with the Azure ML python SDKv2. I'm looking to fine-tune models with my sample of data and was hoping to incorporate different pre-trained models as starting points in my fine-tuning sweep job. I have a normal fine-tuning pipeline working fine and have been using this guidance to attempt t...
[ "Currently it's not supported, we define search_space for hyperparameter sweep in inputs of train_model and call train_model.sweep() to create a sweep node based on train_model with specific run settings.\n\n" ]
[ 2 ]
[]
[]
[ "azure_machine_learning_service", "python" ]
stackoverflow_0074546629_azure_machine_learning_service_python.txt
Q: __main__ has no attribute preload problem from p5 library in python every time I run this code I get the error: AttributeError: module 'main' has no attribute 'preload' I run this code from p5 import setup, draw, size, background, run import numpy as np width = 500 height = 500 def setup(): size(width, heigh...
__main__ has no attribute preload problem from p5 library in python
every time I run this code I get the error: AttributeError: module 'main' has no attribute 'preload' I run this code from p5 import setup, draw, size, background, run import numpy as np width = 500 height = 500 def setup(): size(width, height) def draw(): background(51) run() and get the error message Tr...
[ "convention is to include if __name__ == '__main__': when running a python file by itself. the docs follow this convention in their examples. this script ran without the error but I'm not familiar with p5 and what it's supposed to show\n │ File: test.py\n───────┼───────────────────────────────────────────────...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074554972_python.txt
Q: Automatic Adjust of Y axis values using slider on matplotlib I was working on making a graph that displays the full line by keping x axis constant and left axis adjusting. I am calculating the cost to produce egg tray with multiple variables. Using jupyter notebook with ipywidgets as widgets i was able to get the ...
Automatic Adjust of Y axis values using slider on matplotlib
I was working on making a graph that displays the full line by keping x axis constant and left axis adjusting. I am calculating the cost to produce egg tray with multiple variables. Using jupyter notebook with ipywidgets as widgets i was able to get the answer. jypyter auto adjusting y axis import ipywidgets as widgets...
[ "I finally got the answer.\nI just have to change the limits of my Y\nMy changes are highlighted as BOLD\nI dont know how to properly construct yet. so ill just paste the screenshot of changes\nenter image description here\nenter image description here\n" ]
[ 0 ]
[]
[]
[ "jupyter", "matplotlib", "python", "slider" ]
stackoverflow_0074554532_jupyter_matplotlib_python_slider.txt
Q: When changing font size and what font im using, pygame gives me an error I'm trying to run this snippet of code in my Python Pygame project my_font = font.SysFont('freesansbold', 50) my_font.set_bold(True) size = pygame.font.Font.size(my_font, 50) counter = font.render(str(round((time+1000)/1000)), True, (50,50,50...
When changing font size and what font im using, pygame gives me an error
I'm trying to run this snippet of code in my Python Pygame project my_font = font.SysFont('freesansbold', 50) my_font.set_bold(True) size = pygame.font.Font.size(my_font, 50) counter = font.render(str(round((time+1000)/1000)), True, (50,50,50)) However when I try to run this code it returns this error File "c:\Users\s...
[ "Your code is a bit wrong in places.\nFirst the font object (pygame.font.Font) needs to be created:\npygame.init()\npygame.font.init()\n\nmy_font = pygame.font.SysFont('freesansbold', 50)\nmy_font.set_bold(True)\n\nThe function pygame.font.SysFont() returns a configured Font object. Once it's made, generally you a...
[ 0 ]
[]
[]
[ "attributeerror", "fonts", "pygame", "python" ]
stackoverflow_0074554944_attributeerror_fonts_pygame_python.txt
Q: Most efficient way to convert list of values to probability distribution? I have several lists that can only contain the following values: 0, 0.5, 1, 1.5 I want to efficiently convert each of these lists into probability mass functions. So if a list is as follows: [0.5, 0.5, 1, 1.5], the PMF will look like this: [...
Most efficient way to convert list of values to probability distribution?
I have several lists that can only contain the following values: 0, 0.5, 1, 1.5 I want to efficiently convert each of these lists into probability mass functions. So if a list is as follows: [0.5, 0.5, 1, 1.5], the PMF will look like this: [0, 0.5, 0.25, 0.25]. I need to do this many times (and with very large lists), ...
[ "Here are some solution for you to benchmark:\nUsing collections.Counter\nfrom collections import Counter\n\nbins = [0, 0.5, 1, 1.5]\na = [0.5, 0.5, 1.0, 0.5, 1.0, 1.5, 0.5]\ndenom = len(a)\ncounts = Counter(a)\npmf = [counts[bin]/denom for bin in Bins]\n\nNumPy based solution\nimport numpy as np\n\nbins = [0, 0.5,...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074555084_numpy_python.txt
Q: Token expires in a certain two hours Good afternoon, I am making an API in which it will connect to the dropbox API, the problem stems from the fact that the token does not last long, which is unclear in the documentation, does anyone of you know how to obtain the token through the endpoint or That it does not exp...
Token expires in a certain two hours
Good afternoon, I am making an API in which it will connect to the dropbox API, the problem stems from the fact that the token does not last long, which is unclear in the documentation, does anyone of you know how to obtain the token through the endpoint or That it does not expire, I would appreciate it. I looked in th...
[ "Dropbox is in the process of switching to only issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here.\nApps can still get long-term access by requesting \"offline\" access though, in which case the app receives a \"...
[ 0 ]
[]
[]
[ "api", "dropbox", "python" ]
stackoverflow_0074539973_api_dropbox_python.txt
Q: Python - Column concatenation based on length of data inside the column Need help on column concatenation based on length size . Column3= df["column1"] + "_" + df["column2"] data = {'column1':['af28912368', 'Nan', '234671', 'asr61239'], 'column2':[701, Nan, 761, 312]} df = pd.DataFrame(data) df : column1 column2 ...
Python - Column concatenation based on length of data inside the column
Need help on column concatenation based on length size . Column3= df["column1"] + "_" + df["column2"] data = {'column1':['af28912368', 'Nan', '234671', 'asr61239'], 'column2':[701, Nan, 761, 312]} df = pd.DataFrame(data) df : column1 column2 af28912368 701 NaN Nan 234671 761 asr61239 312 If length of ...
[ "you're first row column1 value keeps changing so I'm assuming this is a typo and not part of the exercise\nthis script worked for me:\n───────┬─────────────────────────────────────────────────────────────────────\n │ File: test-so.py\n───────┼──────────────────────────────────────────────────────────────────...
[ 1 ]
[]
[]
[ "concatenation", "multiple_columns", "python", "string_length" ]
stackoverflow_0074555121_concatenation_multiple_columns_python_string_length.txt
Q: Transforming Badly Formatted Data into something useful Just for fun, someone just dropped a json file needing to be transformed into a Time Series on to my lap. Unfortunately for me, it looks like this: "messages": [ { "format": "string", "topic": "camera1", "timestamp": 1669253760775, "payload": "{\"An...
Transforming Badly Formatted Data into something useful
Just for fun, someone just dropped a json file needing to be transformed into a Time Series on to my lap. Unfortunately for me, it looks like this: "messages": [ { "format": "string", "topic": "camera1", "timestamp": 1669253760775, "payload": "{\"AnalyticalOutput\":[\"1\",\"6\",\"6\",\"9\",\"2\",\"5\",\"3\",\...
[ "Here's one example of drilling down into the payload\nimport json\nd = { \"messages\": [\n{\n \"format\": \"string\",\n \"topic\": \"camera1\",\n \"timestamp\": 1669253760775,\n \"payload\": \"{\\\"AnalyticalOutput\\\":[\\\"1\\\",\\\"6\\\",\\\"6\\\",\\\"9\\\",\\\"2\\\",\\\"5\\\",\\\"3\\\",\\\"7\\\",\\\"6\\\",...
[ 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074555127_json_python.txt
Q: Complex numbers in python Are complex numbers a supported data-type in Python? If so, how do you use them? A: In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily: >>> 1j 1j >>> 1J 1j >>> 1j * 1j (-1+0j) The ‘j’ suffix comes from electrical engineering,...
Complex numbers in python
Are complex numbers a supported data-type in Python? If so, how do you use them?
[ "In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:\n>>> 1j\n1j\n>>> 1J\n1j\n>>> 1j * 1j\n(-1+0j)\n\nThe ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)\nThe type of a complex num...
[ 246, 17, 0 ]
[]
[]
[ "complex_numbers", "python", "types" ]
stackoverflow_0008370637_complex_numbers_python_types.txt
Q: Is it possible to programmatically define identifiers using string data in Python? Suppose I have a class called Circuit, and a dictionary containing data about each circuit component: components = { 'V1': [ ... ], 'L1': [ ... ], 'R1': [ ... ], 'R2': [ ... ], ... } I want to define child o...
Is it possible to programmatically define identifiers using string data in Python?
Suppose I have a class called Circuit, and a dictionary containing data about each circuit component: components = { 'V1': [ ... ], 'L1': [ ... ], 'R1': [ ... ], 'R2': [ ... ], ... } I want to define child objects Circuit.V1, Circuit.L1, and so on. The crux of the problem is that I have strings...
[ "Although not recommended, you can use the __setattr__ dunder method:\nclass C:\n ...\n\nc = C()\n\nc.__setattr__(\"V1\", 1)\n\nprint(\"c.V1 = \", c.V1) # c.V1 = 1\n\n\nIn principle this works, but if you want to define attributes in runtime (you do not know the name of the attributes beforehand) why would you l...
[ 3, 0 ]
[]
[]
[ "identifier", "python", "syntax" ]
stackoverflow_0074555171_identifier_python_syntax.txt
Q: is user input a letter in the CPU's choice? I'm trying to check if user input is one of the letters in the chosen word by the CPU. Let me know if this is not possible the way I'm trying to do it, thanks. import random test_list = [ 'yes', 'no'] # guessing list print("Original list is : " + str(test_list)) cpu_cho...
is user input a letter in the CPU's choice?
I'm trying to check if user input is one of the letters in the chosen word by the CPU. Let me know if this is not possible the way I'm trying to do it, thanks. import random test_list = [ 'yes', 'no'] # guessing list print("Original list is : " + str(test_list)) cpu_choice =[] cpu_choice=("Random element is :", random...
[ "I modified it to loop through the cpu_choice instead of the userinput (userinput is just one letter).\nThe printing of the result is moved out of the loop so the program won't print 'wrong' for every letter in the word that doesn't match.\nuserinput = input('guess a letter: ')[0]\nmatch = False\nfor letter in cpu_...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074555158_python.txt
Q: Parameterized Tests with Function Output I'm working on some fairly complicated test scenarios with PyTest, and I was hoping to encapsulate the test setup for various scenarios in some functions and then make those scenarios available to a test using parameterization. Here is a simplified example: def scenario01()...
Parameterized Tests with Function Output
I'm working on some fairly complicated test scenarios with PyTest, and I was hoping to encapsulate the test setup for various scenarios in some functions and then make those scenarios available to a test using parameterization. Here is a simplified example: def scenario01(): # complicated setup ... return {...
[ "If the functions aren't computationally expensive, there's no harm in it. If it were computationally expensive, I might move the function invocation inside the test method, like so:\n@pytest.mark.parametrize(\"test_data\", [scenario01, scenario02])\ndef test_my_func(scenario):\n test_data = scenario()\n\nThe is...
[ 1 ]
[]
[]
[ "pytest", "python", "testing" ]
stackoverflow_0074554736_pytest_python_testing.txt
Q: Cropping an image after Rotation, Scaling and Translation (with Python Transformation Matrix) such that there is no black background I have pairs of images of the same 2D object with very minor diferences. The two images of a pair have two reference points (a star [x_s,y_s] and an arrow-head [x_a,y_a]) as shown be...
Cropping an image after Rotation, Scaling and Translation (with Python Transformation Matrix) such that there is no black background
I have pairs of images of the same 2D object with very minor diferences. The two images of a pair have two reference points (a star [x_s,y_s] and an arrow-head [x_a,y_a]) as shown below: I have written a Python script to align one image with reference to the second image of the pair with the reference points/coordinat...
[ "If you want \"any help\" and are willing to use Imagemagick 7, then there is a simple solution using its aggressive trim.\nInput:\n\nmagick -fuzz 20% img.png +repage -bordercolor black -border 2 -background black -define trim:percent-background=0% -trim +repage img_trim.png\n\n\n", "Here is a Python/OpenCV solut...
[ 2, 2 ]
[]
[]
[ "geometry", "image_processing", "math", "opencv", "python" ]
stackoverflow_0074546776_geometry_image_processing_math_opencv_python.txt
Q: Insert variable in save file name in python I have a lot of files that need to be saved inside one folder, but the files that need to be saved have the same name except for one part. So, instead of editing one by one, I want to insert variables into similar parts of the names. Eg: D = r"c:\users\folder" f1 = D + r...
Insert variable in save file name in python
I have a lot of files that need to be saved inside one folder, but the files that need to be saved have the same name except for one part. So, instead of editing one by one, I want to insert variables into similar parts of the names. Eg: D = r"c:\users\folder" f1 = D + r"\apple_table.bin" f2 = D + r"\apple_chair.bin" ...
[ "Use a list and a for-loop. For instance:\nPATH_TO_FOLDER = r\"\\PATH\\TO\\FOLDER\"\nSUFFIX = \"table.bin\"\nlist_of_names = [\"apple\"]\nfor item in list_of_names:\n with open(\"{0}{1}{2}\".format(PATH_TO_FOLDER, item, SUFFIX), \"w+\") as f:\n f.write(\"<what you need to write>\")\n\n" ]
[ 1 ]
[]
[]
[ "file", "python", "variables" ]
stackoverflow_0074555287_file_python_variables.txt
Q: Accessing array outside of the for loop in python I am trying to access the array soc+ out the for loop. Outside of the for loop, it gives me only last value. How to access whole soc array out of the for loop? If I used append method it gives follow error " 'numpy.ndarray' object has no attribute 'append' " Thank ...
Accessing array outside of the for loop in python
I am trying to access the array soc+ out the for loop. Outside of the for loop, it gives me only last value. How to access whole soc array out of the for loop? If I used append method it gives follow error " 'numpy.ndarray' object has no attribute 'append' " Thank you. Here is part of my code for k in range(1,len(t)): ...
[ "You can add break statement in the for loop and access the soc out side the for loop.\nYou can keep the entire for loop in 1 function and pass the range value say (k,len(t)) once come out after break.\n", "If I replace soc +=i[k] * (t[k] - t[k - 1]) / 3600 / (cell_capacity) with soc = i[k] * (t[k] - t[k - 1]) /...
[ 0, 0 ]
[]
[]
[ "arrays", "for_loop", "python" ]
stackoverflow_0074505654_arrays_for_loop_python.txt
Q: Infinite loop mistake I'm having issues with this loop. I try to break the loop once the user write "S" or "n" but it doesn't do it. user_input = "" issue_num = 0 ISSUES = ["El motor o las cuchillas no arrancan", "La comida esta picada de manera desigual", "La comida esta picada muy fina o aguada",...
Infinite loop mistake
I'm having issues with this loop. I try to break the loop once the user write "S" or "n" but it doesn't do it. user_input = "" issue_num = 0 ISSUES = ["El motor o las cuchillas no arrancan", "La comida esta picada de manera desigual", "La comida esta picada muy fina o aguada", "Los alimentos se acumulan...
[ "The condition you are using in your inner loop is user_input != \"s\" or user_input != \"n\". This condition is always true because you are using or. The only way it could fail to be true is if user_input was somehow equal to \"s\" and \"n\" at the same time. Since that's not possible with a normal string, you kee...
[ 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074555339_loops_python.txt
Q: How to pass URL as a path parameter to a FastAPI route? I have created a simple API using FastAPI, and I am trying to pass a URL to a FastAPI route as an arbitrary path parameter. from fastapi import FastAPI app = FastAPI() @app.post("/{path}") def pred_image(path:str): print("path",path) return {'path':pa...
How to pass URL as a path parameter to a FastAPI route?
I have created a simple API using FastAPI, and I am trying to pass a URL to a FastAPI route as an arbitrary path parameter. from fastapi import FastAPI app = FastAPI() @app.post("/{path}") def pred_image(path:str): print("path",path) return {'path':path} When I test it, it doesn't work and throws an error. I a...
[ "Option 1\nYou can simply use the path convertor to capture arbitrary paths. As per Starlette documentation, path returns the rest of the path, including any additional / characters.\nfrom fastapi import Request\n\n@app.get('/{_:path}')\ndef pred_image(request: Request):\n return {\"path\": request.url.path[1:]}...
[ 4, 0 ]
[]
[]
[ "fastapi", "python", "starlette" ]
stackoverflow_0072801333_fastapi_python_starlette.txt
Q: Generating Python interpreter-intolerant wheels from a `pyproject.toml` Consider the following pyproject.toml: [build-system] requires = ["setuptools>=40.8.0", "wheel"] [project] name = "foo" version = "0.0.0" requires-python = "~=3.9" If I run pip wheel . in the directory containing this file, then I generate a ...
Generating Python interpreter-intolerant wheels from a `pyproject.toml`
Consider the following pyproject.toml: [build-system] requires = ["setuptools>=40.8.0", "wheel"] [project] name = "foo" version = "0.0.0" requires-python = "~=3.9" If I run pip wheel . in the directory containing this file, then I generate a wheel named foo-0.0.0-py3-none-any.whl. However, this wheel filename indicate...
[ "That is not quite what the platform tag in the wheel filename is used for - cp39 would indicate that you're only compatible with CPython 3.9 or higher, and this wheel should not be selected by PyPy or some other implementations. You would usually only use a compatibility tag like that if you had some compiled C ex...
[ 2 ]
[]
[]
[ "pyproject.toml", "python" ]
stackoverflow_0074555302_pyproject.toml_python.txt
Q: Pandas; Need to combine duplicate columns, and find the mean of another column I have this data frame with about 200 rows, and I need to combine the duplicate writers columns, and then find the mean value of their viewership. How can I accomplish this? Below is a sample of the data frame. Viewership ...
Pandas; Need to combine duplicate columns, and find the mean of another column
I have this data frame with about 200 rows, and I need to combine the duplicate writers columns, and then find the mean value of their viewership. How can I accomplish this? Below is a sample of the data frame. Viewership Writers 0 11.20 Ricky Gervais 1 11.20 Stephen Merch...
[ "Try:\ndf2['Writers'] = df2['Writers'].str.strip()\nmean = df2.groupby(['Writers']).mean()\nprint(mean)\n\nThis should remove any whitespace issues before grouping\n" ]
[ 1 ]
[]
[]
[ "duplicates", "mean", "multiple_columns", "pandas", "python" ]
stackoverflow_0074555228_duplicates_mean_multiple_columns_pandas_python.txt
Q: Using Lambda in GroupBy .agg to find Mean I'm not understanding how to pull the Mean of filtered data within a groupby DataFrame. It works perfectly for sum(), but mean() simply gives me the Percentage of occurrences from the total count. df = test.groupby(['Code']).agg( Count=('% Change', 'count'), H2C_Up_Mea...
Using Lambda in GroupBy .agg to find Mean
I'm not understanding how to pull the Mean of filtered data within a groupby DataFrame. It works perfectly for sum(), but mean() simply gives me the Percentage of occurrences from the total count. df = test.groupby(['Code']).agg( Count=('% Change', 'count'), H2C_Up_Mean=('% C2H',lambda x: (x > 0).mean()), H2C_Pct...
[ "df = test.groupby(['Code']).agg(\n Count=('% Change', 'count'),\n H2C_Up_Mean=('% C2H',lambda x: x[x > 0].mean()),\n H2C_Pct_Up=('% C2H',lambda x: (x > 0).sum()))\n\ngives df as:\n Count H2C_Up_Mean H2C_Pct_Up\nCode \nabc 3 0.5 2\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074554100_pandas_python.txt
Q: Python merging multiple JSON into one JSON without result merged in list I was trying to merge multiple JSON files into one JSON files if file1.json has dict like {"cars": 1, "houses": 2, "schools": 3, "stores": 4} and file2.json has dict like {"Pens": 1, "Pencils": 2, "Paper": 3} The result I am looking for is fi...
Python merging multiple JSON into one JSON without result merged in list
I was trying to merge multiple JSON files into one JSON files if file1.json has dict like {"cars": 1, "houses": 2, "schools": 3, "stores": 4} and file2.json has dict like {"Pens": 1, "Pencils": 2, "Paper": 3} The result I am looking for is file3.json {"cars": 1, "houses": 2, "schools": 3, "stores": 4, "Pens": 1, "Penci...
[ "Just make a dictionary and update it:\ndata={}\nfor file in p_test:\n with open(file) as infile:\n data.update(json.load(infile))\nwith open(path, \"w\") as outfile:\n json.dump(data, outfile)\n\nwith open(path,encoding='utf-8') as file:\n data = json.load(file)\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "json", "list", "python" ]
stackoverflow_0074555508_dictionary_json_list_python.txt
Q: Conda build fails with `Aborting implicit building of eggs.` message I am trying to build a new conda package based on an old one. The repo and code is available for Theme Material Darcula. Theme-material-darcula Jupyter labextension builds and install perfectly fine on my system. But the conda build . command fai...
Conda build fails with `Aborting implicit building of eggs.` message
I am trying to build a new conda package based on an old one. The repo and code is available for Theme Material Darcula. Theme-material-darcula Jupyter labextension builds and install perfectly fine on my system. But the conda build . command fails for me on Aborting implicit building of eggs. Use pip install. to insta...
[ "I'll answer my own question.\nI'm building the package the wrong way. The package is supposed to be built using python setuptools via:\npython3 setup.py sdist\n\nwhich will create tarball file dist directory.\nThis file is supposed to be published to PyPI. A bash script will make the job a whole lot easier (do mak...
[ 0 ]
[]
[]
[ "anaconda", "conda", "conda_build", "python", "recipe" ]
stackoverflow_0072974643_anaconda_conda_conda_build_python_recipe.txt
Q: Stripping non printable characters from a string in python I use to run $s =~ s/[^[:print:]]//g; on Perl to get rid of non printable characters. In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or no...
Stripping non printable characters from a string in python
I use to run $s =~ s/[^[:print:]]//g; on Perl to get rid of non printable characters. In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not. What would you do? EDIT: It has to support Unicode characte...
[ "Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Charact...
[ 94, 83, 20, 15, 13, 8, 7, 6, 3, 3, 3, 2, 2, 1, 1, 0 ]
[]
[]
[ "non_printable", "python", "string" ]
stackoverflow_0000092438_non_printable_python_string.txt
Q: Render a Django view with data classified in a one to many relationship I have a one to many relationshiop: class SessionGPS(models.Model): start_timestamp = models.IntegerField() end_timestamp= models.IntegerField() class GPSData(models.Model): longitude = models.DecimalField(max_digits=15, decimal_...
Render a Django view with data classified in a one to many relationship
I have a one to many relationshiop: class SessionGPS(models.Model): start_timestamp = models.IntegerField() end_timestamp= models.IntegerField() class GPSData(models.Model): longitude = models.DecimalField(max_digits=15, decimal_places=13) lat = models.DecimalField(max_digits=15, decimal_places=13) ...
[ "I don't think there is a query option to what you want. So, the only way I could think of is to post process the data:\nmodels.py:\nclass SessionGPS(models.Model):\n start_timestamp = models.DateTimeField(auto_now_add=True)\n end_timestamp = models.DateTimeField(null=True)\n \nclass GPSData(models.Model):...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074554244_django_python.txt
Q: Taking multiple integers on the same line as input from the user in python I know how to take a single input from user in python 2.5: raw_input("enter 1st number") This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in ...
Taking multiple integers on the same line as input from the user in python
I know how to take a single input from user in python 2.5: raw_input("enter 1st number") This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box. How can I take two or more inputs together in the same dia...
[ "This might prove useful:\na,b=map(int,raw_input().split())\n\nYou can then use 'a' and 'b' separately.\n", "How about something like this?\nuser_input = raw_input(\"Enter three numbers separated by commas: \")\n\ninput_list = user_input.split(',')\nnumbers = [float(x.strip()) for x in input_list]\n\n(You would p...
[ 17, 16, 4, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "Try this:\nprint (\"Enter the Five Numbers with Comma\")\n\nk=[x for x in input(\"Enter Number:\").split(',')]\n\nfor l in k:\n print (l)\n\n", "How about making the input a list. Then you may use standard list operations.\na=list(input(\"Enter the numbers\"))\n\n", "# the more input you want to add variabl...
[ -1, -1, -1 ]
[ "python", "python_2.x" ]
stackoverflow_0007378091_python_python_2.x.txt
Q: What is the logic used to break down multiple lambda variables in python? I am trying to reason through why the result of the following would be 8 but I'm a little stuck. f = lambda x,y: lambda z: (x)(y)(z) print((f)(lambda x: lambda y: x, lambda z: z*2)(3)(4)) I know that the next step would be to substitute f i...
What is the logic used to break down multiple lambda variables in python?
I am trying to reason through why the result of the following would be 8 but I'm a little stuck. f = lambda x,y: lambda z: (x)(y)(z) print((f)(lambda x: lambda y: x, lambda z: z*2)(3)(4)) I know that the next step would be to substitute f into the line as shown below, but this is where I get lost. ans = (lambda x,y: l...
[ "Let's give a name to some of those lambdas:\nconst = lambda x: (lambda y: x)\ndouble = lambda z: (z*2)\n\nAnd eta-reduct the lambda z:... inside f (that is lambda z: ( x(y) )(z) -> x(y)):\nf = lambda x, y: x(y)\n\nWe can now rewrite that expression as ( ( f(const, double) )(3) )(4).\nReducing, we get:\nf(const, do...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074555178_python.txt
Q: How to use groupby transform across multiple columns I have a big dataframe, and I'm grouping by one to n columns, and want to apply a function on these groups across two columns (e.g. foo and bar). Here's an example dataframe: foo_function = lambda x: np.sum(x.a+x.b) df = pd.DataFrame({'a':[1,2,3,4,5,6], ...
How to use groupby transform across multiple columns
I have a big dataframe, and I'm grouping by one to n columns, and want to apply a function on these groups across two columns (e.g. foo and bar). Here's an example dataframe: foo_function = lambda x: np.sum(x.a+x.b) df = pd.DataFrame({'a':[1,2,3,4,5,6], 'b':[1,2,3,4,5,6], 'c':['q'...
[ "Circa Pandas version 0.18, it appears the original answer (below) no longer works.\nInstead, if you need to do a groupby computation across multiple columns, do the multi-column computation first, and then the groupby:\ndf = pd.DataFrame({'a':[1,2,3,4,5,6],\n 'b':[1,2,3,4,5,6],\n ...
[ 22, 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0034099684_pandas_python.txt
Q: How do I return an output for lambda expression to be the actual date in string format my_date = input('Please enter your start date with format year/month/day: ') print(f'You entered {my_date}') split_my_date = my_date.split("/") a = int(split_my_date[0]) # Year b = int(split_my_date[1]) # Month c = int(split_...
How do I return an output for lambda expression to be the actual date in string format
my_date = input('Please enter your start date with format year/month/day: ') print(f'You entered {my_date}') split_my_date = my_date.split("/") a = int(split_my_date[0]) # Year b = int(split_my_date[1]) # Month c = int(split_my_date[2]) # Day s_my_date = str(lambda r_s_my_date : date(a,b,c) + timedelta(days=100)) #...
[ "I think what you are trying to do is to pass the year, month and date as parameters to your lambda function and return the date + 100 days.\nIn that case, it should be like this,\ns_my_date = lambda a, b, c : str(date(a,b,c) + timedelta(days=100))\n\na, b and c are your parameters, which will be used in the functi...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074555656_python.txt
Q: Python - Sum and count specific values with pandas pivot_table I have a pandas dataframe like ACCOUNT AMOUNT STATUS 1 -2 1 2 2 0 2 -1 0 1 2 1 1 2 1 This is would like to get converted into an dataframe like ACCOUNT STATUS COUNT>0 COUNT<0 AMO...
Python - Sum and count specific values with pandas pivot_table
I have a pandas dataframe like ACCOUNT AMOUNT STATUS 1 -2 1 2 2 0 2 -1 0 1 2 1 1 2 1 This is would like to get converted into an dataframe like ACCOUNT STATUS COUNT>0 COUNT<0 AMOUNT>0 AMOUNT<0 1 1 2 1 4 2 2 ...
[ "Using np.sign\nThis function returns an array of -1/0/1 depending on the signs of the values. Essentially giving me a convenient way of identifying things less, equal, or greater than zero. I use this in the group by statement and use agg to count the number of values, and sum to produce the total. After groupi...
[ 3, 1, 0 ]
[ "The next example aggregates by taking the mean across multiple columns.\n\ntable = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],\n aggfunc={'D': np.mean,\n 'E': np.mean})\ntable\n D E\nA C\nbar large 5.500000 7.500000\n small 5...
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0049154895_pandas_python.txt
Q: python csv reader delete special character in uuid Got a large csv file like fab47e7c-05df-4315-b23f-de2cfc8b180f,Lindie,Lilybelle,Lindie.Lilybelle@yopmail.coma 959d21f-e131-473c-ae44-cfea24dbaf3f,Vere,Ax,Vere.Ax@yopmail.com dd20bea2-f3a8-4283-82e2-501efb846fa8,Lacie,Byrne,Lacie.Byrne@yopmail.com and some of uuid...
python csv reader delete special character in uuid
Got a large csv file like fab47e7c-05df-4315-b23f-de2cfc8b180f,Lindie,Lilybelle,Lindie.Lilybelle@yopmail.coma 959d21f-e131-473c-ae44-cfea24dbaf3f,Vere,Ax,Vere.Ax@yopmail.com dd20bea2-f3a8-4283-82e2-501efb846fa8,Lacie,Byrne,Lacie.Byrne@yopmail.com and some of uuids imported with typo like #@3b751941-dca2-4224-b453-d81c...
[ "Your regex is wrong, it's looking for regexes that don't have any characters after them, because of the \"$\" symbol at the end. Use this:\n[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\nYou can test it here: https://regex101.com/r/TJXCaR/1\n" ]
[ 0 ]
[]
[]
[ "csv", "python", "uuid" ]
stackoverflow_0074555560_csv_python_uuid.txt
Q: Change Specific Word in Pandas I have a dataframe city = pd.DataFrame({'id': [1,2,3,4], 'city': ['NRTH CAROLINA','NEW WST AMSTERDAM','EAST TOKYO','LONDON STH']}) How can I change NRTH to NORTH, WST to WEST, and STH to SOUTH, so the output will be like this id city 1 NORTH CAROLINA 2 ...
Change Specific Word in Pandas
I have a dataframe city = pd.DataFrame({'id': [1,2,3,4], 'city': ['NRTH CAROLINA','NEW WST AMSTERDAM','EAST TOKYO','LONDON STH']}) How can I change NRTH to NORTH, WST to WEST, and STH to SOUTH, so the output will be like this id city 1 NORTH CAROLINA 2 NEW WEST AMSTERDAM 3 EAST TOKYO...
[ "Let's define a replace dictionary first then use Series.replace(regex=True) to replace by the word boundary of the dictionary key.\nimport re\n\nd = {\n 'NRTH': 'NORTH',\n 'WST': 'WEST',\n 'STH': 'SOUTH'\n}\n\n\ndf['city'] = df['city'].replace({rf\"\\b{re.escape(k)}\\b\":v for k, v in d.items()}, regex=Tr...
[ 3, 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074555652_dataframe_pandas_python.txt
Q: I cannot get my await to work in the new py update I am having some trouble with my discord bot that we use in a server for a group of friends to listen to youtube music. I will include the error screenshot and sources below. Thanks for looking. Error from console(replit) main.py: import discord from discord.ext i...
I cannot get my await to work in the new py update
I am having some trouble with my discord bot that we use in a server for a group of friends to listen to youtube music. I will include the error screenshot and sources below. Thanks for looking. Error from console(replit) main.py: import discord from discord.ext import commands import music from webserver import keep_a...
[ "You can not use await statement outside async def ....\nYou need to do like so:\nasync def setup(bot):\n await bot.add_cog(Music(bot))\n\nThen at the entry point of your program you should call something like asyncio.run(setup())\nPlease refer to official documentation, it has some handy examples: https://docs....
[ 0 ]
[]
[]
[ "discord", "discord.py", "python", "replit" ]
stackoverflow_0074555631_discord_discord.py_python_replit.txt