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: Can I use random choice to choose between 2 functions Hey guys I'm trying to create a function that randomly picks a number and then randomly adds or subtracts 1 from the chosen number but it seems that the random.choice function isn't working the way it is supposed to do I'm getting output but it's not the result...
Can I use random choice to choose between 2 functions
Hey guys I'm trying to create a function that randomly picks a number and then randomly adds or subtracts 1 from the chosen number but it seems that the random.choice function isn't working the way it is supposed to do I'm getting output but it's not the result of adding or subtracting (I visualized it on Thonny) Here ...
[ "Functions are objects that can be assigned to variables like any other object. To randomly chose one, make a random choice from a list of functions. See below.\nYour function ignores its argument x, I removed it entirely.\nRecommendation: do not define constants in a function. Each time you call the functions they...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074191837_python.txt
Q: How to checkout a tag with GitPython In a python script, I try to checkout a tag after cloning a git repository. I use GitPython 0.3.2. #!/usr/bin/env python import git g = git.Git() g.clone("user@host:repos") g = git.Git(repos) g.execute(["git", "checkout", "tag_name"]) With this code I have an error: g.execute(...
How to checkout a tag with GitPython
In a python script, I try to checkout a tag after cloning a git repository. I use GitPython 0.3.2. #!/usr/bin/env python import git g = git.Git() g.clone("user@host:repos") g = git.Git(repos) g.execute(["git", "checkout", "tag_name"]) With this code I have an error: g.execute(["git", "checkout", "tag_name"]) File "/us...
[ "Assuming you cloned the repository in 'path/to/repo', just try this:\nfrom git import Git\n\ng = Git('path/to/repo')\n\ng.checkout('tag_name')\n\n", "from git import Git\ng = Git(repo_path)\ng.init()\ng.checkout(version_tag)\n\nLike cmd.py Class Git comments say\n\"\"\"\nThe Git class manages communication with ...
[ 10, 1, 0 ]
[ "This worked for me, and I think it's closer to the intended API usage:\nfrom git import Repo\n\nrepo = Repo.clone_from(\"https://url_here\", \"local_path\")\nrepo.heads['tag-name'].checkout()\n\n" ]
[ -1 ]
[ "git", "gitpython", "python" ]
stackoverflow_0020073873_git_gitpython_python.txt
Q: Switch ad-hoc between distro and anaconda python versions I have installed anaconda on Ubuntu 20.04 (conda --version says conda 22.9.0). Now the global python version (which python) is controlled by anaconda since it installs its init code in .bashrc: # >>> conda initialize >>> # !! Contents within this block are ...
Switch ad-hoc between distro and anaconda python versions
I have installed anaconda on Ubuntu 20.04 (conda --version says conda 22.9.0). Now the global python version (which python) is controlled by anaconda since it installs its init code in .bashrc: # >>> conda initialize >>> # !! Contents within this block are managed by 'conda init' !! __conda_setup="$('/home/user/anacond...
[ "Conda installation comes with a default environment, often named base. That's what you see when typing which python: it links to the conda version of python.\nAs any other conda virtual environment, you can deactivate this base environment through conda deactivate.\nIf you do not want this base environment to be a...
[ 1 ]
[]
[]
[ "anaconda", "python", "virtualenv" ]
stackoverflow_0074190273_anaconda_python_virtualenv.txt
Q: Set to Set cross join conversion I was trying to find cross join of two set. I am currently doing the code below: import itertools a={1,2,3} b={4,5,6} itertools.product(a,b) list(itertools.product(a,b)) itertools.product(b,a) list(itertools.product(b,a)) Is there any other way to find out all possible cross join...
Set to Set cross join conversion
I was trying to find cross join of two set. I am currently doing the code below: import itertools a={1,2,3} b={4,5,6} itertools.product(a,b) list(itertools.product(a,b)) itertools.product(b,a) list(itertools.product(b,a)) Is there any other way to find out all possible cross join in a single code? and i need to conve...
[ "Use:\ndf = pd.DataFrame(list(itertools.product(a,b)) + list(itertools.product(b,a)), \n columns=['a','b'])\n\nprint (df)\n a b\n0 1 4\n1 1 5\n2 1 6\n3 2 4\n4 2 5\n5 2 6\n6 3 4\n7 3 5\n8 3 6\n9 4 1\n10 4 2\n11 4 3\n12 5 1\n13 5 2\n14 5 3\n15 6 1\n16 6 ...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074191988_dataframe_pandas_python.txt
Q: Segmentation fault when importing torch-sparse (installing pytorch-geometric) I am trying to install pytorch-geometric for a deep-learning project. Torch-sparse is throwing segmentation faults when I attempt to import it (see below). Initially I tried different versions of each required library, as I thought it mi...
Segmentation fault when importing torch-sparse (installing pytorch-geometric)
I am trying to install pytorch-geometric for a deep-learning project. Torch-sparse is throwing segmentation faults when I attempt to import it (see below). Initially I tried different versions of each required library, as I thought it might be a GPU issue, but I've since tried to simplify by installing cpu-only version...
[ "I've found a combination of packages that works for me - hopefully someone else will have this issue at some point and be able to reproduce the steps from me talking to myself here. The full process for getting stuff working was:\n\nFresh conda environment with forced Python=3.9 (conda create -n ENVNAME python=3.9...
[ 0 ]
[]
[]
[ "conda", "python", "pytorch", "pytorch_geometric", "ubuntu" ]
stackoverflow_0074180286_conda_python_pytorch_pytorch_geometric_ubuntu.txt
Q: How to set numba signature with nested lists? I'm trying to return an nested list, however running into some conversion error. Below is small piece of code for reproduction of error. from numba import njit, prange @njit("ListType(ListType(ListType(int32)))(int32, int32)", fastmath = True, parallel = True, cache =...
How to set numba signature with nested lists?
I'm trying to return an nested list, however running into some conversion error. Below is small piece of code for reproduction of error. from numba import njit, prange @njit("ListType(ListType(ListType(int32)))(int32, int32)", fastmath = True, parallel = True, cache = True) def test(x, y): a = [] for i in pran...
[ "I try to avoid using empty lists with numba, mainly because an empty list cannot be typed. Check out nb.typeof([])\nI am not sure whether your output can be preallocated but you could consider arrays. There would also be massive performance benefits. Here is an attempt:\nfrom numba import njit, prange, int32\nimpo...
[ 0, 0, 0 ]
[]
[]
[ "numba", "numba_pro", "python", "python_3.x" ]
stackoverflow_0074178994_numba_numba_pro_python_python_3.x.txt
Q: Why Sympy does not evaluate this definite integral? I have tried the following code to evaluate this integral but the output is the integral in LaTeX format and not evaluated. import sympy as smp g, t,v = smp.symbols('g t v') expr = smp.sqrt(1 - 1/(g*t +1)**2) smp.Integral(expr,t) If SymPy can not evaluate this i...
Why Sympy does not evaluate this definite integral?
I have tried the following code to evaluate this integral but the output is the integral in LaTeX format and not evaluated. import sympy as smp g, t,v = smp.symbols('g t v') expr = smp.sqrt(1 - 1/(g*t +1)**2) smp.Integral(expr,t) If SymPy can not evaluate this integral, is there any other Python library that can evalu...
[ "You need to use integrate rather than Integral if you actually want to compute the integral although in this particular case integrate fails:\nIn [3]: integrate(expr, t)\nOut[3]: \n⌠ \n⎮ ________________ \n⎮ ╱ 1 \n⎮ ╱ 1 - ────────── dt\n⎮ ╱ 2...
[ 2 ]
[]
[]
[ "integral", "python", "symbolic_math", "sympy" ]
stackoverflow_0074188033_integral_python_symbolic_math_sympy.txt
Q: Prevent related object persistence in sqlalchemy Environment Python 3.8.10 SQLAlchemy 1.3.22 Problem I am having a problem related to the stated here, but couldn't find a solution yet: How to prevent related object persistence in sqlalchemy? I have two models with a one to many relationship: class A: b = db.r...
Prevent related object persistence in sqlalchemy
Environment Python 3.8.10 SQLAlchemy 1.3.22 Problem I am having a problem related to the stated here, but couldn't find a solution yet: How to prevent related object persistence in sqlalchemy? I have two models with a one to many relationship: class A: b = db.relationship("B", back_populates="a", cascade="all,dele...
[ "In the end I ended up with another approach. I couldn't find a solution for the simultaneous storing of A and B, but I just made the checks different so the translation didn't overwrite the original instance.\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074126297_python_sqlalchemy.txt
Q: Python Selenium - loop over iframes I've seen a couple of examples to loop over iframes, but I didn't manage to adapt for myself. I have list of Webelements which are text input contained inside iframes, i.e: one iframe = one text input. I've tried this: text_input = self.driver.find_elements(By.CSS_SELECTOR, '[cl...
Python Selenium - loop over iframes
I've seen a couple of examples to loop over iframes, but I didn't manage to adapt for myself. I have list of Webelements which are text input contained inside iframes, i.e: one iframe = one text input. I've tried this: text_input = self.driver.find_elements(By.CSS_SELECTOR, '[class="Text_input_container__aReGv"]') ifra...
[ "I would suggest you to try switching the frame directly by name or by ID:\n driver.switchTo().frame(“frameName”);\n\nor\ndriver.switchTo().frame(“frameId”);\n\nIf this does not work, try to using XPATH as the selector instead the CSS_SELECTOR in the loop:\ndriver.findElement(By.xpath(\"html/body/your/xpath\"))\n...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074192010_python_selenium.txt
Q: ModuleNotFoundError: No module named 'apotheekMijlbeek_main' I try to deploy my first Django / Postgres app on Pythonanywhere. I activated the postgres on my account / configured the port / address etc but when I try to run the code I'm getting the ModuleNotFoundError: No module named 'apotheekMijlbeek_main'. In m...
ModuleNotFoundError: No module named 'apotheekMijlbeek_main'
I try to deploy my first Django / Postgres app on Pythonanywhere. I activated the postgres on my account / configured the port / address etc but when I try to run the code I'm getting the ModuleNotFoundError: No module named 'apotheekMijlbeek_main'. In my opinion my structure is like apotheekMijlbeek/apotheekMijlbeek_m...
[ "Make sure that you have a settings.py in the directory/home/stefrenneboog23/apotheekMijlbeek/apotheekMijlbeek_main\n" ]
[ 0 ]
[]
[]
[ "django", "python", "pythonanywhere", "wsgi" ]
stackoverflow_0074180484_django_python_pythonanywhere_wsgi.txt
Q: How to manage the sequentive imports in python packages? Let's say I have a package structure like this: Package\ __init__.py module1.py Subpackage\ __init__.py module2.py module3.py The essential point is that I want both the module2.py to work as a script if run from the Pack...
How to manage the sequentive imports in python packages?
Let's say I have a package structure like this: Package\ __init__.py module1.py Subpackage\ __init__.py module2.py module3.py The essential point is that I want both the module2.py to work as a script if run from the Package\Subpackage\ folder and module1.py to work as a script if r...
[ "Two ways of resolving this (both in module2.py):\n\nAdd Package\\Subpackage\\ to the path manually:\n\nfrom sys import path\npath.append('absolute\\\\path\\\\to\\\\Package\\\\Subpackage')\nimport module3\n\nOr better as suggested by @DenysGalanenko:\nimport os \n# get path to directory of the module2.py\ndir_path ...
[ 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0074192019_import_python.txt
Q: (raspberry pi 4 and Python) raspberry Camera mode raise picamera.exc.PiCameraMMALError and picamera.exc.PiCameraError system: raspberry pi 4 model B, use external usb logitech camera I'm follow the youtube tutorial but get picamera.exc.PiCameraMMALError andpicamera.exc.PiCameraError relate discussion on other site...
(raspberry pi 4 and Python) raspberry Camera mode raise picamera.exc.PiCameraMMALError and picamera.exc.PiCameraError
system: raspberry pi 4 model B, use external usb logitech camera I'm follow the youtube tutorial but get picamera.exc.PiCameraMMALError andpicamera.exc.PiCameraError relate discussion on other site 2021 (I didn't get their solution): "Camera issue, no idea what the problem is" https://forums.raspberrypi.com/viewtopic.p...
[ "You need to enable Pi-camera in setting.That's what error is saying.\n\nType sudo raspi-config in terminal & hit enter.\nGo to interface options\nGo to p1 Legacy camera and hit enetr After enable it.\n\n4.Reboot\n\nAs you mentioned external camera What happens here I guess is raspberry Pi has onboard camera socket...
[ 2 ]
[]
[]
[ "picamera", "python", "python_3.x", "raspberry_pi" ]
stackoverflow_0074191236_picamera_python_python_3.x_raspberry_pi.txt
Q: PIL Image.fromarray reducing the size of my image when saved my code: from PIL import Image img = Image.open('this.jpg') # 2.72mb image arrayA = np.array(img) new_img = Image.fromarray(arrayA) new_img.save("this_changed.jpg") # to 660 kb image size A: PIL will compress and subsample your image in order to s...
PIL Image.fromarray reducing the size of my image when saved
my code: from PIL import Image img = Image.open('this.jpg') # 2.72mb image arrayA = np.array(img) new_img = Image.fromarray(arrayA) new_img.save("this_changed.jpg") # to 660 kb image size
[ "PIL will compress and subsample your image in order to save space. Try to deactivate compressing and subsamling:\nnew_image.save(\"this_changed.jpg\",\n quality=100, # preserve color and image quality\n subsampling=0 # use the whole image as base for the save\n)\n\n", "PIL saves ima...
[ 0, 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0074190881_python_python_imaging_library.txt
Q: python BeautifulSoup parsing table I'm learning python requests and BeautifulSoup. For an exercise, I've chosen to write a quick NYC parking ticket parser. I am able to get an html response which is quite ugly. I need to grab the lineItemsTable and parse all the tickets. You can reproduce the page by going here...
python BeautifulSoup parsing table
I'm learning python requests and BeautifulSoup. For an exercise, I've chosen to write a quick NYC parking ticket parser. I am able to get an html response which is quite ugly. I need to grab the lineItemsTable and parse all the tickets. You can reproduce the page by going here: https://paydirect.link2gov.com/NYCPark...
[ "Here you go:\ndata = []\ntable = soup.find('table', attrs={'class':'lineItemsTable'})\ntable_body = table.find('tbody')\n\nrows = table_body.find_all('tr')\nfor row in rows:\n cols = row.find_all('td')\n cols = [ele.text.strip() for ele in cols]\n data.append([ele for ele in cols if ele]) # Get rid of emp...
[ 235, 73, 27, 10, 0 ]
[ "from behave import *\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\nfrom tabulate import t...
[ -1 ]
[ "beautifulsoup", "python" ]
stackoverflow_0023377533_beautifulsoup_python.txt
Q: Rewrite Java code to Python(function) but it does not work I want to rewrite a Java function in Python but it doesn't really work the way I want it to. This is how the Java code looks like: public String matchText(String[] splitText, String[] clozeText, int emptySpaces){ String result=""; for(int i=0;i<spl...
Rewrite Java code to Python(function) but it does not work
I want to rewrite a Java function in Python but it doesn't really work the way I want it to. This is how the Java code looks like: public String matchText(String[] splitText, String[] clozeText, int emptySpaces){ String result=""; for(int i=0;i<splitText.length;i++){ if (splitText[i].equals(clozeText[0]...
[ "The inner for loop should be\nfor x in range(i, i + emptySpaces + 1):\n result += splitText[x]\n\nThis is the correct implementation:\nfrom typing import List\n\ndef matchText(splitText: List[str], clozeText: List[str], emptySpaces: int) -> str:\n result = \"\"\n for i in range(len(splitText)):\n i...
[ 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0074192177_java_python.txt
Q: ModuleNotFoundError: No module named 'PIL' so I'm not sure what to try next for my ImageViewer I can't figure out why my code couldn't work. from tkinter import * """ We need the Pillow library (or PIL) to import images in out application) I need to import both ImageTk and Image """ from PIL import ImageTk, Image ...
ModuleNotFoundError: No module named 'PIL' so I'm not sure what to try next for my ImageViewer
I can't figure out why my code couldn't work. from tkinter import * """ We need the Pillow library (or PIL) to import images in out application) I need to import both ImageTk and Image """ from PIL import ImageTk, Image """ doens't work at the moment bc I can't figure out what's wrong with PIL """ root = Tk() root.ti...
[ "Hey there you can try the following-\n\nMake corrections in your code\nmy_img = ImageTk.PhotoImage(Image.open(\"something.png\"))\n\nTry to update your pip version by using the command in command prompt or powershell\npip install --upgrade pip\n\n\n", "So my actual problem was that I had more than one Python.exe...
[ 1, 0 ]
[]
[]
[ "python", "python_imaging_library", "tkinter" ]
stackoverflow_0074164827_python_python_imaging_library_tkinter.txt
Q: Finding the null space of a matrix using python i am trying to find the null space of a matrix using python and sympy and i don't understand why .nullspace() doesn't work? What is my mistake? Is there another better python module for linear algebra? If i print matrix x it is what i expect so i think the problem li...
Finding the null space of a matrix using python
i am trying to find the null space of a matrix using python and sympy and i don't understand why .nullspace() doesn't work? What is my mistake? Is there another better python module for linear algebra? If i print matrix x it is what i expect so i think the problem lies in the .nullspace() command or something with the ...
[ "Why do you expect a non trivial kernel?\nThe determinant of the matrix is not zero.\nScipy also shows trivial kernel\nimport sympy as sp\nimport numpy as np\nfrom scipy.linalg import null_space\n\ndef ranking(A,m=0.1):\n A = sp.Matrix(A)\n shape = sp.shape(A)\n n = shape[0]\n S = []\n\n for i in ran...
[ 0, 0 ]
[]
[]
[ "linear_algebra", "python", "sympy" ]
stackoverflow_0074190268_linear_algebra_python_sympy.txt
Q: How to index n-dims tensor with (n-k)-dims tensor in TF? I have a tensor A with shape [7, 7, 2, 4] and a tensor B with shape [7, 7]. Tensor B is the argmax of tensor A and its value is 0,1. I want to get tensor C with shape [7, 7, 4] or [7, 7, 1, 4] from A and B. The rule is the (i, j) element of tensor B is the i...
How to index n-dims tensor with (n-k)-dims tensor in TF?
I have a tensor A with shape [7, 7, 2, 4] and a tensor B with shape [7, 7]. Tensor B is the argmax of tensor A and its value is 0,1. I want to get tensor C with shape [7, 7, 4] or [7, 7, 1, 4] from A and B. The rule is the (i, j) element of tensor B is the index of the 2-nd dimensions of tensor A. How can I do it quick...
[ "Okay I was used tf.gather_nd to solve this problem:\ntensor_C = tf.gather_nd(tensor_A, tf.expand_dims(tf.argmax(tensor_B, 2), 2), batch_dims=3)\n\n" ]
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074190674_python_tensorflow.txt
Q: Python Datetime Comparison I'd like to check if the current date is bigger than a date put in by the user. All dates are converted using strftime('%d/%m/%Y'). But if I compare both dates, I get a wrong result: absenzen.view current_date = datetime.date.today().strftime('%d/%m/%Y') return render(request, 'absenzen....
Python Datetime Comparison
I'd like to check if the current date is bigger than a date put in by the user. All dates are converted using strftime('%d/%m/%Y'). But if I compare both dates, I get a wrong result: absenzen.view current_date = datetime.date.today().strftime('%d/%m/%Y') return render(request, 'absenzen.html', {'absenzen': absenzen_loc...
[ "current_date = datetime.date.today().strftime('%d/%m/%Y')\n\nprint(current_date, type(current_date))#25/10/2022 <class 'str'>\n\n\ncurrent_date = datetime.date.today()\n\nprint(current_date, type(current_date))#2022-10-25 <class 'datetime.date'>\n\nIf you print out the current_date datatype it will be: <class 'str...
[ 0 ]
[]
[]
[ "date", "datetime", "django", "python" ]
stackoverflow_0074189981_date_datetime_django_python.txt
Q: How do I create a list of items (attributes) based on the dummy variable value? Let's say I have a dataframe in python with a range of animals, and a range of attributes, with dummy variables for whether the animal has that attribute. I'm interested in creating lists, both vertically and horizontally based on dumm...
How do I create a list of items (attributes) based on the dummy variable value?
Let's say I have a dataframe in python with a range of animals, and a range of attributes, with dummy variables for whether the animal has that attribute. I'm interested in creating lists, both vertically and horizontally based on dummy variable value. e.g. I'd like to: a) create a list of animals that have hair b) cre...
[ "You could use a dictionary to store values regarding the animals. And the first value of the values list can hold the 0 or 1 denoting hair on the animal.\nanimals = { \"Dog\": [ 1, 1 ], \"Fish\": [ 0, 1 ] }\n\n", "(a)\ndf[ df['Hair'] == 1 ]['Name'].to_list() \n\ndf.loc[ df['Hair'] == 1, 'Name'].to_list()\n\n(b)\...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074186241_list_python.txt
Q: PyPDF2 PdfFileWriter has no attribute stream I am trying to split a pdf into its pages and save each page as a new pdf. I have tried this method from a previous question with no success and the pypdf2 split example from here with no success. EDIT: I can see in my files that it does successfully write the first pag...
PyPDF2 PdfFileWriter has no attribute stream
I am trying to split a pdf into its pages and save each page as a new pdf. I have tried this method from a previous question with no success and the pypdf2 split example from here with no success. EDIT: I can see in my files that it does successfully write the first page, the second page pdf is then created but is empt...
[ "The same thing happened to me.\nI was able to solve it by moving the following line inside the loop:\ninputpdf = PdfFileReader(open(\"/home/ubuntu/inputs/cityshape/form5.pdf\", \"rb\"))\nI believe that some versions of PyPDF2 have some sort of bug, that when you invoke thePdfFileWriter.write method, it messes with...
[ 12, 1, 0, 0 ]
[]
[]
[ "pdf", "pypdf2", "python" ]
stackoverflow_0040168027_pdf_pypdf2_python.txt
Q: Change certain index value of string in a list ['0011111', '0011101', '0011110', '0011110', '0011100', '0010111', '0011000', '0011011', '0011000', '0010001', '0010100', '0010111', '0010110', '0010010', '0001110', '0001110', '0001010', '0001111', '0000111', '0001001', '0000101', '0001000', '0000100', '1000001'] Hi ...
Change certain index value of string in a list
['0011111', '0011101', '0011110', '0011110', '0011100', '0010111', '0011000', '0011011', '0011000', '0010001', '0010100', '0010111', '0010110', '0010010', '0001110', '0001110', '0001010', '0001111', '0000111', '0001001', '0000101', '0001000', '0000100', '1000001'] Hi newbie here, how can I change the first index string...
[ "If I understand you correctly, if first character of the string in the list is 1, change it to 0:\nlst = [\n \"0001000\",\n \"0000100\",\n \"1000001\",\n]\n\nlst = [f\"0{s[1:]}\" if s.startswith(\"1\") else s for s in lst]\nprint(lst)\n\nPrints:\n[\"0001000\", \"0000100\", \"0000001\"]\n\n\nEDIT: Using st...
[ 0, 0 ]
[]
[]
[ "indexing", "list", "python", "string" ]
stackoverflow_0074191924_indexing_list_python_string.txt
Q: Using Python and Pandas for a filtering code You’ll need to bring all your filtering skills together for this task. We’ve provided you a list of companies in the developers variable. Filter df however you choose so that you only get games that meet the following conditions: Sold in all 3 regions (North America, Eu...
Using Python and Pandas for a filtering code
You’ll need to bring all your filtering skills together for this task. We’ve provided you a list of companies in the developers variable. Filter df however you choose so that you only get games that meet the following conditions: Sold in all 3 regions (North America, Europe, and Japan) The Japanese sales were greater t...
[ "If I understand correctly, it looks like a multi-condition dataframe filtering:\ndf[\n df[\"developer\"].isin(developers) \\\n & (df[\"jp_sales\"] > df[\"na_sales\"] + df[\"eu_sales\"]) \\\n & ~df[\"na_sales\"].isnull()\n & ~df[\"eu_sales\"].isnull()\n & ~df[\"jp_sales\"].isnull()\n]\n\nIt will not retu...
[ 0, 0 ]
[]
[]
[ "dataframe", "filter", "pandas", "python" ]
stackoverflow_0074187961_dataframe_filter_pandas_python.txt
Q: creating database based on two dataframes I have two dataframes. One is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) Don't give up 12.02.2010 2 6 (5,6) ZIC ZAC 18.03.2010 2 7 7 Blablabla ...
creating database based on two dataframes
I have two dataframes. One is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) Don't give up 12.02.2010 2 6 (5,6) ZIC ZAC 18.03.2010 2 7 7 Blablabla 14.04.2010 2 8 2 Oh la la 14.05....
[ "Define you connection as below:\nimport sqlite3\nconn = sqlite3.connect('musicten.db')\n\n" ]
[ 3 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0074192353_database_python_sqlite.txt
Q: How do I get a list of tables from a Firebird database? So I've got a couple of Firebird databases I need to convert. I've managed to connect to them using python code and the kinterbasdb library, but I can't find a way to get a list of all the tables in the database. Is there a command that will give me the table...
How do I get a list of tables from a Firebird database?
So I've got a couple of Firebird databases I need to convert. I've managed to connect to them using python code and the kinterbasdb library, but I can't find a way to get a list of all the tables in the database. Is there a command that will give me the table names?
[ "Getting the list of tables is:\n\nIn isql: show tables;\nAs a normal query:\nSELECT a.RDB$RELATION_NAME\nFROM RDB$RELATIONS a\nWHERE COALESCE(RDB$SYSTEM_FLAG, 0) = 0 AND RDB$RELATION_TYPE = 0\n\n\n\n", "I use:\nSELECT RDB$RELATION_NAME FROM RDB$RELATIONS\nWHERE (RDB$SYSTEM_FLAG <> 1 OR RDB$SYSTEM_FLAG IS NULL) A...
[ 26, 5, 0 ]
[]
[]
[ "firebird", "kinterbasdb", "python" ]
stackoverflow_0021765586_firebird_kinterbasdb_python.txt
Q: How to properly open / close files in pytest? I have the following test case: @pytest.mark.parametrize('filename', [ ('test.pdf'), ('t est.pdf') ]) def test_should_work(filename: str): # given content_type = 'application/pdf' file = prepare_file_with_fixed_size(filename, MAX_FILE_SIZE) file...
How to properly open / close files in pytest?
I have the following test case: @pytest.mark.parametrize('filename', [ ('test.pdf'), ('t est.pdf') ]) def test_should_work(filename: str): # given content_type = 'application/pdf' file = prepare_file_with_fixed_size(filename, MAX_FILE_SIZE) files = [('file', (filename, file, 'application/pdf'))]...
[ "You almost have the answer... you should read more about exception in python.\nYou have to add a try/catch/finally section:\ndef test_should_work(filename: str):\n # given\n content_type = 'application/pdf'\n try:\n file = prepare_file_with_fixed_size(filename, MAX_FILE_SIZE)\n files = [('fi...
[ 0 ]
[]
[]
[ "io", "pytest", "python", "python_3.x" ]
stackoverflow_0074191628_io_pytest_python_python_3.x.txt
Q: Python csv with less separators than necessary I have a csv file with errors. Some rows have 4 separators (;), while most part of the rows have 5 separators (;). The reason why I have sometimes 4 separators is because sometimes the 2nd column is missing. Example: var1;var2;var3;var4;var5 1;10;john;40;56 2;mary;34;...
Python csv with less separators than necessary
I have a csv file with errors. Some rows have 4 separators (;), while most part of the rows have 5 separators (;). The reason why I have sometimes 4 separators is because sometimes the 2nd column is missing. Example: var1;var2;var3;var4;var5 1;10;john;40;56 2;mary;34;78 3;90.0;smith;52;45 If I import the csv file: imp...
[ "A workaround could be to shift part of the DataFrame:\n# read with shifted columns\ndf = pd.read_csv('myfile.csv', sep=';')\n\n# identify rows with incorrect data\nm = df['var5'].isna()\n# define columns to correct (second to last)\ncols = df.columns[1:]\n\n# correct the invalid rows\ndf.loc[m, cols] = df.loc[m, c...
[ 2, 2, 1, 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074192209_csv_pandas_python.txt
Q: using create_date Automatic fields in odoo I am follow odoo document and in chapter 9 I want to use Automatic field ( create_date) to compute value of another field this is my model. _name = "estate.offer" _description = "this is work as a offer offered to our real estate model" _log_access = True price = fields....
using create_date Automatic fields in odoo
I am follow odoo document and in chapter 9 I want to use Automatic field ( create_date) to compute value of another field this is my model. _name = "estate.offer" _description = "this is work as a offer offered to our real estate model" _log_access = True price = fields.Float() status = fields.Selection(selection=[('a...
[ "Odoo will raise the following error when it tries to compute the validity (_inverse_date_deadline):\nTypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime' \n\nThe date_deadline field is of type Date and create_date is of type DateTime.\nAnd the following error when it tries to compu...
[ 1 ]
[]
[]
[ "odoo", "python" ]
stackoverflow_0074185814_odoo_python.txt
Q: TypeError: 'NoneType' object is not subscriptable when i try to add a new element to a tuple I want to find an element in a matrix, and to add the line and column indexes to 2 tuples, but when i try to assign the new element to any tuple, I encounter this error: TypeError: 'NoneType' object is not subscriptable fr...
TypeError: 'NoneType' object is not subscriptable when i try to add a new element to a tuple
I want to find an element in a matrix, and to add the line and column indexes to 2 tuples, but when i try to assign the new element to any tuple, I encounter this error: TypeError: 'NoneType' object is not subscriptable from typing import NewType import numpy as np def find(element:int, matrix:np.array) ->tuple: '...
[ "You aren't looking at all the elements of matrix, so you don't find some of the elements you are searching for. The elements of range don't include stop.\nHaving not found your elements, you then index into the None that you got from find\nAs an aside, there is a numpy function that collects indexes where some con...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074192076_python.txt
Q: Modify default value of std::array using pybind11 My goal is to modify array which are declared in C++ struct and assigned with default value. I have read this, this, but unfortunately I cannot relate it with my problem. Sample Code C++ class Math{ struct Data { std::array<float, 5> id_ = {0}; // all value set...
Modify default value of std::array using pybind11
My goal is to modify array which are declared in C++ struct and assigned with default value. I have read this, this, but unfortunately I cannot relate it with my problem. Sample Code C++ class Math{ struct Data { std::array<float, 5> id_ = {0}; // all value set to ZERO std::array<uint32_t, 5> length_ = {0}; // al...
[ "Is the type of struct_obj.id_ a pythonic list? I assume this is the problem. In such a case, a new pythonic list is created as a copy of the C++ array to offer a convenient Pythonic interface. However, this list is not connected anymore to the underlying C++ object because a list can not be a reference to a std::a...
[ 0, 0 ]
[]
[]
[ "arrays", "c++", "pybind11", "python", "stl" ]
stackoverflow_0074140218_arrays_c++_pybind11_python_stl.txt
Q: How to add output parameter using sh I have this Python script: """ Get a monitor's details returns "OK" response """ from datadog_api_client import ApiClient, Configuration from datadog_api_client.v1.api.monitors_api import MonitorsApi id = int(input("Write the monitor ID: ")) configuration = Configuration() wit...
How to add output parameter using sh
I have this Python script: """ Get a monitor's details returns "OK" response """ from datadog_api_client import ApiClient, Configuration from datadog_api_client.v1.api.monitors_api import MonitorsApi id = int(input("Write the monitor ID: ")) configuration = Configuration() with ApiClient(configuration) as api_client: ...
[ ".sh file\npython3 test.py arg1 arg2 arg3\n\n.py file\nimport sys\narguments = sys.argv[1:]\nprint(arguments)\n# ['arg1', 'arg2', 'arg3']\n\n" ]
[ 0 ]
[]
[]
[ "python", "sh", "shell" ]
stackoverflow_0074192494_python_sh_shell.txt
Q: How to do CamelCase split in python What I was trying to achieve, was something like this: >>> camel_case_split("CamelCaseXYZ") ['Camel', 'Case', 'XYZ'] >>> camel_case_split("XYZCamelCase") ['XYZ', 'Camel', 'Case'] So I searched and found this perfect regular expression: (?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z...
How to do CamelCase split in python
What I was trying to achieve, was something like this: >>> camel_case_split("CamelCaseXYZ") ['Camel', 'Case', 'XYZ'] >>> camel_case_split("XYZCamelCase") ['XYZ', 'Camel', 'Case'] So I searched and found this perfect regular expression: (?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z]) As the next logical step I tried: >>>...
[ "As @AplusKminus has explained, re.split() never splits on an empty pattern match. Therefore, instead of splitting, you should try finding the components you are interested in.\nHere is a solution using re.finditer() that emulates splitting:\ndef camel_case_split(identifier):\n matches = finditer('.+?(?:(?<=[a-...
[ 62, 47, 13, 11, 6, 5, 3, 2, 2, 1, 0, 0, 0, 0 ]
[ "I think below is the optimim \nDef count_word():\n Return(re.findall(‘[A-Z]?[a-z]+’, input(‘please enter your string’))\nPrint(count_word())\n" ]
[ -2 ]
[ "camelcasing", "python", "regex" ]
stackoverflow_0029916065_camelcasing_python_regex.txt
Q: how can i upload multiple files to azure blob using python flask for web development im working on web development and im in the starting stage of it . i have created a website , in that website there is an html page asking to upload files ,im trying to upload the multiple files to azure blob at once but only the ...
how can i upload multiple files to azure blob using python flask for web development
im working on web development and im in the starting stage of it . i have created a website , in that website there is an html page asking to upload files ,im trying to upload the multiple files to azure blob at once but only the 1st file is getting uploaded . here is the code of html: enter code here <div class="car...
[ "\nYou can just call the request.files twice to get the other file.\n\napp= Flask(__name__)\n\n@app.route('/',methods=['GET','POST'])\n\ndef hello():\n if request.method == 'POST':\n first_file = request.files['file']\n Second_file = request.files['file1']\n\n return first_file.filename+\" \"+...
[ 0 ]
[]
[]
[ "azure_blob_storage", "flask", "flask_login", "flask_wtforms", "python" ]
stackoverflow_0074170272_azure_blob_storage_flask_flask_login_flask_wtforms_python.txt
Q: I would like to make a colormap from a matrix, with making difference, which way we have got the negative values We have two terms, two parameters (h, h0) and a variable T. We can define a certain value of T, where the difference of the two terms divided by L is equal to zero. With this T value, we can calculate g...
I would like to make a colormap from a matrix, with making difference, which way we have got the negative values
We have two terms, two parameters (h, h0) and a variable T. We can define a certain value of T, where the difference of the two terms divided by L is equal to zero. With this T value, we can calculate g0, gc and gs operators, and then witness1 and witness2. Then we make this whole calculation with running parameters (f...
[ "\nI'm sorry but I have simplified a little bit your witnessN functions, but I hope that you can adapt my solution, in which the key points are\n\nto save the values for the grid evaluations of witnessN\nto use Numpy's logical functions\nto use the fact that Booleans can be used as 0 or 1 integers,\n\nWith respect ...
[ 0 ]
[]
[]
[ "colormap", "imshow", "matplotlib", "numpy", "python" ]
stackoverflow_0074173600_colormap_imshow_matplotlib_numpy_python.txt
Q: Why does np.array**3 lead to a different solution than (np.array/1)**3 in my code? I wrote this code to calculate the integral in time of: Q = (Q_max*(1 - (time/t_0 - 1)**2)) which I derived analytically. import numpy as np Q_max = 400 # W m-2 t_0 = 6*3600 # seconds ...
Why does np.array**3 lead to a different solution than (np.array/1)**3 in my code?
I wrote this code to calculate the integral in time of: Q = (Q_max*(1 - (time/t_0 - 1)**2)) which I derived analytically. import numpy as np Q_max = 400 # W m-2 t_0 = 6*3600 # seconds dt = 60 # seconds time = np.arange(0,2*t_0,dt) Q_int...
[ "I looked into problem myself, and I get the same result. So at first time is a int32, but when you do time / 1 it becomes float64. It shouldn't bring problems by itself, but time contains some big numbers, and raising them to 3rd power results in overflowing (here's what i get), but it doesn't effect float, becaus...
[ 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074192296_numpy_python.txt
Q: pygame_gui textbox border styling Been trying to use pygame_gui within a program I'm currently developing, however, been having some trouble with the text box element styling. I've taken a look at their example repos and docs and made a theme.json accordingly. At the moment, all I want to do is style this one text...
pygame_gui textbox border styling
Been trying to use pygame_gui within a program I'm currently developing, however, been having some trouble with the text box element styling. I've taken a look at their example repos and docs and made a theme.json accordingly. At the moment, all I want to do is style this one text box to be transparent with no border (...
[ "Turns out I was missing quotation marks for the \"border_width\" and \"shadow_width\" values - I guess I missed it when no errors were thrown! ‍♀️\n" ]
[ 0 ]
[]
[]
[ "json", "pygame_gui", "python" ]
stackoverflow_0074124036_json_pygame_gui_python.txt
Q: Python sqlalchemy how to check if db empty? Im trying to make a function that will paste information into a database incase its empty i got it to work if i use customer_name = "Ilya" customer_details = session.query(db.Customers).filter( db.Customers.name == customer_name).first() but the problem is if th...
Python sqlalchemy how to check if db empty?
Im trying to make a function that will paste information into a database incase its empty i got it to work if i use customer_name = "Ilya" customer_details = session.query(db.Customers).filter( db.Customers.name == customer_name).first() but the problem is if the customer under the name "Ilya" gets removed it ...
[ "I realize this might be very obvious, but why do you filter your query?\nWhat if you did\nsession.query(db.Customers).first()\n\ninstead of\nsession.query(db.Customers).filter(db.Customers.name == customer_name).first()\n\nThen you could check if there are any users in the database instead of checking for a specif...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074192250_python_sqlalchemy.txt
Q: how to write file to another folder in python I am encrypting a file and it encrypts to a folder named mark but I want the file to encrypt and be placed in a sub folder named Kevin. Code is below: with open("encrypted_" + filename + '.txt', "wb") as ef: ef.write(encrypted_file) That encrypts the file but plac...
how to write file to another folder in python
I am encrypting a file and it encrypts to a folder named mark but I want the file to encrypt and be placed in a sub folder named Kevin. Code is below: with open("encrypted_" + filename + '.txt', "wb") as ef: ef.write(encrypted_file) That encrypts the file but places it in the same folder. How can i edit this so it...
[ "import shutil\n\nwith open(\"encrypted_\" + filename + '.txt', \"wb\") as ef:\n ef.write(encrypted_file)\n\nshutil.move(f\"encrypted_{filename}.txt\", \"Kevin\") #f\"encrypted_{filename}.txt\" is the file and \"Kevin\" is the Destination Folder\n\n", "If using linux, try to move it after encryption:\nimport s...
[ 0, 0 ]
[]
[]
[ "cryptography", "python", "security" ]
stackoverflow_0074192571_cryptography_python_security.txt
Q: Access target Python callable from Celery task instance Is there a way to access the callable Python object from a Celery task, either directly or through a lookup method (like Django's `get_model()). I've got a dot-notation reference to where the callable is declared but I need the actual object to get access to ...
Access target Python callable from Celery task instance
Is there a way to access the callable Python object from a Celery task, either directly or through a lookup method (like Django's `get_model()). I've got a dot-notation reference to where the callable is declared but I need the actual object to get access to it's attributes before sending / calling the task. I've scour...
[ "I was looking in the wrong place - importlib makes this fairly trivial. I was thinking it was something that I needed to get from Celery.\nimport importlib\nsplit_path = dot_notation_path.split(\".\")\nmodule_name, callable_name = \".\".join(split_path[:-1]), split_path[-1]\nmodule_object = importlib.import_module...
[ 0, 0 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0041744505_celery_django_python.txt
Q: python dialogbox in thread I wrote a simple test program which should continuisly ask the user for a float in a dialogbox without blocking the main program, here in the test I removed it for simplicity.: from time import sleep from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit from PyQt5.Qt...
python dialogbox in thread
I wrote a simple test program which should continuisly ask the user for a float in a dialogbox without blocking the main program, here in the test I removed it for simplicity.: from time import sleep from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit from PyQt5.QtGui import QIcon from datetime i...
[ "Does this help? In line 37-48, I removed, so there will no more error: RuntimeError: main thread is not in main loop\nwhile(end==0):\n if UI==0:\n UI=1\n th = threading.Thread(target=lambda q, arg1: q.put(ask(arg1)), args=(que, \"x\"))\n th.setDaemon(True)\n th.start()\n threa...
[ 0 ]
[]
[]
[ "dialog", "multithreading", "python" ]
stackoverflow_0071470696_dialog_multithreading_python.txt
Q: Django: Parse HTML (containing form) to dictionary I create a html form on the server side. <form action="." method="POST"> <input type="text" name="foo" value="bar"> <textarea name="area">long text</textarea> <select name="your-choice"> <option value="a" selected>A</option> <option value="b">B</option> </...
Django: Parse HTML (containing form) to dictionary
I create a html form on the server side. <form action="." method="POST"> <input type="text" name="foo" value="bar"> <textarea name="area">long text</textarea> <select name="your-choice"> <option value="a" selected>A</option> <option value="b">B</option> </select> </form> Desired result: { "foo": "bar", "area...
[ "This is not related to django, just to html parsing. The standard tool for that is the BeautifulSoup (bs4) library.\nIt parses arbitrary HTML, and is often used in web scrapers (including my own). This question covers parsing html forms: Python beautiful soup form input parsing, and pretty much everything you'll...
[ 5, 4, 3, 2, 2, 1, 0 ]
[]
[]
[ "django", "html_parsing", "python" ]
stackoverflow_0065570418_django_html_parsing_python.txt
Q: How to check if a column is not null based on another column in Python Basically I have 3 columns, Country, Period and Cost. I would like to find out if the Country column is populated with a value, then check if the cost & period colunn are also populated with a value. if the cost & period colunn dont have a valu...
How to check if a column is not null based on another column in Python
Basically I have 3 columns, Country, Period and Cost. I would like to find out if the Country column is populated with a value, then check if the cost & period colunn are also populated with a value. if the cost & period colunn dont have a value, then bring back the rows where it failed. so somethign like if country is...
[ "If i understood well your question (if country is not null, then return the rows which have at least one of the Period or Cost columns null) you can use boolean indexing in Pandas :\ndf[~df['Country'].isna() & (df['Period'].isna() | df['Cost'].isna())]\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074192618_python_python_3.x.txt
Q: Removing None values from DataFrame in Python Having the following dataframe: name aaa bbb Mick None None Ivan A C Ivan-Peter 1 None Juli 1 P I want to get two dataframes. One with values, where we have None in columns aaa and/or bbb, named filter_nulls in my code One where we do not have None at all. df_o...
Removing None values from DataFrame in Python
Having the following dataframe: name aaa bbb Mick None None Ivan A C Ivan-Peter 1 None Juli 1 P I want to get two dataframes. One with values, where we have None in columns aaa and/or bbb, named filter_nulls in my code One where we do not have None at all. df_out in my code. This is what I have tri...
[ "Use:\n#DataFrame from sample data\ndf_out = pd.DataFrame(df_out)\n\n#filter columns names by list and test if NaN or None at least in one row\nm = df_out[['aaa','bbb']].isna().any(axis=1)\n\n#OR test both columns separately\nm = df_out['aaa'].isna() | df_out['bbb'].isna()\n\n\n#filter matched and not matched rows\...
[ 1, 1 ]
[]
[]
[ "dataframe", "filter", "pandas", "python" ]
stackoverflow_0074192655_dataframe_filter_pandas_python.txt
Q: How to calculate current day streak in Django? I would like to calculate every time a ClassAttempt with a status "completed" is created or updated. class ClassAttempt(models.Model): user = models.ForeignKey(to=User,on_delete= models.PROTECT, null=True) related_class = models.ForeignKey(to=Class, related_na...
How to calculate current day streak in Django?
I would like to calculate every time a ClassAttempt with a status "completed" is created or updated. class ClassAttempt(models.Model): user = models.ForeignKey(to=User,on_delete= models.PROTECT, null=True) related_class = models.ForeignKey(to=Class, related_name='attempt', on_delete= models.PROTECT, null=True) ...
[ "I'm not sure to understand your issue but a post_save signal (https://docs.djangoproject.com/en/4.1/ref/signals/#post-save) allows you to run some python code every time the .save() method is called on a certain model. (Aslo works on model.objects.create())\nYou could check the status of the saved instance and inc...
[ 0, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074127309_django_python.txt
Q: Linear regression asymmetric coeffcient - dual beta in python In a regression framework, suppose we have two independent variables x1 and x2 and we want different slopes depending on x1>0 or x1<0, and same with x2. This sort of model is used in the computation of the dual beta, if you need an entry point to the l...
Linear regression asymmetric coeffcient - dual beta in python
In a regression framework, suppose we have two independent variables x1 and x2 and we want different slopes depending on x1>0 or x1<0, and same with x2. This sort of model is used in the computation of the dual beta, if you need an entry point to the literature. This topic has been presented at crossvalidated site (Li...
[ "From research, there are at least two posibilities.\n\nSplit variables regarding X>0|X<0 which is related with the provided link in the topic:\ndf[\"GPA+\"] = (df[\"GPA\"] >= 0) * df[\"GPA\"]\ndf[\"GPA-\"] = (df[\"GPA\"] < 0) * df[\"GPA\"]\n\nWhen having time attribute, the dual beta can be considered from the inc...
[ 1 ]
[]
[]
[ "asymmetric", "coefficients", "python", "regression" ]
stackoverflow_0074078098_asymmetric_coefficients_python_regression.txt
Q: Extract data from a txt I have a log of a simulation looking like this: Time = 1 smoothSolver: Solving for Ux, Initial residual = 1, Final residual = 0.0289664, No Iterations 2 smoothSolver: Solving for Uy, Initial residual = 1, Final residual = 0.028966, No Iterations 2 smoothSolver: Solving for Uz, Initial r...
Extract data from a txt
I have a log of a simulation looking like this: Time = 1 smoothSolver: Solving for Ux, Initial residual = 1, Final residual = 0.0289664, No Iterations 2 smoothSolver: Solving for Uy, Initial residual = 1, Final residual = 0.028966, No Iterations 2 smoothSolver: Solving for Uz, Initial residual = 1, Final residual =...
[ "You can use regular expressions, via standard package re\nimport re\n\nlog = \"\"\"\nTime = 1\n\nsmoothSolver: Solving for Ux, Initial residual = 1, Final residual = 0.0289664, No Iterations 2\nsmoothSolver: Solving for Uy, Initial residual = 1, Final residual = 0.028966, No Iterations 2\nsmoothSolver: Solving ...
[ 1 ]
[]
[]
[ "data_extraction", "python" ]
stackoverflow_0074192508_data_extraction_python.txt
Q: Return key value pair if value exists in dictionary Python I have the following dictionary and list: dict_ = {'one':['a','b','c','d','e','f'], 'two':['g','h','l','m'], 'three':['x','y','z'], 'four':['xx','yy']} ls = ['a','x','c','h','l'] I need to loop through the dict values and check if the items in ls exist i...
Return key value pair if value exists in dictionary Python
I have the following dictionary and list: dict_ = {'one':['a','b','c','d','e','f'], 'two':['g','h','l','m'], 'three':['x','y','z'], 'four':['xx','yy']} ls = ['a','x','c','h','l'] I need to loop through the dict values and check if the items in ls exist in dict values, if so I would like to return a new dict with key/...
[ "You can check overlaps with a set intersection -\nnew_dict = {k: list(set(v) & set(ls)) for k, v in dct.items() if (set(v) & set(ls))}\n\nOutput\n{'one': ['c', 'a'], 'two': ['l', 'h'], 'three': ['x']}\n\n", "_dict = {'one':['a','b','c','d','e','f'],\n'two':['g','h','l','m'],\n'three':['x','y','z']}\n\nls = ['a',...
[ 3, 2, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074192733_dictionary_list_python.txt
Q: Getting mean of specific column (not dataframe) and using it to replace every NAN value in related column Suppose I have this dataset and it had 2 NAN values in columns 'alcohol' and 3 NAN values in column 'magnesium'. They do not have NAN values, but suppose they did. What lines of code might I use to get not onl...
Getting mean of specific column (not dataframe) and using it to replace every NAN value in related column
Suppose I have this dataset and it had 2 NAN values in columns 'alcohol' and 3 NAN values in column 'magnesium'. They do not have NAN values, but suppose they did. What lines of code might I use to get not only the mean of the appropriate column (alcohol mean for alcohol), but also fill/replace alcohol NAN values with ...
[ "Try this:\ndf.fillna(df[[\"alcohol\", \"magnesium\"]].mean())\n\nExample:\ndf = pd.DataFrame({\n \"col1\": [1, 2, 3, np.NaN, 5, 6],\n \"alcohol\": [1, 2, 3, np.NaN, np.NaN, 6],\n \"magnesium\": [1, np.NaN, np.NaN, np.NaN, 5, 6],\n \"col4\": [1, 2, 3, np.NaN, 5, 6]})\n\ndf.fillna(df[[\"alcohol\", \"magn...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074192779_pandas_python.txt
Q: Is using a dictionary of lambda functions an acceptable way to write code? I wanted to code a function that returns the number of days of a given month on a given year (for Project Euler 19). Of course it's very easy to do this with if statements but, for the sheer pleasure of seeing such a way work in Python, I d...
Is using a dictionary of lambda functions an acceptable way to write code?
I wanted to code a function that returns the number of days of a given month on a given year (for Project Euler 19). Of course it's very easy to do this with if statements but, for the sheer pleasure of seeing such a way work in Python, I decided to use a dictionary with lambda-functions as values: md={ 'jan':lambd...
[ "You can just remove the strings so you don't have to eval it:\nmd = {\n 'jan': lambda y: 31,\n 'feb': lambda y: 29 if ((y % 400 == 0) or (y % 4 == 0 and y % 100)) else 28,\n 'mar': lambda y: 31,\n 'apr': lambda y: 30,\n 'may': lambda y: 31,\n 'jun': lambda y: 30,\n 'jul': lambda y: 31,\n 'a...
[ 2 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0074192882_lambda_python.txt
Q: Pass operator to function that selects on dataframe How to pass operator (eq, ne, gt etc.) to dataframe select function? import pandas as pd from operator import eq, ne df = pd.DataFrame({'Greet Ing': ['Hi Friend', 123, 'Hi Friend', '456']}) df[df['Greet Ing'] == 'Hi Friend'] df.query("`Greet Ing` == 'Hi Friend'...
Pass operator to function that selects on dataframe
How to pass operator (eq, ne, gt etc.) to dataframe select function? import pandas as pd from operator import eq, ne df = pd.DataFrame({'Greet Ing': ['Hi Friend', 123, 'Hi Friend', '456']}) df[df['Greet Ing'] == 'Hi Friend'] df.query("`Greet Ing` == 'Hi Friend'") def filter(dataframe, column, operator, value): ...
[ "Create function with pass Series to operator:\nfrom operator import eq, ne\n\ndef f(df1, c, op, y):\n return df1[op(df1[c], y)]\n\ndf2 = f(df, 'Greet Ing', eq, 'Hi Friend')\nprint (df2)\n Greet Ing\n0 Hi Friend\n2 Hi Friend\n\nOr you can map operator by dictionary:\nfrom operator import eq, ne\n\nops = {'==...
[ 1 ]
[]
[]
[ "dataframe", "operators", "pandas", "python" ]
stackoverflow_0074192931_dataframe_operators_pandas_python.txt
Q: How can I access variable, which was assigned in another python script? I have two scripts, let's say "reading" and "calculation". Script "reading" has inside of it several functions, and reads data from csv files and creates pandas dataframes. Let's say it defines variable "dataframe_1". Script "calculation" make...
How can I access variable, which was assigned in another python script?
I have two scripts, let's say "reading" and "calculation". Script "reading" has inside of it several functions, and reads data from csv files and creates pandas dataframes. Let's say it defines variable "dataframe_1". Script "calculation" makes some calculation with dataframes, which were defined in script "reading". I...
[ "First write a function or a method that returns a dataframe in reading.py e.g.\ndef foo(arguments):\n # create dataframe\n # return dataframe\n\nThen, import foo in calculation.py to generate dataframe:\nfrom reading import foo\ndataframe = foo(arguments)\n\n# do calculations on dataframe\n\nOR\nIn reading.py:...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074192590_pandas_python.txt
Q: Python type hinting with exceptions I have a function that looks like this: def check_for_errors(result): if 'success' in result: return True if 'error' in result: raise TypeError return False In successful run of this function, I should get a bool, but if there is an error I should ...
Python type hinting with exceptions
I have a function that looks like this: def check_for_errors(result): if 'success' in result: return True if 'error' in result: raise TypeError return False In successful run of this function, I should get a bool, but if there is an error I should get a TypeError- which is OK because I de...
[ "Type hinting can't say anything about exceptions. They are entirely out of scope for the feature. You can still document the exception in the docstring however. \nFrom PEP 484 -- Type Hints:\n\nExceptions\nNo syntax for listing explicitly raised exceptions is proposed. Currently the only known use case for this fe...
[ 115, 11, 3 ]
[]
[]
[ "exception", "python", "python_3.x", "python_typing", "type_hinting" ]
stackoverflow_0044282268_exception_python_python_3.x_python_typing_type_hinting.txt
Q: python - json with multiple object to csv I receive files (json) from time to time from AWS sns. Some of them contain only 1 object, some other have several objects. I am trying to run a python script to extract a couple of columns as example but I get multiple errors due to this several objects or the format of t...
python - json with multiple object to csv
I receive files (json) from time to time from AWS sns. Some of them contain only 1 object, some other have several objects. I am trying to run a python script to extract a couple of columns as example but I get multiple errors due to this several objects or the format of the file. Ideally I want to get all the data int...
[ "You can try this to include all fields from json to csv file.\nimport pandas as pd\nimport json\n\ndf=pd.read_json('test.json',lines=True)\nnewdf=[]\nfor i,row in df.iterrows():\n data=json.loads(row['Message'])\n row['timestamp']=data['mail']['timestamp']\n row['eventType']=data['eventType']\n newdf.a...
[ 0, 0 ]
[]
[]
[ "csv", "json", "multiple_columns", "parsing", "python" ]
stackoverflow_0074192052_csv_json_multiple_columns_parsing_python.txt
Q: Convert TF Object Detection API model to TFLite Please help in following iam really stuck when I converting with following code !python models/research/object_detection/export_tflite_graph_tf2.py \ --trained_checkpoint_dir {'/content/drive/MyDrive/customTF2/training'} \ --output_directory {'/content/drive/...
Convert TF Object Detection API model to TFLite
Please help in following iam really stuck when I converting with following code !python models/research/object_detection/export_tflite_graph_tf2.py \ --trained_checkpoint_dir {'/content/drive/MyDrive/customTF2/training'} \ --output_directory {'/content/drive/MyDrive/customTF2/tflite'} \ --pipeline_config_pa...
[ "https://github.com/tensorflow/models/commit/ecdab2324c65504ab52986e2bb5b64edda38f19e\nThe update is not ok. Reports have been made.\nTry to comment out line 99 it did work for me\n" ]
[ 1 ]
[]
[]
[ "python", "tensorflow", "tflite" ]
stackoverflow_0074182048_python_tensorflow_tflite.txt
Q: Selenium translate page to English not working I have a simple code that scrapes the Polish betting site and stores data in the csv file. I would like to have market names translated from Polish to English in csv file. My current solution is not working, instead, it opens a new instance of chrome with an empty pag...
Selenium translate page to English not working
I have a simple code that scrapes the Polish betting site and stores data in the csv file. I would like to have market names translated from Polish to English in csv file. My current solution is not working, instead, it opens a new instance of chrome with an empty page, and my code breaks. Here is my code: from os impo...
[ "You should put the following block\noptions = webdriver.ChromeOptions()\nprefs = {\n \"translate_whitelists\": {\"po\":\"en\"},\n \"translate\":{\"enabled\":\"True\"}\n}\noptions.add_experimental_option('prefs', prefs)\ndriver = webdriver.Chrome('C:/Users/peroperic/source/repos/chromedriver.exe',chrome_options=o...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074192940_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt
Q: How to apply different functions to the respective items in a dask bag, similar to bag.to_textfiles(_, name_function) Core Problem So in dask you can do import dask.bag as db bag = db.from_sequence([1, 2, 3, 4, 5]) # Save with file names "name_function(i), where i is incremented. bag.to_textfiles(path, name_funct...
How to apply different functions to the respective items in a dask bag, similar to bag.to_textfiles(_, name_function)
Core Problem So in dask you can do import dask.bag as db bag = db.from_sequence([1, 2, 3, 4, 5]) # Save with file names "name_function(i), where i is incremented. bag.to_textfiles(path, name_function) where a slightly different function, namely the name_function with different index, is applied to the saving operati...
[ "So thanks to Michael Delgado's comments I can now present a solution for the core problem, as well as the more concrete problem.\nCore Answer\nI will give a minimal example for how to apply a set of different functions to the elements of a Bag object:\nfrom math import ceil, floor # example functions\n\nimport da...
[ 1 ]
[]
[]
[ "dask", "python" ]
stackoverflow_0074183816_dask_python.txt
Q: .NET character class subtraction support in Python I have this regex ("^[-A-Z0-9-[O]]{1,8}$") comming from a client requirement (normally should not be changed). But it doesn't work in python (it works in C). from re import search var = "MY01C0DE" regex = "^[-A-Z0-9-[O]]{1,8}$" print(search(regex, var)) this pr...
.NET character class subtraction support in Python
I have this regex ("^[-A-Z0-9-[O]]{1,8}$") comming from a client requirement (normally should not be changed). But it doesn't work in python (it works in C). from re import search var = "MY01C0DE" regex = "^[-A-Z0-9-[O]]{1,8}$" print(search(regex, var)) this prints None. But if I change the regex to "^[-A-NP-Z0-9]{1...
[ "You can use PyPi regex module that supports .NET-like character class subtraction and use\nfrom regex import search, V1\n\nvar = \"MY01C0DE\"\nregex = \"^[-A-Z0-9-[O]]{1,8}$\"\nprint(search(regex, var, V1))\n# => <regex.Match object; span=(0, 8), match='MY01C0DE'>\n\nSee the Python demo.\nCheck the \"Nested sets a...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074192968_python_regex.txt
Q: To plot specific date on time series data I am trying to plot specific dates on time series dataset using matplotlib. Those dates indicates some events which I would like to highlight. I want to do this for multiple dates. I was able to do it for one date which worked for me but not for multiple dates. Can someone...
To plot specific date on time series data
I am trying to plot specific dates on time series dataset using matplotlib. Those dates indicates some events which I would like to highlight. I want to do this for multiple dates. I was able to do it for one date which worked for me but not for multiple dates. Can someone help me out in plotting multiple dates? from d...
[ "import matplotlib.pyplot as plt\nimport datetime\nimport pandas as pd\nimport numpy as np\n\n\n# Generate toy data\ndf =pd.DataFrame({'var': np.random.randint(low = 3,high=8,size=365)}, \n index=pd.date_range(start='2022-01-01', end='2022-12-31', freq='D'),\n\n)\n\nplt.figure(figsize = (10, 5))\n# plot the ...
[ 0 ]
[]
[]
[ "datetime", "matplotlib", "pandas", "python" ]
stackoverflow_0074191581_datetime_matplotlib_pandas_python.txt
Q: How to make Cython use the correct shared library? I am currently trying to write a wrapper for a C library. It works perfectly locally, but has to be run on a remote server on which I do not have admin privileges. A compiled version of the C library and include files is available in a known folder that I will den...
How to make Cython use the correct shared library?
I am currently trying to write a wrapper for a C library. It works perfectly locally, but has to be run on a remote server on which I do not have admin privileges. A compiled version of the C library and include files is available in a known folder that I will denote hereafter as /correct/folder. I first tried using a ...
[ "Well, managed to do it (always after posting the question, of course...).\nHad to use -Wl,-rpath,/correct/folder instead of -Wl,-rpath-link,/correct/folder.\n" ]
[ 0 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0074191692_cython_python.txt
Q: Python Chess Game, object has no attribute error I am currently making a chess game in python but keep coming up with an error that says "AttributeError: 'GameState' object has no attribute 'board'", however I'm pretty certain it should have this attribute . Any ideas on how to fix this? This is the main file: imp...
Python Chess Game, object has no attribute error
I am currently making a chess game in python but keep coming up with an error that says "AttributeError: 'GameState' object has no attribute 'board'", however I'm pretty certain it should have this attribute . Any ideas on how to fix this? This is the main file: import pygame as p from engine import * WIDTH = 512 HEI...
[ "Simple, you wrote __innit__ instead of __init__ in the class constructor which means it doesn't execute that function which leads to not creating the variable self.board\n" ]
[ 1 ]
[]
[]
[ "chess", "python" ]
stackoverflow_0074193035_chess_python.txt
Q: Oracle xmlagg with SQLAlchemy I have a column aggregation scenario where the result could be longer than 4000 characters, so I am trying to switch from listagg to xmlagg. Here's what I have right now that works as expected: func.listagg(aggregator, separator).within_group(*order_by) However, I couldn't find any e...
Oracle xmlagg with SQLAlchemy
I have a column aggregation scenario where the result could be longer than 4000 characters, so I am trying to switch from listagg to xmlagg. Here's what I have right now that works as expected: func.listagg(aggregator, separator).within_group(*order_by) However, I couldn't find any examples of xmlagg in SQLAlchemy doc...
[ "\nIs the xmlagg supported at all in SQLAlchemy?\n\nLike any other function, it should work with SQLAlchemy.\n>>> from sqlalchemy import func, select\n>>>\n>>> f1 = func.xmlagg(func.xmlelement(\"foo_tag\", \"foo_column_aggregator\", 'foo_separator'))\n>>>\n>>> print(select(f1))\nSELECT xmlagg(xmlelement(:xmlelement...
[ 1, 0 ]
[]
[]
[ "oracle", "python", "sql", "sqlalchemy" ]
stackoverflow_0074127206_oracle_python_sql_sqlalchemy.txt
Q: Number of digits in MNIST data in python How can I find the number of samples per digit in training and test sets? Also if I want to >visualize at least 9 images for each digit in the training data. #Loading MNIST data set in Python no_of_different_labels = 10 image_pixels = image_size * image_size``` #Load...
Number of digits in MNIST data in python
How can I find the number of samples per digit in training and test sets? Also if I want to >visualize at least 9 images for each digit in the training data. #Loading MNIST data set in Python no_of_different_labels = 10 image_pixels = image_size * image_size``` #Loading Training Samples ```train_data = np.loadt...
[ "I think you can use Numpy's unique function, and zip both the resulting numbers and counts into a dictionary that indicates the digit counts:\n# y_train is the same as your t_train. It's usual to name label arrays with \"y\" :-)\n\n# Count elements, and return unique numbers and their counts\nunique, counts = np.u...
[ 1 ]
[]
[]
[ "anaconda3", "jupyter_notebook", "mnist", "python", "python_3.x" ]
stackoverflow_0072580800_anaconda3_jupyter_notebook_mnist_python_python_3.x.txt
Q: Std output is correct but Output column is empty in leet code I solved a simple leet code problem the std output is correct but output is not. At first I thought it was because I am printing not returning the value, but the same problem occurs even if I return it. Can someone help me with this Thank you in advance...
Std output is correct but Output column is empty in leet code
I solved a simple leet code problem the std output is correct but output is not. At first I thought it was because I am printing not returning the value, but the same problem occurs even if I return it. Can someone help me with this Thank you in advance class jimpack: def reduce(num): if(num%2==0): ...
[ "I had the same issue with another question in python...\nfound this in looking for answers and helped me alot so hopefully it helps you too.\nhttps://support.leetcode.com/hc/en-us/articles/360011834174-I-encountered-Wrong-Answer-Runtime-Error-for-a-specific-test-case-When-I-test-my-code-using-this-test-case-it-pro...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074090153_python_python_3.x.txt
Q: locust does not work when I started worker node, because of failed to connect master node from worker node What happened? locust does not work when I started worker node, because of failed to connect master node from worker node. the below is details. this problem occasionally happens. $ locust -f /path/to/a.py ...
locust does not work when I started worker node, because of failed to connect master node from worker node
What happened? locust does not work when I started worker node, because of failed to connect master node from worker node. the below is details. this problem occasionally happens. $ locust -f /path/to/a.py --config=config/master.conf [2022-10-25 17:56:34,618] PC-0003395.local/INFO/locust.main: Starting web interface ...
[ "Everything looks right in your setup. The only thing I can think of is macOS’s software firewall (the one that pops up and asks you something along the lines of ”is it ok for Python to receive incoming connections?”)\nTry setting master-bind-host = 127.0.0.1 in master.conf, that might help with that.\n" ]
[ 0 ]
[]
[]
[ "locust", "python" ]
stackoverflow_0074191756_locust_python.txt
Q: app packed with pyinstaller don't open file from temporary directory (tkinter, tksvg, tempfile) Hi everyone I have a problem with a simple app (at least the MRE is simple) packed with pyinstaller. This desktop app should display a simple SVG file (I use tksvg). My app first writes SVG into a temporary directory (w...
app packed with pyinstaller don't open file from temporary directory (tkinter, tksvg, tempfile)
Hi everyone I have a problem with a simple app (at least the MRE is simple) packed with pyinstaller. This desktop app should display a simple SVG file (I use tksvg). My app first writes SVG into a temporary directory (writing is not as simple as in MRE), and then in the right moment displays it. It works nicely until I...
[ "Pyinstaller places your assets (images, icons, whatever) in a special directory that's created in your temp dir at runtime. I use this fetch_resource function to dynamically load assets when running a pyinstaller executable\nimport sys\nfrom pathlib import Path\n\n\ndef fetch_resource(rsrc_path):\n \"\"\"Loads ...
[ 1, 1 ]
[]
[]
[ "pyinstaller", "python", "temporary_files", "tkinter" ]
stackoverflow_0074182018_pyinstaller_python_temporary_files_tkinter.txt
Q: searching/filtering on negative days and time in column I want to filter/search on negative dates/times in a column. I already filtered the difference between dates, dropped NaN and create frame via: df = (df['date1'] - df['date2']).dropna().to_frame(name=None) Result of dataset 0 0 8 days 00:00:00 1 8 d...
searching/filtering on negative days and time in column
I want to filter/search on negative dates/times in a column. I already filtered the difference between dates, dropped NaN and create frame via: df = (df['date1'] - df['date2']).dropna().to_frame(name=None) Result of dataset 0 0 8 days 00:00:00 1 8 days 00:00:00 2 43 days 00:00:00 3 -42 days 06:50:00 4 1...
[ "Filtering out the unwanted days beforehand can be more handy:\ndf = df.query('date1 > date2').eval('date1 - date2').dropna().to_frame(name=None) \n\n", "Filter negative Timedeltas from subtracted Series:\ns = df['date1'] - df['date2']\n\nout = s[s < pd.Timedelta(0)].to_frame(0) \n\n" ]
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074193316_pandas_python.txt
Q: How to save a Dictionary inside a Pandas DataFrame? Context I have a Pandas DataFrame and a Use Case, where I need to store a Collection (Dictionary) in of the Columns. I do know, that a DataFrame is probably not designed for this, however, I am looking for a simple solution without Relationships between multiple ...
How to save a Dictionary inside a Pandas DataFrame?
Context I have a Pandas DataFrame and a Use Case, where I need to store a Collection (Dictionary) in of the Columns. I do know, that a DataFrame is probably not designed for this, however, I am looking for a simple solution without Relationships between multiple DataFrames, Series, etc. I am currently getting the follo...
[ "Repeat list of dict by multiple by length of DataFrame:\ndata['Procedures'] = [procedures] * len(data)\n\n" ]
[ 1 ]
[ "To save a Dictionary inside a Pandas DataFrame use pd.DataFrame.from_dict(input_dict).\nIf you think it's not clear, refer to this link.\n" ]
[ -1 ]
[ "dataframe", "dictionary", "pandas", "python", "series" ]
stackoverflow_0074192903_dataframe_dictionary_pandas_python_series.txt
Q: How to replace a text with another text in several txt-files at the same time I want to know how to replace a text with another text in several txt-files at the same time. I have several files with the name S-n, n = 1,...,29, and I want to keep the same name for the new txt files. Here is the code that I've found ...
How to replace a text with another text in several txt-files at the same time
I want to know how to replace a text with another text in several txt-files at the same time. I have several files with the name S-n, n = 1,...,29, and I want to keep the same name for the new txt files. Here is the code that I've found through internet for one file at a time: # creating a variable and storing the text...
[ "First, to the error message you posted\n(No such file or directory: 'S-1')\nIn short, your Python script cannot find the text file S-1.txt that you reference.\nCheck that your python script is next to your text file, like below:\n ├── Your_Main_Folder\n ├──── Your_Python_File.py\n └──── S-1.txt\n\nThe important...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074191831_python.txt
Q: Or condition in element_to_be_clickable selenium/python Looking for idea how to resolve my problem with "or" statement inside .element_to_be_clickable function in python-selenium. I want to my script click one of few (elements)buttons if one of them are clickable(I want to list them in this method with full xpath....
Or condition in element_to_be_clickable selenium/python
Looking for idea how to resolve my problem with "or" statement inside .element_to_be_clickable function in python-selenium. I want to my script click one of few (elements)buttons if one of them are clickable(I want to list them in this method with full xpath. For now it works only for one button(/html/body/button[1]). ...
[ "There is any_of expected_condition.\nAs per documentation:\nAn expectation that any of multiple expected conditions is true.\nEquivalent to a logical 'OR'.\nReturns results of the first matching condition, or False if none do.\n\nThe example of use of it looks like:\nWebDriverWait(driver, 20).until(\n EC.any_of...
[ 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074193372_python_python_3.x_selenium_selenium_webdriver_webdriverwait.txt
Q: How can i redirect to an external page from fastapi's exception handler I'm writing a web-app that has to support Single-Sign-On through Saml. The back-end is made with FastAPI and the front end is made in react. Nginx is used to proxy requests to the backend. I have an endpoint for logins that returns a redirect ...
How can i redirect to an external page from fastapi's exception handler
I'm writing a web-app that has to support Single-Sign-On through Saml. The back-end is made with FastAPI and the front end is made in react. Nginx is used to proxy requests to the backend. I have an endpoint for logins that returns a redirect request to an identity provider. When accessing the endpoint directly through...
[]
[]
[ "This looks more like a front-end issue since as you are saying everything works as expected when you access the endpoint in the browser.\nI think the issue here is that the library you are using to make API requests from your front end application does not follow redirect. For example axios does not do that out of...
[ -1 ]
[ "cors", "fastapi", "python", "saml" ]
stackoverflow_0074193420_cors_fastapi_python_saml.txt
Q: Creating database based on two dataframes INSERT VALUES I have two dataframes. One is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) And another dataframe called singer Singer nationality S...
Creating database based on two dataframes INSERT VALUES
I have two dataframes. One is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) And another dataframe called singer Singer nationality Singer_ID JT Watson USA 1 Rafinha Brazil...
[ "First, do not import sqlite3 the second time. Also, you still have an open connection.\nTwo issues with the SQL:\n'Let''s go' (single quote character must be doubled/escaped\ntuple([4,5]) => '(4,5)'\n" ]
[ 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074193450_python_sqlite.txt
Q: Map key to length of value in dictionary I would like to create another dictionary where the output will be new_dic = {key: len(value)} Given a dictionary containing lists in its values. Example: dic = {'a':[1,2,3], 'b':[4,5], 'c':[6]} And I want to create new_dic from dic where the new_dic map keys to length of...
Map key to length of value in dictionary
I would like to create another dictionary where the output will be new_dic = {key: len(value)} Given a dictionary containing lists in its values. Example: dic = {'a':[1,2,3], 'b':[4,5], 'c':[6]} And I want to create new_dic from dic where the new_dic map keys to length of value like this: new_dic = {'a':3, 'b':2, 'c'...
[ "Not much to explain here.\nnew_dic = {d:len(dic[d]) if type(dic[d]) in {tuple,list,dict} else 1 for d in dic}\n", "this will work even if you have an int not inside a list as the value in the dict\ndic = {'a':[1,2,3], 'b':[4,5] , 'c':6}\nnew_dic = {key: len(val) if type(val) in [tuple, list] else 1 for key, val ...
[ 2, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074193250_dictionary_python.txt
Q: Reading an Excel file in python using pandas I am trying to read an excel file this way : newFile = pd.ExcelFile(PATH\FileName.xlsx) ParsedData = pd.io.parsers.ExcelFile.parse(newFile) which throws an error that says two arguments expected, I don't know what the second argument is and also what I am trying to ach...
Reading an Excel file in python using pandas
I am trying to read an excel file this way : newFile = pd.ExcelFile(PATH\FileName.xlsx) ParsedData = pd.io.parsers.ExcelFile.parse(newFile) which throws an error that says two arguments expected, I don't know what the second argument is and also what I am trying to achieve here is to convert an Excel file to a DataFra...
[ "Close: first you call ExcelFile, but then you call the .parse method and pass it the sheet name.\n>>> xl = pd.ExcelFile(\"dummydata.xlsx\")\n>>> xl.sheet_names\n[u'Sheet1', u'Sheet2', u'Sheet3']\n>>> df = xl.parse(\"Sheet1\")\n>>> df.head()\n Tid dummy1 dummy2 dummy3 dummy4 dummy5 \\...
[ 254, 107, 22, 18, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "pandas", "python", "python_2.7" ]
stackoverflow_0017063458_pandas_python_python_2.7.txt
Q: I am trying to predict value of a an output through KN regression but getting an error This is the code used Also posted below is the error which is received File "C:\Users\Manoj\Videos\KNN.py", line 277, in <module> yhat = model.predict(new_data) File "C:\Users\Manoj\AppData\Roaming\Python\Python39\site-pac...
I am trying to predict value of a an output through KN regression but getting an error
This is the code used Also posted below is the error which is received File "C:\Users\Manoj\Videos\KNN.py", line 277, in <module> yhat = model.predict(new_data) File "C:\Users\Manoj\AppData\Roaming\Python\Python39\site-packages\sklearn\neighbors\_regression.py", line 241, in predict y_pred = np.mean(_y[neigh_...
[ "Your dataframe probably contains string which knn does not support\n" ]
[ 0 ]
[]
[]
[ "knn", "python", "scikit_learn" ]
stackoverflow_0074193511_knn_python_scikit_learn.txt
Q: Mongo get Distinct Value Pairs and a List of Values of a thrid attribute I have the following problem: I want to get the following information from a MongoDB using the Python driver: A list of two unique combinations of two attributes and a sublist of a third value with the attributes of the third value. Input: ...
Mongo get Distinct Value Pairs and a List of Values of a thrid attribute
I have the following problem: I want to get the following information from a MongoDB using the Python driver: A list of two unique combinations of two attributes and a sublist of a third value with the attributes of the third value. Input: [ { surname: "Will", lastname: "Smith", position:"Actor" }, { surname: "Mi...
[ "Your desired output is not a valid JSON so i'll assume you meant the following.\nYou just need to use $addToSet while grouping to get all unique positions, like so:\ndb.collection.aggregate([\n {\n \"$group\": {\n \"_id\": {\n \"surname\": \"$surname\",\n \"lastname\": \"$lastname\"\n }...
[ 1 ]
[]
[]
[ "aggregate", "mongodb", "python" ]
stackoverflow_0074193406_aggregate_mongodb_python.txt
Q: BeautifulSoup deleting first half of HTML? I'm practicing with BeautifulSoup and HTML requests in general for the first time. The goal of the programme is to load a webpage and it's HTML, then search through the webpage (in this case a recipe, to get a sub string of it's ingredients). I've managed to get it workin...
BeautifulSoup deleting first half of HTML?
I'm practicing with BeautifulSoup and HTML requests in general for the first time. The goal of the programme is to load a webpage and it's HTML, then search through the webpage (in this case a recipe, to get a sub string of it's ingredients). I've managed to get it working with the following code: url = "https://www.bb...
[ "You need to use:\nclass_=\"recipe__ingredients\"\n\nFor example:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.bbcgoodfood.com/recipes/healthy-tikka-masala\"\n\ndoc = (\n BeautifulSoup(requests.get(url).text, \"html.parser\")\n .find(class_=\"recipe__ingredients\")\n)\n\ningredients ...
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074193415_beautifulsoup_python_web_scraping.txt
Q: Python 3 Simon Says For Loop String Comparison I'm new to python 3 and I feel like I am learning in the worst way possible. Everything is through an online text-book called zybooks. I've been trying to understand for loops, and for the program I am supposed to write I have to use for loops. here are the instructi...
Python 3 Simon Says For Loop String Comparison
I'm new to python 3 and I feel like I am learning in the worst way possible. Everything is through an online text-book called zybooks. I've been trying to understand for loops, and for the program I am supposed to write I have to use for loops. here are the instructions: "Simon Says" is a memory game where "Simon" out...
[ "You'd have a much easier time using an index :\nuser_score = 0\nsimon_pattern = 'RRGBRYYBGY'\nuser_pattern = 'RRGBBRYBGY'\nfor i in range(len(simon_pattern)):\n if user_pattern[i] == simon_pattern[i]:\n user_score += 1\n\n", "The issue with your second attempt code (for s in simon_pattern ...) is that...
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "for_loop", "python", "string" ]
stackoverflow_0046762456_for_loop_python_string.txt
Q: How to add a URL into a dataFrame I'm trying to add a specific URL into a dataFrame in order to export the information into a csv. Every row of this csv has a specific ID added at the end of the URL attached The URL example would be like this: https://example.navigator.com/index.php?pagina=demoData;ID The problem...
How to add a URL into a dataFrame
I'm trying to add a specific URL into a dataFrame in order to export the information into a csv. Every row of this csv has a specific ID added at the end of the URL attached The URL example would be like this: https://example.navigator.com/index.php?pagina=demoData;ID The problem is that if I convert this into a strin...
[ "import pandas as pd\ns = 'https://example.navigator.com/index.php?pagina=demoData;ID'\npd.DataFrame([s,s]).to_csv('test.csv', sep=';')\n\ncreates\n;0\n0;\"https://example.navigator.com/index.php?pagina=demoData;ID\"\n1;\"https://example.navigator.com/index.php?pagina=demoData;ID\"\n\nIf you open it with Excel, you...
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python", "url" ]
stackoverflow_0074193497_csv_dataframe_pandas_python_url.txt
Q: Create fixtures from a list of countries in python Input below: list_1 = [TeamA,TeamB,TeamC,TeamD] Output should be like below TeamA TeamB TeamA TeamC TeamA TeamD TeamB TeamC TeamB TeamD TeamC TeamD A: list_1 = ['TeamA', 'TeamB', 'TeamC', 'TeamD'] print("\n".join([f"{a} {b}" for a in list_1 for b in list_1[list...
Create fixtures from a list of countries in python
Input below: list_1 = [TeamA,TeamB,TeamC,TeamD] Output should be like below TeamA TeamB TeamA TeamC TeamA TeamD TeamB TeamC TeamB TeamD TeamC TeamD
[ "list_1 = ['TeamA', 'TeamB', 'TeamC', 'TeamD']\nprint(\"\\n\".join([f\"{a} {b}\" for a in list_1 for b in list_1[list_1.index(a) + 1:]]))\n\nOutput:\nTeamA TeamB\nTeamA TeamC\nTeamA TeamD\nTeamB TeamC\nTeamB TeamD\nTeamC TeamD\n\n", "list_1 = [\"TeamA\",\"TeamB\",\"TeamC\",\"TeamD\"]\n\nfixtures = [[a, b] for i, ...
[ 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074193574_list_python.txt
Q: Is there a way to join nodes of a network based upon an underlying image? The Goal My aim here is to: Take a skeletonised image consisting of multiple intersecting non-straight lines Detect corners using a harris corner detect Join these corner nodes into a graph based upon whether two corners are connected by th...
Is there a way to join nodes of a network based upon an underlying image?
The Goal My aim here is to: Take a skeletonised image consisting of multiple intersecting non-straight lines Detect corners using a harris corner detect Join these corner nodes into a graph based upon whether two corners are connected by the underlying image The first two parts are relatively trivial using the skelet...
[ "The skan package might do what you need, as alluded to by Cris's comment. (Disclaimer: I am the main author of skan.)\n" ]
[ 0 ]
[]
[]
[ "image_processing", "python", "scikit_image", "scipy" ]
stackoverflow_0074188111_image_processing_python_scikit_image_scipy.txt
Q: Generate weeks from column with dates I have a large dataset which contains a date column that covers from the year 2019. Now I do want to generate number of weeks on a separate column that are contained in those dates. Here is how the date column looks like: import pandas as pd data = {'date': ['2019-09-10', '...
Generate weeks from column with dates
I have a large dataset which contains a date column that covers from the year 2019. Now I do want to generate number of weeks on a separate column that are contained in those dates. Here is how the date column looks like: import pandas as pd data = {'date': ['2019-09-10', 'NaN', '2019-10-07', '2019-11-04', '2019-11-...
[ "IIUC use:\ndf['date'] = pd.to_datetime(df['date'])\n\ndf['week'] = df['date'].sub(df['date'].iat[0]).dt.days // 7 + 1\nprint (df.head(10))\n date week\n0 2019-09-10 1.0\n1 NaT NaN\n2 2019-10-07 4.0\n3 2019-11-04 8.0\n4 2019-11-28 12.0\n5 2019-12-02 12.0\n6 2020-01-24 20.0\n7 2020-01-29 2...
[ 1, 1 ]
[]
[]
[ "dataframe", "date", "pandas", "python" ]
stackoverflow_0074193655_dataframe_date_pandas_python.txt
Q: Zlib not available after building a linux image with buildroot A similar question was asked 3 years ago with no answers: "ModuleNotFoundError: No module named 'zlib'” when I add python3 support with buildroot And I have tried the comment that says to make clean. I am trying to build a custom linux image using buil...
Zlib not available after building a linux image with buildroot
A similar question was asked 3 years ago with no answers: "ModuleNotFoundError: No module named 'zlib'” when I add python3 support with buildroot And I have tried the comment that says to make clean. I am trying to build a custom linux image using buildroot for a beaglebone. I have packaged a python application using t...
[ "I have solved this by using glibc in buildroot instead of mulibc.\n" ]
[ 0 ]
[]
[]
[ "buildroot", "python", "zlib" ]
stackoverflow_0074155437_buildroot_python_zlib.txt
Q: Creating DropDown List in Kivy using for loop in .kv file I am coding a system in kivy that requires the user to input a 3 letter abbreviation of a sports team's name. E.G 'ENG' for England like you would see on a scoreboard. I am trying to use dropdown menus to do this, and am writing these dropdowns in my .kv fi...
Creating DropDown List in Kivy using for loop in .kv file
I am coding a system in kivy that requires the user to input a 3 letter abbreviation of a sports team's name. E.G 'ENG' for England like you would see on a scoreboard. I am trying to use dropdown menus to do this, and am writing these dropdowns in my .kv file. However, at the moment I am having to write them by definin...
[ "You can either use a default method (like on_start) or a custom method (in which case you have to call it properly) as follows:\n def build(self):\n # Create the screen manager\n sm = ScreenManager()\n sm.add_widget(NamingScreen(name='name_screen'))\n return sm\n\n\n def on_start(...
[ 1 ]
[]
[]
[ "drop_down_menu", "for_loop", "kivy", "kivy_language", "python" ]
stackoverflow_0074192719_drop_down_menu_for_loop_kivy_kivy_language_python.txt
Q: How can I exclude words from frequency word analysis in a list of articles in python? I have a dataframe df with a column "Content" that contains a list of articles extracted from the internet. I have already the code for constructing a dataframe with the expected output (two columns, one for the word and the othe...
How can I exclude words from frequency word analysis in a list of articles in python?
I have a dataframe df with a column "Content" that contains a list of articles extracted from the internet. I have already the code for constructing a dataframe with the expected output (two columns, one for the word and the other for its frequency). However, I would like to exclude some words (conectors, for instance)...
[ "There are a few ways you can achieve this. You can either use the isin() method with a list comprehension,\ndata = {'test': ['x', 'NaN', 'y', 'z', 'gamma',]}\n\ndf = pd.DataFrame(data)\n\nwords = ['x', 'y', 'NaN']\n\ndf = df[~df.test.isin([word for word in words])]\n\nOr you can go with not string contains and a j...
[ 0 ]
[]
[]
[ "python", "word_frequency" ]
stackoverflow_0074193589_python_word_frequency.txt
Q: Python web app form generates excel or pdf after submit So I have this questions and answers form in a web application, most questions are input based, there are some that are checkbox, list or a date, but most are text/number input. I want that after the submit button it generates a link to download or downloads ...
Python web app form generates excel or pdf after submit
So I have this questions and answers form in a web application, most questions are input based, there are some that are checkbox, list or a date, but most are text/number input. I want that after the submit button it generates a link to download or downloads directly after the file is written. I cannot seem to find thi...
[ "Create a view in Django that accepts the POST request from the form.\nThen use library like reportLab to generate the pdf file.\nAfter you generated the pdf file you can return it like that:\nresponse = HttpResponse(file, content_type=\"application/pdf\")\nresponse[\"Content-Disposition\"] = 'attachment; filename=...
[ 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074193616_django_html_python.txt
Q: python runs but stop working and nothing happens I am trying to run the code, but it stops working when runs to print('continue') and then nothing happens at all. I have tried to install new python version and also other programs with classes work. Please, give me some hint why this doesn't run properly. import os...
python runs but stop working and nothing happens
I am trying to run the code, but it stops working when runs to print('continue') and then nothing happens at all. I have tried to install new python version and also other programs with classes work. Please, give me some hint why this doesn't run properly. import os import os.path import openpyxl from openpyxl import l...
[ "\nIs the Serbian for Sheet1 (Лист1) suppose to be there?\nDo the two XLSX files exist on the desktop (as chdir suggests)?\n\nConsider first trying the load_workbook functions instead of creating wobject -- just as a sanity check.\n" ]
[ 0 ]
[]
[]
[ "class", "execution", "openpyxl", "python" ]
stackoverflow_0074193364_class_execution_openpyxl_python.txt
Q: Store cell value of first few characters I am trying to change the name of a sheet according to the value of a cell. here is the code I am using. from openpyxl import load_workbook wb = load_workbook('file_name.xlsx') ws = wb['Sheet 1'] sheet_name = ws['B2'] ws.title = f'Marketing {sheet_name}' This code works...
Store cell value of first few characters
I am trying to change the name of a sheet according to the value of a cell. here is the code I am using. from openpyxl import load_workbook wb = load_workbook('file_name.xlsx') ws = wb['Sheet 1'] sheet_name = ws['B2'] ws.title = f'Marketing {sheet_name}' This code works, but my problem is I only need to extract th...
[ "Use slicing:\nsheet_name = ws['B2'].value[:3]\n\n", "You can use the characters in the string.\nEdit the parameters to get the desired result.\nfrom openpyxl import load_workbook\n\nwb = load_workbook('file_name.xlsx') \nws = wb['Sheet 1']\nsheet_name = ws['B2'].value\nws.title = f'Marketing {sheet_name[0:3]}' ...
[ 3, 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0074181512_excel_openpyxl_python.txt
Q: How to stop Python from crashing when the input is supposed to be an int but the user inputs a different data type? num = int(input("Number: ")) if num != int: def summer(): summed = 0 for i in str(num): summed += int(i) print(summed) if len(str(num)) != 5: print("Type a numb...
How to stop Python from crashing when the input is supposed to be an int but the user inputs a different data type?
num = int(input("Number: ")) if num != int: def summer(): summed = 0 for i in str(num): summed += int(i) print(summed) if len(str(num)) != 5: print("Type a number with 5 letters") else: print(*str(num), sep=", ") summer()
[ "You should use try\nwhile True:\n try:\n num = int(input('Number : '))\n break\n except ValueError:\n print('Value is not an integer, repeat')\n continue\n\n" ]
[ 0 ]
[]
[]
[ "input", "python" ]
stackoverflow_0074193735_input_python.txt
Q: Update one list with respect to another list in python I'm very new in python. I just stuck in one problem. I have two lists, like - list1 = [1,2,3,4,5] list2 = [3,6,8,9,1,2,4,0,5] Now I have to check each value of list1 with that it is present in list2 or not. If all the value of list1 is present in list2 then u...
Update one list with respect to another list in python
I'm very new in python. I just stuck in one problem. I have two lists, like - list1 = [1,2,3,4,5] list2 = [3,6,8,9,1,2,4,0,5] Now I have to check each value of list1 with that it is present in list2 or not. If all the value of list1 is present in list2 then update the list2 by removing extra values from list2. So list...
[ "One of the many options for performing the task\nlist1 = [1, 2, 3, 4, 5]\nlist2 = [3, 6, 8, 9, 1, 2, 4, 0, 5]\nlist2 = [num for num in list2 if num in list1 and set(list1).issubset(list2)]\n\n" ]
[ 1 ]
[]
[]
[ "for_loop", "list", "nested_loops", "python" ]
stackoverflow_0074193734_for_loop_list_nested_loops_python.txt
Q: TypeError: 'NoneType' object is not callable telebot i'm new to pyton. I got trubles with telegram bot. if i'm only send file everything works fine, but when i start from begining with entering data and generating pdf file and after that send file in bot my code crush with error: 2022-10-17 12:19:54,164 (__init__....
TypeError: 'NoneType' object is not callable telebot
i'm new to pyton. I got trubles with telegram bot. if i'm only send file everything works fine, but when i start from begining with entering data and generating pdf file and after that send file in bot my code crush with error: 2022-10-17 12:19:54,164 (__init__.py:878 MainThread) ERROR - TeleBot: "Infinity polling exce...
[ "I got it. If someone interested problem was in bot.register_next_step_handler. It can't provide arguments if function so instead of this:\nbot.register_next_step_handler(message, send_PDF(message, name, number, info, adress))\n\nI made this:\nsend_PDF(message, name, number, info, adress)\n\nAnd now everithing work...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074097264_python_python_3.x.txt
Q: Sum up true false in pandas df using plotly dash for visualization I have the following CSV Data: id,expNumber,attempt,finished,successful, 1,1,1,true,false, 1,1,2,false,false, 1,1,3,true,true, 1,2,1,false,false, 1,2,2,true,false, 1,2,3,true,true, 1,4,1,false,false, 1,4,2,false,...
Sum up true false in pandas df using plotly dash for visualization
I have the following CSV Data: id,expNumber,attempt,finished,successful, 1,1,1,true,false, 1,1,2,false,false, 1,1,3,true,true, 1,2,1,false,false, 1,2,2,true,false, 1,2,3,true,true, 1,4,1,false,false, 1,4,2,false,false, I want to use Plotly Dash and DashTable for visualization of the...
[ "I am not sure I understood your desired output:\nimport dash\nfrom dash.dependencies import Input, Output\nfrom dash import dash_table\nfrom dash import dcc\nfrom dash import html\nimport plotly.express as px\nimport pandas as pd\n\ndf = pd.read_csv(\"data.csv\")\n\ndf.set_index('id', inplace=True, drop=False)\n\n...
[ 1 ]
[]
[]
[ "pandas", "plotly", "plotly_dash", "python" ]
stackoverflow_0074191712_pandas_plotly_plotly_dash_python.txt
Q: How to create an array according to row and column names using pandas for example i have a data like csv file: x(col) y(row) Value 0 0 5 3 1 10 2 2 2 1 3 6 output: [[5,0,0,0]...
How to create an array according to row and column names using pandas
for example i have a data like csv file: x(col) y(row) Value 0 0 5 3 1 10 2 2 2 1 3 6 output: [[5,0,0,0], [0,10,0,0], [0, 0,2,0], [0, 0,0,6]]
[ "You can use a pivot_table:\na = (df\n .pivot_table(index='y(row)', columns='x(col)',\n values='Value', fill_value=0)\n .reindex(index=range(df['y(row)'].max()+1),\n columns=range(df['x(col)'].max()+1))\n .to_numpy()\n)\n\nOr numpy indexing:\na = np.zeros((df['y(row)'].max()+1, df['y...
[ 1, 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074193780_numpy_pandas_python.txt
Q: pandas df turn rows containing dict lists into new df and keep id I hope I can describe the problem clearly. I have a pandas df with 2 columns (date, person) that looks like this: date person 0 2002-09-04 [{'name':'anna', 'weight':'2.9', 'hospital':'x'}, {'name': 'jacob', ...}, ...] 1 2002-10-...
pandas df turn rows containing dict lists into new df and keep id
I hope I can describe the problem clearly. I have a pandas df with 2 columns (date, person) that looks like this: date person 0 2002-09-04 [{'name':'anna', 'weight':'2.9', 'hospital':'x'}, {'name': 'jacob', ...}, ...] 1 2002-10-16 [{'name':'lynn', 'weight':'3.0', 'hospital':'y'}, {'name': 'tony'...
[ "You can explode your list of dicionaries and convert them to column with pandas.json_normalize:\nout = (df\n .explode('person', ignore_index=True)\n .pipe(lambda d: d.join(pd.json_normalize(d.pop('person'))))\n)\n\noutput:\n date name weight hospital\n0 2002-09-04 anna 2.9 x\n1 2002-09-...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074193778_dataframe_pandas_python.txt
Q: pandas overlay on top of a plot I have some time series data in a pandas dataframe that I can visualise as follows: import pandas as pd d = {'end_time': [datetime.datetime(2020, 3, 17, 0, 0), datetime.datetime(2020, 3, 17, 0, 5), datetime.datetime(2020, 3, 17, 0, 10), datetime.datetime(2020, 3, 17, 0, 15), dateti...
pandas overlay on top of a plot
I have some time series data in a pandas dataframe that I can visualise as follows: import pandas as pd d = {'end_time': [datetime.datetime(2020, 3, 17, 0, 0), datetime.datetime(2020, 3, 17, 0, 5), datetime.datetime(2020, 3, 17, 0, 10), datetime.datetime(2020, 3, 17, 0, 15), datetime.datetime(2020, 3, 17, 0, 20), date...
[ "Considering this random dataframe, where\n\nend_time: dates starting from 2020-03-17 00:00:00 to 2020-03-17 00:55:00 with a 5 minutes interval\n\nmeasurement: random integers between 300 and 4000\n\nreliability: random integers between 0 and 100\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'end_t...
[ 1 ]
[]
[]
[ "dataframe", "date", "matplotlib", "pandas", "python" ]
stackoverflow_0074192039_dataframe_date_matplotlib_pandas_python.txt
Q: Printing count of a column based on value of another column I have a data frame: Dept_Name Placed A 1 B 0 C 1 Where 'Placed' column has a boolean value I want to print the count of rows that have the value '1' in placed grouped by the Dept_Name Dept_Name Count(Placed == 1) A 3 B 4 C 0 A: If values are 0...
Printing count of a column based on value of another column
I have a data frame: Dept_Name Placed A 1 B 0 C 1 Where 'Placed' column has a boolean value I want to print the count of rows that have the value '1' in placed grouped by the Dept_Name Dept_Name Count(Placed == 1) A 3 B 4 C 0
[ "If values are 0,1 or True/False you can aggregate sum, last for column Count use Series.reset_index:\ndf1 = df.groupby('Dept_Name')['Placed'].sum().reset_index(name='Count')\n\nIf test some non boolean values - e.g. count values 100:\ndf2 = df['Placed'].eq(100).groupby(df['Dept_Name']).sum().reset_index(name='Coun...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074193893_pandas_python.txt
Q: How do I get the index of a row where max value is not duplicated? Given this df from io import StringIO import pandas as pd data = StringIO('''gene_variant gene val1 val2 val3 b1 b 1 1 1 b2 b 2 11 1 b3 b 3 11 1 c2 c 1 1 1 t1 t 1 1 1 t2 t 12 2 2 t4 t 12 3 2 t5...
How do I get the index of a row where max value is not duplicated?
Given this df from io import StringIO import pandas as pd data = StringIO('''gene_variant gene val1 val2 val3 b1 b 1 1 1 b2 b 2 11 1 b3 b 3 11 1 c2 c 1 1 1 t1 t 1 1 1 t2 t 12 2 2 t4 t 12 3 2 t5 t 1 4 3 d2 d 11 1 2 d4 d 11 1 1''') df = pd.read_csv...
[ "If need maximum only for groups with no duplicated values is possible use:\n#per groups count number of unique values\ndf1 = df.groupby('gene').transform('nunique')\n\n#compare columns with `gene_variant` and set NaN if duplicates per columns\n \n#if maximum is count from all columns if not duplicated values get m...
[ 1, 1 ]
[]
[]
[ "group_by", "max", "pandas", "python", "python_3.x" ]
stackoverflow_0074193723_group_by_max_pandas_python_python_3.x.txt
Q: Breaking a python string in pandas dataframe I have a column 'released' which has values like 'June 13, 1980 (United States)' I want to get the year from this string so I tried using the following code df['year_correct'] = df['released'].astype(str).str[',':'('] But it is returning all the values as Nan in the ne...
Breaking a python string in pandas dataframe
I have a column 'released' which has values like 'June 13, 1980 (United States)' I want to get the year from this string so I tried using the following code df['year_correct'] = df['released'].astype(str).str[',':'('] But it is returning all the values as Nan in the new 'year_correct' column. Please help
[ "A better way might be to extract the 4 digits value using words delimiter (\\b) to ensure no more than 4 digits:\ndf['year_correct'] = df['released'].astype(str).str.extract(r'\\b(\\d{4})\\b')\n\nExample:\n released year_correct\n0 June 13, 1980 (United States) 1980\n\n" ]
[ 4 ]
[]
[]
[ "dataframe", "pandas", "python", "string", "substring" ]
stackoverflow_0074193915_dataframe_pandas_python_string_substring.txt
Q: How does python lists internally works with different elements types? Basically I want to know how can Python access elements in O(1) time in lists, when those elements are of different types. Example: my_list = [1,1.54,'hello'] # takes O(1) time my_list[1] A: Because all of them share one common type: object. ...
How does python lists internally works with different elements types?
Basically I want to know how can Python access elements in O(1) time in lists, when those elements are of different types. Example: my_list = [1,1.54,'hello'] # takes O(1) time my_list[1]
[ "Because all of them share one common type: object. Python stores an array of objects internally. Details vary with the capability of the language used for the implementation.\nTwo example implementations:\nCPython\nPyObject *\nPyList_GetItem(PyObject *op, Py_ssize_t i)\n{\n if (!PyList_Check(op)) {\n PyE...
[ 0 ]
[]
[]
[ "arrays", "data_structures", "python" ]
stackoverflow_0074193849_arrays_data_structures_python.txt
Q: Ec2 register target using lamda but getting error i am facing a chalenge if one of the given ec2 instance id is wrong then test run under lambda is not working and error ( i-9876277sgshj) is not in running state or not exists. So if an ec2 instance id was wrong why didn't it registere the correct ec2 instance(i-26...
Ec2 register target using lamda but getting error
i am facing a chalenge if one of the given ec2 instance id is wrong then test run under lambda is not working and error ( i-9876277sgshj) is not in running state or not exists. So if an ec2 instance id was wrong why didn't it registere the correct ec2 instance(i-26377gdhdhj) .please help if any ec2 instance id is wrong...
[ "One of the solution might be, add a feature into your python script wihch verifies/gets the instance id of ec2-instance on the fly. For this, first of all assign a unique tag to all ec2-instance which you are planning to register in TG. Then use ec2 list & describe function of boto3 for getting all instance ids, a...
[ 1 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "devops", "lambda", "python" ]
stackoverflow_0073990130_amazon_ec2_amazon_web_services_devops_lambda_python.txt
Q: How to create all possible phrases from two lists, with a few conditions to follow I have two lists alt, runs (a pair). they always have the same size. the items inside alt are going to be a random combination of the following five options: "verb", "article", "constant", "o-constant", "variable" the items of runs ...
How to create all possible phrases from two lists, with a few conditions to follow
I have two lists alt, runs (a pair). they always have the same size. the items inside alt are going to be a random combination of the following five options: "verb", "article", "constant", "o-constant", "variable" the items of runs are always different from one pair to another here is an example: alt = ["constant", "va...
[ "The idea is to start with what is certainly going to be in the output: the constants. And then add the articles/o-constants followed by the verbs according to their specific (slightly different) rule sets.\nIn the end, we sort the list according to the order in the input.\nIt's probably possible to optimize the co...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074193534_python.txt