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: How to merge two dataframes, where one is multi-indexed, with different headers I've been trying to merge two dataframes that look as below, one is multi-indexed while the other is not. FIRST DATAFRAME: bd_df outcome opp_name Sam 3 win Roy Jones 2 win Floyd Mayw...
How to merge two dataframes, where one is multi-indexed, with different headers
I've been trying to merge two dataframes that look as below, one is multi-indexed while the other is not. FIRST DATAFRAME: bd_df outcome opp_name Sam 3 win Roy Jones 2 win Floyd Mayweather 1 win Bernard Hopkins James 3 win James Bond ...
[ "I think you need merge by bout number in level of MultiIndex with index in bt_df:\nmain_df = (bd_df.reset_index()\n .merge(bt_df, \n left_on='bout number',\n right_index=True, \n how='left', \n suffixes=('_',''))...
[ 1 ]
[]
[]
[ "dataframe", "merge", "multi_index", "pandas", "python" ]
stackoverflow_0074613883_dataframe_merge_multi_index_pandas_python.txt
Q: Plotly: How to add volume to a candlestick chart code: from plotly.offline import init_notebook_mode, iplot, iplot_mpl def plot_train_test(train, test, date_split): data = [Candlestick(x=train.index, open=train['open'], high=train['high'], low=train['low'], close=train['close'],name='train'), C...
Plotly: How to add volume to a candlestick chart
code: from plotly.offline import init_notebook_mode, iplot, iplot_mpl def plot_train_test(train, test, date_split): data = [Candlestick(x=train.index, open=train['open'], high=train['high'], low=train['low'], close=train['close'],name='train'), Candlestick(x=test.index, open=test['open'], high=test[...
[ "If you looking add smaller subplot of volume just below OHLC chart, you can use:\n\nrows and cols to specify the grid for subplots.\nshared_xaxes=True for same zoom and filtering\nrow_width=[0.2, 0.7] to change height ratio of charts. ie. smaller volume chart than OHLC\n\nPlot:\n\nimport pandas as pd\nimport plotl...
[ 24, 23, 2, 1, 0 ]
[]
[]
[ "matplotlib", "plot", "plotly", "python" ]
stackoverflow_0064689342_matplotlib_plot_plotly_python.txt
Q: ImportError: Pandas requires version '3.0.7' or newer of 'openpyxl' (version '3.0.5' currently installed) I have a strange problem which leads to the msg in the title, leading to the error report below. The fact is - I have (on Linux) python 3.9.15, Pandas 1.5.2, openpyxl 3.0.10. I do not use venv, for editing I u...
ImportError: Pandas requires version '3.0.7' or newer of 'openpyxl' (version '3.0.5' currently installed)
I have a strange problem which leads to the msg in the title, leading to the error report below. The fact is - I have (on Linux) python 3.9.15, Pandas 1.5.2, openpyxl 3.0.10. I do not use venv, for editing I use Wing, but I do not run script from it, only from the shell. I looked over /usr/lib64/python3.9/site-packages...
[ "It turned out being cache question - no idea what created a site-package cache under ~/./local/ and why python looked there at first\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074612873_pandas_python_python_3.x.txt
Q: Pyinstaller --onefile warning file already exists but should not When running Pyinstaller --onefile, and starting the resulting .exe, multiple popups show up with the following warning: WARNING: file already exists but should not: C:\Users\myuser\AppData\Local\Temp\_MEI90082\Cipher\_AES.cp37-win_amd64.pyd This ma...
Pyinstaller --onefile warning file already exists but should not
When running Pyinstaller --onefile, and starting the resulting .exe, multiple popups show up with the following warning: WARNING: file already exists but should not: C:\Users\myuser\AppData\Local\Temp\_MEI90082\Cipher\_AES.cp37-win_amd64.pyd This makes the .exe hard to use even though clicking through the warnings sti...
[ "I have almost the same issue.\nNot a good idea - remove part of the list that you are iterating.\nTry this:\nfrom PyInstaller.building.datastruct import TOC\n\n# ...\n# a = Analysis(...)\n\nx = 'cp36-win_amd64'\ndatas_upd = TOC()\n\nfor d in a.datas:\n if x not in d[0] and x not in d[1]:\n datas_upd.appe...
[ 1, 0, 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0066069360_pyinstaller_python.txt
Q: Changing bad format of number and currency from user input to float number I need to write a script in Python which will transform bad input from user to float number. For example "10,123.20 Kč" to "10123.2" "10.023,123.45 Kč" to "10023123.45" "20 743 210.2 Kč" to "20743210.2" or any other bad input - this is what...
Changing bad format of number and currency from user input to float number
I need to write a script in Python which will transform bad input from user to float number. For example "10,123.20 Kč" to "10123.2" "10.023,123.45 Kč" to "10023123.45" "20 743 210.2 Kč" to "20743210.2" or any other bad input - this is what I've come up with. Kč is Czech koruna. My thought process was to get rid of any...
[ "You could select the find all numerics instead of trying to remove non-numerics\nIn any case you have to make some assumtpions about the input, here is the code assuming that a final block of two digits in a text with separators is the fractional part.\nimport re\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.0...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_re" ]
stackoverflow_0074613237_python_python_re.txt
Q: Read a binary mp4 to a numpy array I read this answer on how to pass an mp4 file from client to server using python's FastAPI. I can read the file into its binary form like as suggested: contents = file.file.read() contents Out[25]: b'\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00isommp42.. Now, I want to load the cont...
Read a binary mp4 to a numpy array
I read this answer on how to pass an mp4 file from client to server using python's FastAPI. I can read the file into its binary form like as suggested: contents = file.file.read() contents Out[25]: b'\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00isommp42.. Now, I want to load the content into a numpy array. I have looked on...
[ "So, I commented heavily about how unsure I am that it is really the thing to do, and how I suspect XY problem on this.\nBut, just to give a formal answer to the question, as is, I repeat here what I said in comments:\nnp.frombuffer(contents, dtype=np.uint8)\n\nIs the way to turn a byte string into a numpy array of...
[ 0 ]
[]
[]
[ "binaryfiles", "mp4", "numpy", "python" ]
stackoverflow_0074613682_binaryfiles_mp4_numpy_python.txt
Q: Python FastAPI/Uvicorn - External logger wont work? I am using logtail.com and for some reason it wont log ONLY in my FastAPI/UVICORN app, I tried using the package in an a different test python file and it worked? I dont understand what I am missing. I call the logger and it should work but it does not, additiona...
Python FastAPI/Uvicorn - External logger wont work?
I am using logtail.com and for some reason it wont log ONLY in my FastAPI/UVICORN app, I tried using the package in an a different test python file and it worked? I dont understand what I am missing. I call the logger and it should work but it does not, additionally I even do a log INSTANTLY after I instantiate the log...
[ "It should work, but only after you shutdown the API.\nLogging inside the main function before calling uvicorn.run() and inside endpoint routes should work as you expected.\nuvicorn.run() is a sync function. So the interpreter waits until the function has finished (API has shutdown) and executes the following state...
[ 1 ]
[]
[]
[ "fastapi", "logging", "python", "python_3.x", "uvicorn" ]
stackoverflow_0074605213_fastapi_logging_python_python_3.x_uvicorn.txt
Q: list comprehension to filter a list of lists This problem is from https://leetcode.com/problems/find-players-with-zero-or-one-losses/. Is it possible to use list comprehension in this problem to create a new list that only has the first item of every tuple that never shows up in the second item of any tuple. For i...
list comprehension to filter a list of lists
This problem is from https://leetcode.com/problems/find-players-with-zero-or-one-losses/. Is it possible to use list comprehension in this problem to create a new list that only has the first item of every tuple that never shows up in the second item of any tuple. For instance: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],...
[ "List comprehension works, but not optimised way to solve these sort of problems\nIn [48]: list(set([j[0] for j in matches if j[0] not in [i[1] for i in matches]]))\nOut[48]: [1, 2, 10]\n\n", "What you did\nneverLost = [w for w, l in matches if w not l]\n\nis going to check whether the first item in that tuple is...
[ 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0074611917_list_list_comprehension_python.txt
Q: Retain original document element index of argument passed through sklearn's CountVectorizer() in order to access corresponding part of speech tag I have a data frame with sentences and the respective part of speech tag for each word (Below is an extract of the data I'm working with (data taken from SNLI corpus). F...
Retain original document element index of argument passed through sklearn's CountVectorizer() in order to access corresponding part of speech tag
I have a data frame with sentences and the respective part of speech tag for each word (Below is an extract of the data I'm working with (data taken from SNLI corpus). For each sentence in my collection I would like to extract unigrams and the corresponding pos-tag of that word. For instance if I've the following: vect...
[ "After reviewing the source code for the sklearn CountVectorizer class, particularly the fit function, I don't believe the class has any way of tracking the original document element indexes relative to the extracted unigram features: where the unigram features do not necessarily have the same tokens. Other than th...
[ 0 ]
[]
[]
[ "countvectorizer", "nlp", "python", "scikit_learn", "stanford_nlp" ]
stackoverflow_0074611192_countvectorizer_nlp_python_scikit_learn_stanford_nlp.txt
Q: Run function in tex-based RPG game writed in python How to write a function to the game where you can run from the fight and so it would return your position to the state before the battle, because with my current code it returns you to the beginning of the game. This is my code def run(): runnum = random.rand...
Run function in tex-based RPG game writed in python
How to write a function to the game where you can run from the fight and so it would return your position to the state before the battle, because with my current code it returns you to the beginning of the game. This is my code def run(): runnum = random.randitn(1, 10) if runnum <= 4: print("Success!") ...
[ "If you want to be able to come back to a previous state (before the fight), either store the previous state, or use the Command pattern which allows for easy \"undo\", or do something else that may require re-architecturing your game.\nIt would be simpler to help you if we had a Minimal Reproducible Example of you...
[ 0, 0 ]
[]
[]
[ "function", "python", "return", "text" ]
stackoverflow_0074604923_function_python_return_text.txt
Q: Copy dataframe n times, assign new IDs, keeping the original I have a dataframe that looks like this: df = pd.DataFrame({'id':[1,3,500, 53, 1, 500], 'code1':['a0', 'b0', 'b0', 'c0', 'b0', 'a0'], 'code2':['aa', 'bb', 'cc', 'bb', 'cc', 'bb'], 'date':['2022-10-01', '2022-09-01', '2022-10-01', '2022-11-01', '2022-09-0...
Copy dataframe n times, assign new IDs, keeping the original
I have a dataframe that looks like this: df = pd.DataFrame({'id':[1,3,500, 53, 1, 500], 'code1':['a0', 'b0', 'b0', 'c0', 'b0', 'a0'], 'code2':['aa', 'bb', 'cc', 'bb', 'cc', 'bb'], 'date':['2022-10-01', '2022-09-01', '2022-10-01', '2022-11-01', '2022-09-01', '2022-11-01']}) I want to expand (copy) this dataframe N times...
[ "You can use the key parameter of concat to increment a step based on the max id in the original DataFrame:\nN = 4\n\nstep = df['id'].max()\nout = pd.concat([df]*N, keys=range(N))\nout['id'] += out.index.get_level_values(0)*step\nout = out.droplevel(0)\n\nMore simple variant with numpy:\nimport numpy as np\n\nN = 4...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python", "repeat" ]
stackoverflow_0074614077_dataframe_pandas_python_repeat.txt
Q: Change x-tick intervals when using matplotlib.pyplot I have the following code. I am trying to plot a line plot. However, it is plotting too many x-values on the x-axis. I would like to plot fewer x-axis values (plot one value every few values) so that the x-axis scale is readable. I would be so grateful for a hel...
Change x-tick intervals when using matplotlib.pyplot
I have the following code. I am trying to plot a line plot. However, it is plotting too many x-values on the x-axis. I would like to plot fewer x-axis values (plot one value every few values) so that the x-axis scale is readable. I would be so grateful for a helping hand! plt.figure(figsize=(70,70)) ax = sns.lineplot(d...
[ "Here you can see the relevant documentation. Change the line\nplt.xticks(rotation = 30,weight='bold',fontsize=60)\n\nto\nplt.xticks(ticks = list(range(0,70_000,10_000)),rotation = 30,weight='bold',fontsize=60)\n\nand you will have ticks at only every 10 thousand steps. You can change the list to suit your needs.\n...
[ 1 ]
[]
[]
[ "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074614017_jupyter_notebook_pandas_python.txt
Q: How to call a class class vraagmachine: def __init__(self): self.answers=[] self.count=0 def askname(self): self.name=input('What is your name?: ') if self.name=='stop': for i in range(self.count): print(self.answers) def askage(self): self.age=input('How old are you?: ') ...
How to call a class
class vraagmachine: def __init__(self): self.answers=[] self.count=0 def askname(self): self.name=input('What is your name?: ') if self.name=='stop': for i in range(self.count): print(self.answers) def askage(self): self.age=input('How old are you?: ') self.answer=self.name...
[ "You can't \"execute everything in it\" in one go, since there are three different functions.\nYou'd do\nvm = vraagmachine() # instantiate a `vraagmachine`; calls __init__\nvm.askname()\nvm.askage()\n\nif that's the order you want to ask things in, or the other way around maybe.\n" ]
[ 0 ]
[]
[]
[ "call", "class", "python" ]
stackoverflow_0074614128_call_class_python.txt
Q: How to mock a class with nested properties and autospec? I'm wondering if it's possible to mock a class which contains properties by using patch and autospec? The goal in the example below is to mock (recursively) ClassB. Example: # file: class_c.py class ClassC: def get_default(self) -> list[int]: re...
How to mock a class with nested properties and autospec?
I'm wondering if it's possible to mock a class which contains properties by using patch and autospec? The goal in the example below is to mock (recursively) ClassB. Example: # file: class_c.py class ClassC: def get_default(self) -> list[int]: return [1, 2, 3] def delete(self, name: str): print...
[ "Once you patched the target class, anything you try to access under that class will be mocked with MagicMock (also recursively). Therefore, if you want to keep the specification of that class, then yes, you should use the autospec=true flag.\nBut because you are trying to mock a class within a class accessed by a ...
[ 4 ]
[]
[]
[ "mocking", "python", "unit_testing" ]
stackoverflow_0074611520_mocking_python_unit_testing.txt
Q: Why orientation parameter doesn't exists in Slider? Hi have this small code for practice using CustomTkinter, reading the official documentation for a vertical slider i need to write orientation = 'vertical' but when i run the code Py charm says "_tkinter.TclError: unknown option "-orientation", how is possible th...
Why orientation parameter doesn't exists in Slider?
Hi have this small code for practice using CustomTkinter, reading the official documentation for a vertical slider i need to write orientation = 'vertical' but when i run the code Py charm says "_tkinter.TclError: unknown option "-orientation", how is possible that orientation isn't a parameter? I can't understand plea...
[ "Comment out line 8.\nAdd this parameter orient=Tk.Vertical.\nslider = customtkinter.CTkSlider(master=win, from_=0, to=100,orient=Tk.Vertical, command=slider,fg_color='#555555',progress_color='#144870')\n\n" ]
[ 1 ]
[]
[]
[ "python", "slider", "tkinter" ]
stackoverflow_0074613942_python_slider_tkinter.txt
Q: how to show avaliable sizes of clothes on the form? Django I'm developing online clothing store on Django. Now I faced the issue: I have a form which helps user to add to his cart some clothes. I need to show which sizes of this clothes are avaliable. To do this, I need to refer to the database. But how to do it f...
how to show avaliable sizes of clothes on the form? Django
I'm developing online clothing store on Django. Now I faced the issue: I have a form which helps user to add to his cart some clothes. I need to show which sizes of this clothes are avaliable. To do this, I need to refer to the database. But how to do it from the form? models.py: from django.db import models from djang...
[ "How about dividing each clothes by size(with quantity)? Clothes with different size can be treated as different product.\nproduct\n\n\n\n\nID\nname\nimage\ndescription\nprice\n...\n\n\n\n\n1\njean\na.jpg\ngood jean\n12345\n...\n\n\n\n\nsize\n\n\n\n\nID\nproduct_id\nsize\nquantity\n...\n\n\n\n\n1\n1\nxxxl\n12345\n....
[ 0, 0 ]
[]
[]
[ "django", "django_4.1", "python" ]
stackoverflow_0074600909_django_django_4.1_python.txt
Q: Python Regular Expression: re.sub to replace matches I am trying to analyze an earnings call using python regular expression. I want to delete unnecessary lines which only contain the name and position of the person, who is speaking next. This is an excerpt of the text I want to analyze: "Questions and Answers\nOp...
Python Regular Expression: re.sub to replace matches
I am trying to analyze an earnings call using python regular expression. I want to delete unnecessary lines which only contain the name and position of the person, who is speaking next. This is an excerpt of the text I want to analyze: "Questions and Answers\nOperator [1]\n\n Shannon Siemsen Cross, Cross Research LL...
[ "Try to use re.sub to replace the match:\nimport re\n\ntext = \"\"\"\\\nQuestions and Answers\nOperator [1]\n\nShannon Siemsen Cross, Cross Research LLC - Co-Founder, Principal & Analyst [2]\nI hope everyone is well. Tim, you talked about seeing some improvement in the second half of April. So I was wondering if yo...
[ 1, 0 ]
[]
[]
[ "python", "python_re", "regex" ]
stackoverflow_0074613853_python_python_re_regex.txt
Q: create a list of lists with a checkerboard pattern I would like to change the values ​​of this list by alternating the 0 and 1 values ​​in a checkerboard pattern. table = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ...
create a list of lists with a checkerboard pattern
I would like to change the values ​​of this list by alternating the 0 and 1 values ​​in a checkerboard pattern. table = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 i tried: for i in range(le...
[ "for i in range(len(table)):\n for j in range(len(table[i])):\n if (i+j)%2 == 0:\n table[i][j] = 0\n\noutput:\n [[0, 1, 0, 1, 0],\n [1, 0, 1, 0, 1],\n [0, 1, 0, 1, 0],\n [1, 0, 1, 0, 1],\n [0, 1, 0, 1, 0]]\n\n" ]
[ 2 ]
[ "There doesn't appear to be any reliance on the original values in the list. Therefore it might be better to implement something that creates a list in the required format like this:\ndef checkboard(rows, columns):\n e = 0\n result = []\n for _ in range(rows):\n c = []\n for _ in range(column...
[ -1 ]
[ "python" ]
stackoverflow_0074613553_python.txt
Q: Edit an object with unique field: UNIQUE constraint failed: blog_post.title I am trying to update a record that has the title field as unique. when i edit any other field other than the title i get this error: UNIQUE constraint failed: blog_post.title, but when i edit the title, a new object is created. I have loo...
Edit an object with unique field: UNIQUE constraint failed: blog_post.title
I am trying to update a record that has the title field as unique. when i edit any other field other than the title i get this error: UNIQUE constraint failed: blog_post.title, but when i edit the title, a new object is created. I have looked up examples and work arounds and couldn't fine a suitable approach to resolvi...
[ "I think because you're creating a new instance instead of actually updating an existing record, after fetching your record via its id start changing the field values needed and then invoke the save method.\npost_edit.body=\"Example\"\npost_edit.save()\n\n" ]
[ 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "flask_wtforms", "python" ]
stackoverflow_0074613932_flask_flask_sqlalchemy_flask_wtforms_python.txt
Q: Edge Detection for high resolution pictures I am trying to locate three objects in my image and crop the sherd out. Any way that I can detect the edges better? This is the code I use to detect objects. def getEdgedImg(img): kernel = np.ones((3,3), np.uint8) eroded = cv2.erode(img, kernel) blur = cv2.me...
Edge Detection for high resolution pictures
I am trying to locate three objects in my image and crop the sherd out. Any way that I can detect the edges better? This is the code I use to detect objects. def getEdgedImg(img): kernel = np.ones((3,3), np.uint8) eroded = cv2.erode(img, kernel) blur = cv2.medianBlur(eroded, 3) med_val = np.median(erode...
[ "Had a shot at it, but as expected the weak background contrast is giving trouble, as does the directed lighting. Just checking the stone right now, but the script should give you the tools to find the two reference cards as well. If you want to show the intermediate images, see the comments in the script.\nDo you ...
[ 2 ]
[]
[]
[ "computer_vision", "opencv", "python" ]
stackoverflow_0074612527_computer_vision_opencv_python.txt
Q: retrieve xpath or other element identifier from a python program I am trying to do something i can't find any help on. I want to be able to locate the xpath or other 'address' information in of a particular element for later use by selenium. I have text for the element and can find it using the selenium By.LINK.TE...
retrieve xpath or other element identifier from a python program
I am trying to do something i can't find any help on. I want to be able to locate the xpath or other 'address' information in of a particular element for later use by selenium. I have text for the element and can find it using the selenium By.LINK.TEXT methodology. However, i am writing an application where speed is cr...
[ "\nThe Selenium WebElement object received by driver.find_element(ByLocator) is already a reference to the actual physical web element on the page. In other words, the WebElement object is an address of the actual web element you asking about.\nThere is no way to get a By locator of an already found WebElement\n\nS...
[ 0 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0074614066_python_selenium_xpath.txt
Q: How to reshape a pandas data frame which has duplicate columns to a required format? I have a list of elements extracted from a xml file, they are passed to a pandas dataframe and assigned columns as below. #dataframe created with a list of lists df = pd.DataFrame([ ['2201 W WILLOW'], ['2201 W WILLOW'], ['ENID']...
How to reshape a pandas data frame which has duplicate columns to a required format?
I have a list of elements extracted from a xml file, they are passed to a pandas dataframe and assigned columns as below. #dataframe created with a list of lists df = pd.DataFrame([ ['2201 W WILLOW'], ['2201 W WILLOW'], ['ENID'], ['ENID, OK 73073'], ['73073'], ['2201 W WILLOW'], ['2201 W WILLOW'], ['ENID'], ['EN...
[ "You can use a MultiIndex:\n(df.set_axis(pd.MultiIndex\n .from_arrays([df.columns,\n df.groupby(df.columns, axis=1)\n .cumcount()]),\n axis=1)\n .loc[0].unstack().add_prefix('value_')\n)\n\nOutput:\n value_0 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074614298_dataframe_pandas_python.txt
Q: Windows - Use default python rather than Anaconda installation my problem is before I installed Anaconda, my python with python and py commands shows the same versions. After I installed Anaconda, my python version is using Anaconda installation. How to prevent this, because I don't want to use Anaconda python ver...
Windows - Use default python rather than Anaconda installation
my problem is before I installed Anaconda, my python with python and py commands shows the same versions. After I installed Anaconda, my python version is using Anaconda installation. How to prevent this, because I don't want to use Anaconda python version on my Windows. I already put my python PATH on the top When I ...
[ "You need to change the default opener for the .py files on your computer.\ntry to right-click on the .py file, select \"open with\" and look for python.\nYou can always use cmd and run the following:\npython <path_to_file>\n\nor\npython3 <path_to_file>\n\nIt depended on your python version\n(as long as you set you...
[ 0 ]
[]
[]
[ "anaconda", "python", "windows" ]
stackoverflow_0074614179_anaconda_python_windows.txt
Q: My wordcloud mask is producing a series of points outlining where the mask should be but the words are fitting to the shape of the entire image As described above my wordcloud is not behaving in a way I have sen before and I have no idea what is causing the issue as I have made them before and never experienced th...
My wordcloud mask is producing a series of points outlining where the mask should be but the words are fitting to the shape of the entire image
As described above my wordcloud is not behaving in a way I have sen before and I have no idea what is causing the issue as I have made them before and never experienced this problem. # import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from PIL import Image from wordcloud import Wor...
[ "As commented by Paul Brodersen the image used for the mask has to be black and white, with black corresponding to the area to be filled.\nThanks Paul\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python", "word_cloud" ]
stackoverflow_0074612436_matplotlib_python_word_cloud.txt
Q: UnboundLocalError: local variable referenced before assignment error I tried all the solutions I could find nothing helped A survey for a school project and expected to add 100 points to the persons score Do you think you could help code: #QUESTION q1 = "TRUE OR FALSE: The lightest atom is hydrogen" q2 = "TRUE OR...
UnboundLocalError: local variable referenced before assignment error
I tried all the solutions I could find nothing helped A survey for a school project and expected to add 100 points to the persons score Do you think you could help code: #QUESTION q1 = "TRUE OR FALSE: The lightest atom is hydrogen" q2 = "TRUE OR FALSE: Osmium is one of the densest atom if not the most" q3 = "TRUE OR F...
[ "Cause of Error\n\nThe error is your global statements should be inside function software since the global keyword allows us to modify variables outside of the current scope. You need it in the function software\n\nImprovements\n\nCoding is largely about using the right data structures. Using a variable for each q...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074609169_python.txt
Q: Create bar charts by grouped columns I have a dataframe like this: data = [[2008, 'A', 12.2], [2008, 'A', 11.3], [2009, 'A', 4.2], [2010, 'A', 3.4], [2011, 'A', 14.2], [2008, 'B', 4.1], [2008, 'B', 17.2], [2009, 'B', 12.2], [2008, 'C', 12.2], [2011, 'C', 12.2]] df = pd.DataFrame(data, columns=['year', '...
Create bar charts by grouped columns
I have a dataframe like this: data = [[2008, 'A', 12.2], [2008, 'A', 11.3], [2009, 'A', 4.2], [2010, 'A', 3.4], [2011, 'A', 14.2], [2008, 'B', 4.1], [2008, 'B', 17.2], [2009, 'B', 12.2], [2008, 'C', 12.2], [2011, 'C', 12.2]] df = pd.DataFrame(data, columns=['year', 'type', 'income']) I'd like to group the ...
[]
[]
[ "Use:\ndf.groupby(['type', 'year']).sum().groupby(level='type').plot.bar()\n\nOutput:\n\n\n\nAn interesting alternative:\n(df.pivot_table(index='year', columns='type', values='income', aggfunc='sum')\n .plot.bar(subplots=True, figsize=(4,10))\n)\n\nOutput:\n\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0074614367_pandas_python.txt
Q: how add a point in an specific position of a string in a column in python Hy! I have a dataframe with two columns latitude and longitude with a wrong format that i want to correct. The structure of de strings in columns is the next Lat Long -314193332 -6419125129999990 -313147283 -641708031 I need to append a ...
how add a point in an specific position of a string in a column in python
Hy! I have a dataframe with two columns latitude and longitude with a wrong format that i want to correct. The structure of de strings in columns is the next Lat Long -314193332 -6419125129999990 -313147283 -641708031 I need to append a point in the third position to have this structure: Lat Long ...
[ "You can use arithmetic with a conversion to log10 to get the number of digits:\nN = 2 # number of digits to keep before decimal part\nout = df.div(10**np.floor(np.log10(df.abs())+1).sub(N))\n\nOutput:\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n\nIntermediate (number of digits):\nnp...
[ 4, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074613924_pandas_python.txt
Q: Delete comments with python function Anybody can advise what could be wrong with my code? I am trying to make a method that removes the single line comments from the content. Also, the method should return the single line comments that start with '#'. import os def deleteComments(file): try: my_file =...
Delete comments with python function
Anybody can advise what could be wrong with my code? I am trying to make a method that removes the single line comments from the content. Also, the method should return the single line comments that start with '#'. import os def deleteComments(file): try: my_file = open(file, 'r') data = my_file.r...
[ "This should make it work.\nimport os\n\ndef deleteComments(file):\n try:\n my_file = open(file, 'r')\n data = my_file.read()\n clean = \"\"\n comments_count = 0\n for i in data.split('\\n'):\n if i[0] == \"#\":\n clean += i\n clean += '...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074614357_python.txt
Q: Strings in nested lists I have a list looking like this: record1 = [["2020/02/19", 7.0], ["2020/02/20", 7.3], ["2020/02/21", 6.1]] but I want to change the dates from yyyy/mm/dd to dd/mm/yyyy. record1= [["19/02/2020", 7.0], ["20/02/2020", 7,3], ["21/02/2020", 6.1] How can I do this? I cannot just use ::-1 becaus...
Strings in nested lists
I have a list looking like this: record1 = [["2020/02/19", 7.0], ["2020/02/20", 7.3], ["2020/02/21", 6.1]] but I want to change the dates from yyyy/mm/dd to dd/mm/yyyy. record1= [["19/02/2020", 7.0], ["20/02/2020", 7,3], ["21/02/2020", 6.1] How can I do this? I cannot just use ::-1 because then everything gets mixed ...
[ "The proper way of doing it using datetime module:\nrecord1 = [[datetime.strptime(d, '%Y/%m/%d').strftime('%d/%m/%Y'), v] for d, v in record1]\n\nThis converts it to datetime object, then formats it the way you intended\n>>> record1\n[['19/02/2020', 7.0], ['20/02/2020', 7.3], ['21/02/2020', 6.1]]\n\nThis would be a...
[ 3 ]
[]
[]
[ "date", "nested_lists", "python" ]
stackoverflow_0074614410_date_nested_lists_python.txt
Q: python single file multiple lock issue I have a scenario where in there are 2 processes (Log_writer1.py and Log_writer2.py) running (as cron jobs) which are eventually writing to the same log file(test_log_file.txt) as part of the log_event function. Because of multiple locks, there are inconsistencies and all dat...
python single file multiple lock issue
I have a scenario where in there are 2 processes (Log_writer1.py and Log_writer2.py) running (as cron jobs) which are eventually writing to the same log file(test_log_file.txt) as part of the log_event function. Because of multiple locks, there are inconsistencies and all data are not being stored in the log file. Is t...
[ "No, not an easy way. Even if you could share a lock, you'd then run into lock contention issues\nEither:\n\n(easiest, just requires an extra step later) have each process write to a separate, uniquely named log file and concatenate them afterwards if you need to.\n(harder, requires an extra process and communicati...
[ 1 ]
[]
[]
[ "cron_task", "locks", "multithreading", "python" ]
stackoverflow_0074614387_cron_task_locks_multithreading_python.txt
Q: Why there is a python version besides the package version? When I check the version of a package, I get a python version in parentheses. What does it mean? This python 3.7.3 does not match with the PyCharm interpreter I am using (python 3.8). Is that the reason? Should I worry the version between parentheses is n...
Why there is a python version besides the package version?
When I check the version of a package, I get a python version in parentheses. What does it mean? This python 3.7.3 does not match with the PyCharm interpreter I am using (python 3.8). Is that the reason? Should I worry the version between parentheses is not the same as my python project interpreter?
[ "It is possible that you have many python versions installed on your computer.\nYou probably need to pip install again the same package for the python version you are using with your Pycharm if you want them to work correctly.\nif you are not sure how to do that with CMD commands,\nyou can access your Pycharm, look...
[ 1 ]
[]
[]
[ "pycharm", "python", "versioning" ]
stackoverflow_0074614311_pycharm_python_versioning.txt
Q: How do i solve the "AttributeError: 'NoneType' object has no attribute 'split' " on specifying the k-clustering value? I'm trying to find the best values of k clustering, but it is showing error k_range = range(1,10) sse = [] max_iter = 300 init = 'k-means++' n_init = 10 for k in k_range: km = KMeans(n_cluste...
How do i solve the "AttributeError: 'NoneType' object has no attribute 'split' " on specifying the k-clustering value?
I'm trying to find the best values of k clustering, but it is showing error k_range = range(1,10) sse = [] max_iter = 300 init = 'k-means++' n_init = 10 for k in k_range: km = KMeans(n_clusters=k, max_iter = max_iter, init = init, n_init = n_init) km.fit(df[['Age','Income($)']]) sse.append(km.inertia_)
[ "seems like an issue caused by a numpy.\nimporting a specific version of numpy ( downgrading it to 1.21.4) should fix the problem\nimport numpy \nnumpy.__version__ \n'1.21.4' \n\nmake sure, you not importing numpy as np again afterwards before you assign your clastering model\n", "Instead of downgrading numpy, y...
[ 0, 0 ]
[ "Setting the minimum value in your range to a value greater than 1 will fix this problem\nEX: range(2,10)\n" ]
[ -1 ]
[ "k_means", "python" ]
stackoverflow_0072395721_k_means_python.txt
Q: Access shadow root content with selenium I'm trying to accept the cookie pop up on http://www.immobilienscout24.de. I'm using selenium 4.61, webdriver-manger with chrome, python 3.11 and Fedora 37, but I'm always getting an error. I'm using the following code driver = webdriver.Chrome(ChromeDriverManager().install...
Access shadow root content with selenium
I'm trying to accept the cookie pop up on http://www.immobilienscout24.de. I'm using selenium 4.61, webdriver-manger with chrome, python 3.11 and Fedora 37, but I'm always getting an error. I'm using the following code driver = webdriver.Chrome(ChromeDriverManager().install()) def accept_cookies(): shadow_root = W...
[ "The following code works for me:\nurl = \"http://www.immobilienscout24.de/\"\ndriver.get(url)\n\ntime.sleep(10)\n\nelement = driver.execute_script(\"\"\"return document.querySelector('#usercentrics-root').shadowRoot.querySelector(\"button[data-testid='uc-accept-all-button']\")\"\"\")\nelement.click()\n\n" ]
[ 0 ]
[]
[]
[ "automation", "css_selectors", "python", "selenium", "shadow_dom" ]
stackoverflow_0074614456_automation_css_selectors_python_selenium_shadow_dom.txt
Q: Python3 surprising behavior of identifier being a non-ASCII Unicode character Following code runs without an assertion error: K = 'K' = '' = '' = '' = '' = '' ᴷ = 'ᴷ' assert K == == == == == ᴷ print(f'{K=}, {=}, {=}, {=}, {=}, {=}') and prints K='ᴷ', ='ᴷ', ='', ='ᴷ', ='ᴷ', ='ᴷ' I am aware of https://pep...
Python3 surprising behavior of identifier being a non-ASCII Unicode character
Following code runs without an assertion error: K = 'K' = '' = '' = '' = '' = '' ᴷ = 'ᴷ' assert K == == == == == ᴷ print(f'{K=}, {=}, {=}, {=}, {=}, {=}') and prints K='ᴷ', ='ᴷ', ='', ='ᴷ', ='ᴷ', ='ᴷ' I am aware of https://peps.python.org/pep-3131/ and have read the Python documentation about identifiers htt...
[ "Python identifiers with non-ASCII characters are subject to NFKC normalisation(1), you can see the effect in the following code:\nimport unicodedata\nfor char in ['K', '', '', '', '', '', 'ᴷ']:\n normalised_char = unicodedata.normalize('NFKC', char)\n print(char, normalised_char, ord(normalised_char))\n\nThe...
[ 8 ]
[]
[]
[ "python", "python_3.x", "unicode" ]
stackoverflow_0074614341_python_python_3.x_unicode.txt
Q: How to identify in which region new point will lie using Sklearn Python? I have a sample code for the Sklearn taken from the website. I am trying to learn how to classify points using Sklearn(Scikit-Learn). Here is the code: import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedCol...
How to identify in which region new point will lie using Sklearn Python?
I have a sample code for the Sklearn taken from the website. I am trying to learn how to classify points using Sklearn(Scikit-Learn). Here is the code: import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.model_selection import train_test_split from sklearn.prepro...
[ "So, you have X_train and X_test. These are both lists containing tuples. The values in the tuples (a, b) have some range, like 0 -> 1. In your graphs, these are the x and y coordinates of your dots.\nYou also have y_train and y_test. These are the known classifications of all the tuples in X_train and X_test. Thes...
[ 1, 1, 1 ]
[]
[]
[ "python", "python_3.x", "scikit_learn" ]
stackoverflow_0074577545_python_python_3.x_scikit_learn.txt
Q: Explanation for Linked List in Python I have started learning linked list in python and after going through a lot material for leaning linked list. I found out that linked list is made of nodes(each node has two values namely the data and a address) and the first node is called the HEAD node and last node points t...
Explanation for Linked List in Python
I have started learning linked list in python and after going through a lot material for leaning linked list. I found out that linked list is made of nodes(each node has two values namely the data and a address) and the first node is called the HEAD node and last node points towards the None value showing it to be the ...
[ "\nwhen we assign an object to a variable(head) we are actually assigning the address of that object to the variable. I would like to know whether my assumption is correct or wrong and if its wrong why is it wrong.\n\nThis would be true for other -- pointer-based -- languages, like C, but Python does not actually g...
[ 1 ]
[ "So linked list has this concept of Start pointer, commonly referred to as Head.\nThe head points to the first node of the linkedlist.\nSo when you say,\nL = SingleLinkedList()\n\nYou essentially create a linked list whose head pointer is still set to None.\nIn the next step you create a node :\nn = Node(10)\n\nAnd...
[ -1 ]
[ "data_structures", "linked_list", "python", "python_3.x" ]
stackoverflow_0074609360_data_structures_linked_list_python_python_3.x.txt
Q: Python 3 SSL cannot grab certificate I'm trying to have a simple function collect certificates from servers. Using Python 3.10.8 and my code looks something this: import ssl def certgrab(dom): address = (dom, 443) try: f = ssl.get_server_certificate(address) except Exception as clanger: ...
Python 3 SSL cannot grab certificate
I'm trying to have a simple function collect certificates from servers. Using Python 3.10.8 and my code looks something this: import ssl def certgrab(dom): address = (dom, 443) try: f = ssl.get_server_certificate(address) except Exception as clanger: return {'clanger': clanger} print(f)...
[ "\nConnectionRefusedError(10061, 'No connection could be made because the target machine actively refused it'\n\nThis has nothing to do with certificates, not even with TLS. This is a connection error at the TCP level, i.e. even before any TLS and certificates are in effect.\n\nBut most websites return the followin...
[ 0 ]
[]
[]
[ "certificate", "connection_refused", "python", "ssl" ]
stackoverflow_0074613540_certificate_connection_refused_python_ssl.txt
Q: Kivy settings panel removes text property value from button widgets I have come across an issue with the Kivy settings panel, when I open and close the panel, the text properties of my button widgets are cleared, even though they still display correctly. The following code demonstrates the issue: from kivy.app imp...
Kivy settings panel removes text property value from button widgets
I have come across an issue with the Kivy settings panel, when I open and close the panel, the text properties of my button widgets are cleared, even though they still display correctly. The following code demonstrates the issue: from kivy.app import App from kivy.uix.button import Button class TestApp(App): def ...
[ "Missing import of class SettingWithSpinner from kivy.uix.settings, related to python settings freezes GUI.\nWithout the import, no errors where reported at runtime and the bug is present, including the import seems to resolve the issue.\n" ]
[ 0 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0074612754_kivy_python.txt
Q: How to flatten string column in pyspark? a b [{'npi': [1013006469, 1003263552], 'tin': {'type': 'npi', 'value': '1013006469'}}, {'npi': [1487607883], 'tin': {'ty...
How to flatten string column in pyspark?
a b [{'npi': [1013006469, 1003263552], 'tin': {'type': 'npi', 'value': '1013006469'}}, {'npi': [1487607883], 'tin': {'type': 'npi', 'value': '1487607883'}}] 0 [{'n...
[ "from_json function for tin in pyspark will get it done.\nExample\nfrom pyspark.sql.functions import from_json, col\nfrom pyspark.sql.types import StructType, StructField, StringType\n\nschema = StructType(\n [\n StructField('col1', StringType(), True),\n StructField('col2', StringType(), True)\n ...
[ 0 ]
[]
[]
[ "apache_spark_sql", "flatten", "pyspark", "python" ]
stackoverflow_0074611190_apache_spark_sql_flatten_pyspark_python.txt
Q: Invalid literal for int() when trying to load pandas I am using Spyder 5.4.0 with Miniconda3. I have created a new Python environment using conda create -n env_full anaconda, then successfully activated in Spyder (using packages like numpy or matplotlib), but when I try to import pandas, I get: File "C:\ProgramDa...
Invalid literal for int() when trying to load pandas
I am using Spyder 5.4.0 with Miniconda3. I have created a new Python environment using conda create -n env_full anaconda, then successfully activated in Spyder (using packages like numpy or matplotlib), but when I try to import pandas, I get: File "C:\ProgramData\Miniconda3\envs\env_full\lib\site-packages\numexpr\util...
[ "Well the error states that os.environ['OMP_NUM_THREADS'] evaluates to '5,3,2' which is a string of multiple numbers. This cannot be converted into an integer.\nCheck out this documentation. So your virtual environment sets different thread numbers for different 'nesting depths'. I think you can set it to a single ...
[ 0 ]
[]
[]
[ "multithreading", "pandas", "python", "spyder" ]
stackoverflow_0074614058_multithreading_pandas_python_spyder.txt
Q: KMeans Attribute Error: 'NoneType' object has no attribute 'split' The KMeans code was working before but now it's not. The change I made was "pip install scikit-image" which I think changed numpy 1.18.5 to numpy 1.22.3 . But then I changed numpy back to 1.18.5 by doing -m pip install numpy==1.18.5 --user . And th...
KMeans Attribute Error: 'NoneType' object has no attribute 'split'
The KMeans code was working before but now it's not. The change I made was "pip install scikit-image" which I think changed numpy 1.18.5 to numpy 1.22.3 . But then I changed numpy back to 1.18.5 by doing -m pip install numpy==1.18.5 --user . And this didn't fix the issue. Any ideas what else it could be? Also, I don't ...
[ "seems like fixed an issue by importing a specific version of numpy\nimport numpy \nnumpy.__version__ \n'1.21.4' \n\nmake sure, you not importing\nimport numpy as np \n\nafterwards\n", "upgrading this:\npip install -U threadpoolctl\nsolved the prb for me.\n" ]
[ 0, 0 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0072117354_error_handling_python.txt
Q: Django - How to call a function with arguments inside a template I have the following function-based view: def get_emails(request, HOST, USERNAME, PASSWORD): context = { 'FU_HOST': settings.FU_HOST, 'FU_USERNAME': settings.FU_USERNAME, 'FU_PASSWORD': settings.FU_PASSWORD, 'FV_HO...
Django - How to call a function with arguments inside a template
I have the following function-based view: def get_emails(request, HOST, USERNAME, PASSWORD): context = { 'FU_HOST': settings.FU_HOST, 'FU_USERNAME': settings.FU_USERNAME, 'FU_PASSWORD': settings.FU_PASSWORD, 'FV_HOST': settings.FV_HOST, 'FV_USERNAME': settings.FV_USERNAME, ...
[ "Something like this is not achieved by placing that function on your frontend template, what you need to be doing is to redirect the user to a view that contains that function and by extracting these values from the users request, because as you can see you've got methods that are hitting your Database, which isn'...
[ 1, 0, 0 ]
[]
[]
[ "django", "function", "python", "view" ]
stackoverflow_0074613987_django_function_python_view.txt
Q: Spotify API invalid redirect URI I am running python and flask, when it starts to run I encounter this error message image of error message I have looked at other forums of people encoutering the same error to no avail #here is the code ''' from flask import Flask, request, url_for, session, redirect import spoti...
Spotify API invalid redirect URI
I am running python and flask, when it starts to run I encounter this error message image of error message I have looked at other forums of people encoutering the same error to no avail #here is the code ''' from flask import Flask, request, url_for, session, redirect import spotipy from spotipy.oauth2 import SpotifyO...
[ "Looks like you have a typo in the Redirect URI, in the one being sent to Spotify it is\n\nhttp://127.0.0.1:5000/redirect\n\nNote the spelling of redirect, from the Screenshot from the Spotify Dashboard this is \"redierect\" and also the lack of a forward slash on the one being passed to Spotify as this has to matc...
[ 0 ]
[]
[]
[ "python", "spotify" ]
stackoverflow_0074598589_python_spotify.txt
Q: In Python, how do I draw/ save a monochrome 2 bit BMP with Wand I have a need to create a 2 bit monochrome Windows BMP format image, and need to draw lines in a pattern. Since I have just started using python, I followed a tutorial and installed the Wand module. Drawing is fine, I get the content I need. Problem i...
In Python, how do I draw/ save a monochrome 2 bit BMP with Wand
I have a need to create a 2 bit monochrome Windows BMP format image, and need to draw lines in a pattern. Since I have just started using python, I followed a tutorial and installed the Wand module. Drawing is fine, I get the content I need. Problem is saving the image. No matter what I do, the resulting image is alway...
[ "Try using Image.quantize() to remove all the unique gray colors before setting the depth/colorspace properties.\n # ...\n image.quantize(2, colorspace_type='gray', dither=True)\n image.depth = 2\n image.colorspace = 'gray'\n image.type = 'bilevel' # or grayscale would also work.\n image.save(fil...
[ 2, 0 ]
[]
[]
[ "python", "wand" ]
stackoverflow_0069254456_python_wand.txt
Q: How to convert date format from yyyy-mm-dd to yymmdd base on python Robot Framework How to convert date format from yyyy-mm-dd to date yymmdd base on python Robot Framework I tried below Keyword in RobotFramework ${StartDate}= Convert Date 2022-09-29 result_format=**%yy%MM%dd** But I am getting 20220929 y...
How to convert date format from yyyy-mm-dd to yymmdd base on python Robot Framework
How to convert date format from yyyy-mm-dd to date yymmdd base on python Robot Framework I tried below Keyword in RobotFramework ${StartDate}= Convert Date 2022-09-29 result_format=**%yy%MM%dd** But I am getting 20220929 yyyymmdd Expected Output from above example ==> 220929 yymmdd
[ "You can try it as below:\n${StartDate}= Convert Date 2022-09-29 result_format=%y%m%d\n\nThis will give your expected output 220929 in yymmdd format\n" ]
[ 0 ]
[]
[]
[ "date", "date_conversion", "python", "robotframework" ]
stackoverflow_0073897604_date_date_conversion_python_robotframework.txt
Q: Searching for intersections in two tuples of tuples in python Having the following problem. I'm reading the data from stdin and save it in list that I convert to tuple the following way: x = int(input()) f = [] for i in range(x): a, b = map(int, input().split()) f.append([a,b]) def to_tuple(lst): ret...
Searching for intersections in two tuples of tuples in python
Having the following problem. I'm reading the data from stdin and save it in list that I convert to tuple the following way: x = int(input()) f = [] for i in range(x): a, b = map(int, input().split()) f.append([a,b]) def to_tuple(lst): return tuple(to_tuple(i) if isinstance(i, list) else i for i in lst) ...
[ "I am sure this can be solve by different ways. but I believe this is the easiest.\nout = set() # holds the output\nfor ff in f: # loop through f tuple\n ff = set(ff) # convert to set\n for ss1,ss2 in s: # loop through s tuple\n # you can select which tuple to do the intersection on. \n # here I ...
[ 0, 0, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0074584078_python_tuples.txt
Q: Issue with Netmiko when using Nornir Iv recently been using Nornir with Netmiko to get some output from my devices. When I run the following code: from nornir import InitNornir from nornir.core.filter import F from nornir_netmiko.tasks import netmiko_send_command, netmiko_send_config from nornir_ut...
Issue with Netmiko when using Nornir
Iv recently been using Nornir with Netmiko to get some output from my devices. When I run the following code: from nornir import InitNornir from nornir.core.filter import F from nornir_netmiko.tasks import netmiko_send_command, netmiko_send_config from nornir_utils.plugins.functions import print_result ...
[ "You set the platform equal to Cisco which is not mapped by the netmiko_plugin to any supported device_type. You should read the docs on netmiko_plugin. The platform should be equivalent to cisco_ios or cisco_ios_telnet.\n", "inventory['options']['hosts_query] = replace(replace(replace(replace(platform,'cisco-io...
[ 2, 0 ]
[]
[]
[ "error_handling", "netmiko", "python", "python_3.x" ]
stackoverflow_0067458383_error_handling_netmiko_python_python_3.x.txt
Q: How to Split Image Into Multiple Pieces in Python I'm trying to split a photo into multiple pieces using PIL. def crop(Path,input,height,width,i,k,x,y,page): im = Image.open(input) imgwidth = im.size[0] imgheight = im.size[1] for i in range(0,imgheight-height/2,height-2): print i fo...
How to Split Image Into Multiple Pieces in Python
I'm trying to split a photo into multiple pieces using PIL. def crop(Path,input,height,width,i,k,x,y,page): im = Image.open(input) imgwidth = im.size[0] imgheight = im.size[1] for i in range(0,imgheight-height/2,height-2): print i for j in range(0,imgwidth-width/2,width-2): p...
[ "Splitting image to tiles of MxN pixels (assuming im is numpy.ndarray):\ntiles = [im[x:x+M,y:y+N] for x in range(0,im.shape[0],M) for y in range(0,im.shape[1],N)]\n\nIn the case you want to split the image to four pieces:\nM = im.shape[0]//2\nN = im.shape[1]//2\n\ntiles[0] holds the upper left tile\n", "Edit: I b...
[ 44, 41, 39, 34, 20, 4, 3, 3, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "import cv2\n\ndef crop_image(image_path, output_path):\n im = cv2.imread(os.listdir()[2])\n imgheight=im.shape[0]\n imgwidth=im.shape[1]\n\n y1 = 0\n M = 2000\n N = 2000\n for y in range(0,imgheight,M):\n for x in range(0, imgwidth, N):\n y1 = y + M\n x1 = x + N\n...
[ -1 ]
[ "crop", "image", "python", "python_imaging_library", "split" ]
stackoverflow_0005953373_crop_image_python_python_imaging_library_split.txt
Q: AttributeError: 'Pipeline' object has no attribute 'fit_resample' Based on the documentation given on the following link pipeline and imbalanced i have tried to implement code on some dataset, here is code : import numpy as np import pandas as pd from collections import Counter from sklearn.preprocessing import...
AttributeError: 'Pipeline' object has no attribute 'fit_resample'
Based on the documentation given on the following link pipeline and imbalanced i have tried to implement code on some dataset, here is code : import numpy as np import pandas as pd from collections import Counter from sklearn.preprocessing import LabelEncoder,OneHotEncoder from imblearn.over_sampling import SMOTE fr...
[ "The tutorial employs imblearn.pipeline.Pipeline, while your code uses sklearn.pipeline.Pipeline (check import expressions). These appear to be different kinds of pipelines.\n" ]
[ 1 ]
[]
[]
[ "imblearn", "python" ]
stackoverflow_0074614451_imblearn_python.txt
Q: convert nanosecond precision datetime to snowflake TIMESTAMP_NTZ format I have a string datetime "2017-01-01T20:19:47.922596536+09". I would like to convert this into snowflake's DATETIME_NTZ date type (which can be found here). Simply put, DATETIME_NTZ is defined as TIMESTAMP_NTZ TIMESTAMP_NTZ internally stores ...
convert nanosecond precision datetime to snowflake TIMESTAMP_NTZ format
I have a string datetime "2017-01-01T20:19:47.922596536+09". I would like to convert this into snowflake's DATETIME_NTZ date type (which can be found here). Simply put, DATETIME_NTZ is defined as TIMESTAMP_NTZ TIMESTAMP_NTZ internally stores “wallclock” time with a specified precision. All operations are performed wit...
[ "You can do this on the Snowflake side if you want by sending the string format as-is and converting to a timestamp_ntz. This single line shows two ways, one that simply strips off the time zone information, and one that converts the time zone to UTC before stripping off the time zone.\nselect try_to_timestamp_ntz(...
[ 0 ]
[]
[]
[ "datetime", "numpy", "pandas", "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074611360_datetime_numpy_pandas_python_snowflake_cloud_data_platform.txt
Q: How to combine X_test, y test, and y predictions after text analytics prediction? After using logitics Reg on text analytics, I was trying to combine the X_test, y_arr_test (label), and y_predictions to ONE dataframe, but don't know how to do it. Need help. ''' from sklearn.feature_extraction.text import CountVect...
How to combine X_test, y test, and y predictions after text analytics prediction?
After using logitics Reg on text analytics, I was trying to combine the X_test, y_arr_test (label), and y_predictions to ONE dataframe, but don't know how to do it. Need help. ''' from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() vectorizer.fit(X_arr_train) X_train = vectorizer...
[ "for the existing df you can just add the prediction results like:\nx_train['preds'] = y_predictions\nsame goes for labels like\nx_train['labels'] = y_train\nor all in one:\nnew_df = x_train.copy()\n\nnew_df['preds'] = y_predictions\nnew_df['labels'] = y_train\n\n\nhave you tried this?\n" ]
[ 0 ]
[]
[]
[ "concatenation", "nlp", "pandas", "python", "scikit_learn" ]
stackoverflow_0065360549_concatenation_nlp_pandas_python_scikit_learn.txt
Q: How do I apply my Random Forest classifier to an unlabelled dataset? Using sklearn, I have just finished training, tuning hyperparameters and testing a Random Forest Multiclass Classifier using RandomizedSearchCV. I have obtained the best parameters, best score and so on. This was all done with a labelled dataset....
How do I apply my Random Forest classifier to an unlabelled dataset?
Using sklearn, I have just finished training, tuning hyperparameters and testing a Random Forest Multiclass Classifier using RandomizedSearchCV. I have obtained the best parameters, best score and so on. This was all done with a labelled dataset. Now I want to apply this classifier onto an unlabelled dataset (meaning t...
[ "Edit: This answer is based on the following version of the question: https://stackoverflow.com/revisions/74613826/2\nYou can use the forest_search.predict(X_test) method, which will use the best parameters found in search.\n", "Or you can try to go to unsupervised learning direction and try one of the clustering...
[ 1, 0 ]
[]
[]
[ "classification", "python", "random_forest", "scikit_learn" ]
stackoverflow_0074613826_classification_python_random_forest_scikit_learn.txt
Q: Cannot locate python module: KV Language, PyInstaller I have an application developed in Kivy which works fine when I execute using a python interpreter. The problem happens when I try to execute after creating an executable using pyinstaller. The .kv file is unable to locate the python modules that it needs. I be...
Cannot locate python module: KV Language, PyInstaller
I have an application developed in Kivy which works fine when I execute using a python interpreter. The problem happens when I try to execute after creating an executable using pyinstaller. The .kv file is unable to locate the python modules that it needs. I believe this has something to do with root path configuration...
[ "I had the same problem, for me the solution was to fully unintall all your versions of python, NOT your code editors, but the Python files.\nUsually located in:\nC:\\Users\\YOUR PC NAME\\AppData\\Local\\Programs\\Python\\Python311\nAfter that go to the official python website:\nhttps://www.python.org/downloads/\n...
[ 0 ]
[]
[]
[ "kivy_language", "pyinstaller", "python" ]
stackoverflow_0074614620_kivy_language_pyinstaller_python.txt
Q: Failing to pre-sign s3 url in Bahrain AWS region ONLY I've had some Python code that pre-signs AWS S3 URLs that have been working for years. We just added a new bucket in the Bahrain AWS data center. This location was disabled and required explicitly enabling that data center. That all seemed fine. However, the re...
Failing to pre-sign s3 url in Bahrain AWS region ONLY
I've had some Python code that pre-signs AWS S3 URLs that have been working for years. We just added a new bucket in the Bahrain AWS data center. This location was disabled and required explicitly enabling that data center. That all seemed fine. However, the resulting URL always gives me an IllegalLocationConstraintExc...
[ "Try specifying endpoint_url in S3 client:\nboto3.client('s3', endpoint_url='https://s3.me-south-1.amazonaws.com', region_name='me-south-1')\n\nIf you get the following error\nThe authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.\n\nspecify signature_version too:\nfrom botocor...
[ 5, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "python" ]
stackoverflow_0061602839_amazon_s3_amazon_web_services_python.txt
Q: Could not find a version that satisfies the requirement discord-componentsERROR: No matching distribution found for discord-components I got this error while Developing a Ticket Tool discord Bot Plz help me to solve this error ` import discord import datetime from discord.ext import commands from discord_componen...
Could not find a version that satisfies the requirement discord-componentsERROR: No matching distribution found for discord-components
I got this error while Developing a Ticket Tool discord Bot Plz help me to solve this error ` import discord import datetime from discord.ext import commands from discord_components import Button, Select, SelectOption, ComponentsBot, interaction from discord_components.component import ButtonStyle `
[ "Discord.py 2.0 has built in buttons with discord.ui.buttons use it instead.\nRead the documentation here. There are also plenty of tutorials on it.\n" ]
[ 0 ]
[]
[]
[ "components", "discord", "discord.py", "discord_buttons", "python" ]
stackoverflow_0074614321_components_discord_discord.py_discord_buttons_python.txt
Q: No module named 'scipy.signal' Whenever I am trying to import scipy.signal it gives the following error No module named 'scipy.signal' I am currently on python 3.9 and 1.9.3 for scipy.I have tried uninstalling and reinstalling scipy A: Well I solved the problem by completely uninstalling python and reinstalling...
No module named 'scipy.signal'
Whenever I am trying to import scipy.signal it gives the following error No module named 'scipy.signal' I am currently on python 3.9 and 1.9.3 for scipy.I have tried uninstalling and reinstalling scipy
[ "Well I solved the problem by completely uninstalling python and reinstalling it\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "scipy" ]
stackoverflow_0074535849_python_python_3.x_scipy.txt
Q: how to write xml back to a file I have about 100,000 price-table records in XML and I need to remove entries where the price amount is 0.00. The data is structured as follows: <data> <price-table product-id="100109a"> <amount quantity="1">10.00</amount> </price-table> <price-table product-id="2...
how to write xml back to a file
I have about 100,000 price-table records in XML and I need to remove entries where the price amount is 0.00. The data is structured as follows: <data> <price-table product-id="100109a"> <amount quantity="1">10.00</amount> </price-table> <price-table product-id="201208c"> <amount quantity="1"...
[ "tostring() returns a bytes object unless encoding=\"unicode\" is used.\nThe code can be simplified quite a bit. There is no need to use open(), fromstring() or tostring(). Just parse the XML file into an ElementTree object, do your changes, and save using ElementTree.write().\nfrom xml.etree import ElementTree as ...
[ 2, 1 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0074609129_elementtree_python_xml.txt
Q: What is the difference between a "pip wheel -e" and "pip install -e"? Building a C-extension library to python, I noticed that building it with with wheel (and then install the *.whl) versus a direct install, gives very different results and build artifacts. Building with: pip install -e . We get an entry for Edi...
What is the difference between a "pip wheel -e" and "pip install -e"?
Building a C-extension library to python, I noticed that building it with with wheel (and then install the *.whl) versus a direct install, gives very different results and build artifacts. Building with: pip install -e . We get an entry for Editable project location in the pip list results The buildi atrifacts are few...
[ "So in summary:\n\npip install -e . makes your installed (live) package Editable, by pointing and using the local (package project) directory for all it's files. This way you can edit the package files and see the results immediately.\npip wheel -e . ignores the -e flag because it only builds the wheel, (in your l...
[ 0 ]
[]
[]
[ "pip", "python", "python_3.x", "setuptools" ]
stackoverflow_0074432908_pip_python_python_3.x_setuptools.txt
Q: problem with cvxopt on mac //incompatible architecture I need cvxopt to run some portfolio optimization scripts. I have a MacBook pro with an M1 chip running Monterey 12.3, Python 3.10.2 and pip 22.0.4. I installed cvxopt with pip, also installed Rosetta2 but I keep getting the following message: Exception has occ...
problem with cvxopt on mac //incompatible architecture
I need cvxopt to run some portfolio optimization scripts. I have a MacBook pro with an M1 chip running Monterey 12.3, Python 3.10.2 and pip 22.0.4. I installed cvxopt with pip, also installed Rosetta2 but I keep getting the following message: Exception has occurred: ImportError dlopen(/Library/Frameworks/Python.framewo...
[ "Building cvxopt from source with pip install --no-binary cvxopt cvxopt solved this problem for me.\n" ]
[ 0 ]
[]
[]
[ "cvxopt", "macos", "python" ]
stackoverflow_0071663396_cvxopt_macos_python.txt
Q: Using an API with python Here is the API from this website curl -X POST -F data=@path/to/file.csv https://api-adresse.data.gouv.fr/search/csv/ I would like to know how to use this in python. What I currently know is that from the same website, we also have this API curl "https://api-adresse.data.gouv.fr/search/?q...
Using an API with python
Here is the API from this website curl -X POST -F data=@path/to/file.csv https://api-adresse.data.gouv.fr/search/csv/ I would like to know how to use this in python. What I currently know is that from the same website, we also have this API curl "https://api-adresse.data.gouv.fr/search/?q=8+bd+du+port" With python we...
[ "This worked for me, but I don't know what type of response you are expercting. I got no errors and some values in a test as a result.\nimport requests\n\nfiles = [\n ('data', ('file', open('your path to .csv file', 'rb'), 'application/octet-stream'))\n]\n\nresponse = requests.post(\"https://api-adresse.data.gou...
[ 0 ]
[]
[]
[ "api", "curl", "python", "python_requests" ]
stackoverflow_0074614452_api_curl_python_python_requests.txt
Q: Pandas Dataframe add element to a list in a cell I am trying something like this: List append in pandas cell But the problem is the post is old and everything is deprecated and should not be used anymore. d = {'col1': ['TEST', 'TEST'], 'col2': [[1, 2], [1, 2]], 'col3': [35, 89]} df = pd.DataFrame(data=d) col1 col...
Pandas Dataframe add element to a list in a cell
I am trying something like this: List append in pandas cell But the problem is the post is old and everything is deprecated and should not be used anymore. d = {'col1': ['TEST', 'TEST'], 'col2': [[1, 2], [1, 2]], 'col3': [35, 89]} df = pd.DataFrame(data=d) col1 col2 col3 TEST [1, 2, 3] 35 TEST [1, 2, 3] 89 ...
[ "Not sure if this is the best way to go but, option 2 works with a little modification\nimport pandas as pd\n\nd = {'col1': ['TEST', 'TEST'], 'col2': [[1, 2], [1, 2]], 'col3': [35, 89]}\ndf = pd.DataFrame(data=d)\ndf[\"col2\"] = df[\"col2\"].apply(lambda x: x + [0,0])\nprint(df)\n\nFirstly, if you want to add all m...
[ 3, 0 ]
[ "have you tried the flowing code?\nfor val in df['col2']:\n val.append(0)\n\nBest Regards,\nStan\n" ]
[ -1 ]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074614688_dataframe_pandas_python.txt
Q: Pyinstaller and hiddenimports: how to force to import a package that doesn't get automatically imported by pyinstaller I tried to generate a .exe file using pyinstaller. It works fine, except for fact that one package was not automatically detected and imported by pyinstaller. Such package, that in this example we...
Pyinstaller and hiddenimports: how to force to import a package that doesn't get automatically imported by pyinstaller
I tried to generate a .exe file using pyinstaller. It works fine, except for fact that one package was not automatically detected and imported by pyinstaller. Such package, that in this example we will call "packageOfInterest", did not get imported because the developers did not provide an hook. Reading some documentat...
[ "The .exe crashed because one file is not showing. Such file was belonging to the \"packageofinterest\" (mne)\n\nhmm.. you could try use --collect-data packageofinterest as it seems you are missing some files which are belongs to the package.\nAlso you can use --hidden-import packageofinterest if you don't want to ...
[ 0, 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0068684228_pyinstaller_python.txt
Q: Pandas group-by proportion of cumulative sum start from 0 I have the following pandas Data Frame (without 2 the last columns): name day show-in-appointment previous-missed-appointments proportion-previous-missed 0 Jack 2020/01/01 show 0 0 1 J...
Pandas group-by proportion of cumulative sum start from 0
I have the following pandas Data Frame (without 2 the last columns): name day show-in-appointment previous-missed-appointments proportion-previous-missed 0 Jack 2020/01/01 show 0 0 1 Jack 2020/01/02 no-show 0 ...
[ "You can use cumsum and shift in groupby.apply for the first column, then divide by groupby.cumcount for the second column:\nm = df['show-in-appointment'].eq('no-show')\n\ng = m.groupby(df['name'].str.casefold(), group_keys=False)\ndf['previous-missed-appointments'] = (\n g.apply(lambda x: x.cumsum().shift(fill_v...
[ 1 ]
[]
[]
[ "cumulative_sum", "group_by", "pandas", "proportions", "python" ]
stackoverflow_0074614849_cumulative_sum_group_by_pandas_proportions_python.txt
Q: How to copy content of docx file and append it to another docx file using python I want to combine multiple docx file and save it in another docx file. I not only want to copy all the text, but also it's formatting(runs). eg. bold, italics, underline, bullets, etc. A: If you need to copy the contents of just one...
How to copy content of docx file and append it to another docx file using python
I want to combine multiple docx file and save it in another docx file. I not only want to copy all the text, but also it's formatting(runs). eg. bold, italics, underline, bullets, etc.
[ "If you need to copy the contents of just one docx file to another, you can use this\nfrom docx import Document\nfrom docxcompose.composer import Composer\n\n# main docx file\nmaster = Document(r\"path\\of\\main.docx\")\ncomposer = Composer(master)\n# doc1 is the docx file getting copied\ndoc1 = Document(r\"file\\t...
[ 0 ]
[]
[]
[ "docx", "file_handling", "python", "python_docx" ]
stackoverflow_0067689211_docx_file_handling_python_python_docx.txt
Q: Tkinter Radio button is being selected when hovered over I am having a weird issue with my radio buttons. When I run my program, they are initially unselected (as expected). However, if I mouse over one of them, they will select themselves, and this can allow both to be selected at the same time. This only seems t...
Tkinter Radio button is being selected when hovered over
I am having a weird issue with my radio buttons. When I run my program, they are initially unselected (as expected). However, if I mouse over one of them, they will select themselves, and this can allow both to be selected at the same time. This only seems to happen once per program execution, and manually selecting ei...
[ "You need to declare your variable (option) as global - and yes, it's very strange. Unfortunately, I could not find the reason.\n", "The reason is that the variable option gets garbage-collected.\nYou can avoid this by having a reference to the variable, e.g., by adding self.option = option.\nThis seems to be sim...
[ 1, 0 ]
[]
[]
[ "python", "radio_button", "tkinter" ]
stackoverflow_0057355027_python_radio_button_tkinter.txt
Q: Is Unpacking a Type Hint Possible? or Its Workarounds? Is there a way to unpack a tuple type alias? For example, ResultTypeA = tuple[float, float, dict[str, float]] ResultTypeB = tuple[*ResultTypeA, str, str] So that ResultTypeB evaluates to tuple[float, float, dict[str, float], str, str] instead of tuple[tupl...
Is Unpacking a Type Hint Possible? or Its Workarounds?
Is there a way to unpack a tuple type alias? For example, ResultTypeA = tuple[float, float, dict[str, float]] ResultTypeB = tuple[*ResultTypeA, str, str] So that ResultTypeB evaluates to tuple[float, float, dict[str, float], str, str] instead of tuple[tuple[float, float, dict[str, float]], str, str] If not possibl...
[ "What you are looking for may be the new typing.TypeVarTuple as proposed by PEP 646. Due to how new it is (Python 3.11+) and how big of a change this produces, many static type checkers still do not fully support it (see this mypy issue for example).\nMaybe typing.Unpack is actually more applicable in this case, bu...
[ 2 ]
[]
[]
[ "python", "type_hinting" ]
stackoverflow_0074614332_python_type_hinting.txt
Q: Assign week number relative to month for each date in a DataFrame Let it be the following python pandas dataframe. | date | other_columns |... | ------------- | -------------- |... | 2022-02-06 | row |... | 2022-02-07 | row |... | 2022-02-08 | row |... | 2022-02-...
Assign week number relative to month for each date in a DataFrame
Let it be the following python pandas dataframe. | date | other_columns |... | ------------- | -------------- |... | 2022-02-06 | row |... | 2022-02-07 | row |... | 2022-02-08 | row |... | 2022-02-15 | row |... | 2022-02-24 | row |... | 202...
[ "Could you use something like this?\nimport pandas as pd\nimport math\n\n# create a date range\ndr = pd.date_range(\n start=\"2022-02-01\",\n end=\"2022-02-28\",\n freq=\"D\"\n)\n\n# create a dataframe\ndf = pd.DataFrame(\n {\n \"date\": dr\n }\n)\n\n# define a function to get the week number\...
[ 2, 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074614712_dataframe_datetime_pandas_python.txt
Q: Python scp/paramiko Bad Time Format Exception when attempting to get a file Python 3.9 scp 0.14.4 running on Mac OSX Ventura 13.0 When trying to run the following: def createSSHClient(server, port, user, password): client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(A...
Python scp/paramiko Bad Time Format Exception when attempting to get a file
Python 3.9 scp 0.14.4 running on Mac OSX Ventura 13.0 When trying to run the following: def createSSHClient(server, port, user, password): client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(server, port, user, password) return clien...
[ "I think you are using two different libraries to access the file\nFor paramiko you can use the following to get the file\nsftp = ssh.open_sftp()\nsftp.get(remotepath='/mnt/users/username/file.txt', localpath='file.txt')\n\nrather than\nscp = SCPClient(ssh.get_transport())\nscp.get(remote_path='/mnt/users/username/...
[ 0 ]
[]
[]
[ "paramiko", "python", "scp" ]
stackoverflow_0074614758_paramiko_python_scp.txt
Q: Transform a raw json column of pandas df into more columns in my pandas dataframe I have a column which follows a simple pattern: {'author_position': 'first', 'author': {'id': 'https://openalex.org/A3003121718', 'display_name': 'Chaolin Huang', 'orcid': None}, 'institutions': [{'id': None, 'display_n...
Transform a raw json column of pandas df into more columns
in my pandas dataframe I have a column which follows a simple pattern: {'author_position': 'first', 'author': {'id': 'https://openalex.org/A3003121718', 'display_name': 'Chaolin Huang', 'orcid': None}, 'institutions': [{'id': None, 'display_name': 'Jin Yin-tan Hospital, Wuhan, China', 'ror': None, ...
[ "you can check if the following code works!\ndf = pd.DataFrame()\ndf['authors'] = pd.json_normalize(j)['author.display_name']\ndf['institutions'] = pd.json_normalize(j, record_path=['institutions'])['display_name']\ndf\n\n" ]
[ 1 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074612814_json_pandas_python.txt
Q: Psycopg2 does not recognize the DB I want to drop I tried to write a function to drop database : def deleteDb(self, dbName: str): conn = psycopg2.connect(dbname="postgres", user="postgres") conn.autocommit = True curs = conn.cursor() curs.execute("DROP DATABASE {};".format(dbName)) curs.close()...
Psycopg2 does not recognize the DB I want to drop
I tried to write a function to drop database : def deleteDb(self, dbName: str): conn = psycopg2.connect(dbname="postgres", user="postgres") conn.autocommit = True curs = conn.cursor() curs.execute("DROP DATABASE {};".format(dbName)) curs.close() conn.close() When I try to test it with an existi...
[ "Remember to put quotes around identifiers that contain upper-case letters:\ncurs.execute('DROP DATABASE \"{}\";'.format(dbName))\n\nNote that string substitution into SQL-statements is generally a bad idea beause it is vulnerable to SQL-injection.\n" ]
[ 1 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0074615134_postgresql_psycopg2_python.txt
Q: AttributeError : module 'module.modulename' has no attribute 'register' Apologies everyone. Begining out Python and Flask. I'm trying to add all my routes to a separate routes.py file. Below is my folder structure. - appfolder - routes __init__.py (empty file) routes.py - app.py routes.py...
AttributeError : module 'module.modulename' has no attribute 'register'
Apologies everyone. Begining out Python and Flask. I'm trying to add all my routes to a separate routes.py file. Below is my folder structure. - appfolder - routes __init__.py (empty file) routes.py - app.py routes.py contents from flask import Blueprint routes = Blueprint('routes', __name__)...
[ "You're not actually importing the blueprint from routes.py, you're importing the script containing the blueprint hence the error message\n\nAttributeError: module 'routes.routes' has no attribute 'register'\n\nchange this\nfrom routes import routes\nto\nfrom routes.routes import routes\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0073982014_python.txt
Q: Tuple function that returns certain parameters I'm stuck on an exercise where I should do a function which makes a tuple out of 3 given numbers and returns tuple following these rules: 1st element must be the smallest parameter 2nd element must be the biggest parameter 3rd element is the sum of parameters For ex...
Tuple function that returns certain parameters
I'm stuck on an exercise where I should do a function which makes a tuple out of 3 given numbers and returns tuple following these rules: 1st element must be the smallest parameter 2nd element must be the biggest parameter 3rd element is the sum of parameters For example: > print(do_tuple(5, 3, -1)) # (-1, 5, 7) Wha...
[ "You need to return the tuple inside your function\ndef do_tuple(x: int, y: int, z: int):\n \n tuple_ = (x,y,z)\n summ = x + y + z\n mini = min(tuple_)\n maxi = max(tuple_)\n return (mini, maxi, summ)\n \n \nif __name__ == \"__main__\":\n print(do_tuple(5, 3, -1))\n\n", "As already indic...
[ 2, 2 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0074615011_python_tuples.txt
Q: Error on python - TypeError: 'str' object is not callable I'm starting to code right now, but I've searched on google and found an answer: I know the problem is a variable that is already predefined in python that needs to be renamed, but I can't find it. Can someone help me? import os import pandas as pd lista_a...
Error on python - TypeError: 'str' object is not callable
I'm starting to code right now, but I've searched on google and found an answer: I know the problem is a variable that is already predefined in python that needs to be renamed, but I can't find it. Can someone help me? import os import pandas as pd lista_arquivo = os.listdir(fr"C:\Users\Master\Desktop\cursos\projetos\...
[ "you have a typo in\nif \"abril.xlsx\" in arquivo():\n\nit should be:\nif \"abril.xlsx\" in arquivo:\n\nWhen you are adding () to the variable name it is trying to \"call\" it - execute as a function, but it is string, that's why you're getting error\n" ]
[ 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074615211_python_string.txt
Q: Is it possible to transform one asset into another asset using ops in dagster? From what I found here, it is possible to use ops and graphs to generate assets. However, I would like to use an asset as an input for an op. I am exploring it for a following use case: I fetch a list of country metadata from an extern...
Is it possible to transform one asset into another asset using ops in dagster?
From what I found here, it is possible to use ops and graphs to generate assets. However, I would like to use an asset as an input for an op. I am exploring it for a following use case: I fetch a list of country metadata from an external API and store it in my resource: @dagster.asset def country_metadata_asset() -> ...
[ "It seems to me like the augmented data that's returned from retrieve_and_process_data can (at least in theory) be represented by an asset.\nSo we can start from the standpoint that we'd like to create some asset that takes in country_names_asset, as well as the source data asset (the thing that has a bunch of rows...
[ 1 ]
[]
[]
[ "dagster", "python" ]
stackoverflow_0074613973_dagster_python.txt
Q: Unknown image file format. One of JPEG, PNG, GIF, BMP required I built a simple CNN model and it raised below errors: Epoch 1/10 235/235 [==============================] - ETA: 0s - loss: 540.2643 - accuracy: 0.4358 --------------------------------------------------------------------------- InvalidArgumentError ...
Unknown image file format. One of JPEG, PNG, GIF, BMP required
I built a simple CNN model and it raised below errors: Epoch 1/10 235/235 [==============================] - ETA: 0s - loss: 540.2643 - accuracy: 0.4358 --------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call last) <ipython-input-...
[ "Some of your files in the validation folder are not in the format accepted by Tensorflow ( JPEG, PNG, GIF, BMP), or may be corrupted. The extension of a file is indicative only, and does not enforce anything on the content of the file.\nYou might be able to find the culprit using the imghdr module from the python ...
[ 13, 0, 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0068191448_python_tensorflow.txt
Q: multiprocessing: No space left on device When i run the multiprocessing example on a OSX. I get the Error OSError: [Errno 28] No space left on device. The ENOSPC ("No space left on device") error will be triggered in any situation in which the data or the metadata associated with an I/O operation can't be written...
multiprocessing: No space left on device
When i run the multiprocessing example on a OSX. I get the Error OSError: [Errno 28] No space left on device. The ENOSPC ("No space left on device") error will be triggered in any situation in which the data or the metadata associated with an I/O operation can't be written down anywhere because of lack of space. This ...
[ "One possible reason to run into this error (as in my case), is that the system reaches a limit of allowed POSIX semaphores. This limit can be inspected by the sysctl kern.posix.sem.max command and is 10000 on my macOS 13.0.1.\nTo set it, for example to 15000 until next reboot, you can use:\nsudo sysctl -w kern.pos...
[ 0 ]
[]
[]
[ "multiprocessing", "oserror", "python", "python_3.x" ]
stackoverflow_0070175977_multiprocessing_oserror_python_python_3.x.txt
Q: python app function error when reading a parquet file I am developing a python script that will run as a azure app function. It should read a parquet file from our gen1 datalake and do some processing over it. When running in debug mode in VS Code it works perfectly but when I deploy the script to the app function...
python app function error when reading a parquet file
I am developing a python script that will run as a azure app function. It should read a parquet file from our gen1 datalake and do some processing over it. When running in debug mode in VS Code it works perfectly but when I deploy the script to the app function it retrieve a error with a not very meaninfull message. Ex...
[ "\nWell, the .lsfunction will list all the file in the folder. Instead of that I will suggest that you download the file and then read the file.\n\nTo this you will need to run the following code.\n\n\nmultithread.ADLDownloader(adlsFileSystemClient,lpath=\"< Local Path >\",rpath=\"<Path to file>\")\n\n\nAlso, while...
[ 0, 0 ]
[]
[]
[ "azure_functions", "parquet", "python" ]
stackoverflow_0074513036_azure_functions_parquet_python.txt
Q: Issues with Keras predict function I have trained LSTM model and saved the model in my drive. I uploaded the model and when I use model.predict I get issue, but it used to work before with no problems. What is really strange is that it works fine on my laptop but not on google colab. 2 frames /usr/local/lib/python...
Issues with Keras predict function
I have trained LSTM model and saved the model in my drive. I uploaded the model and when I use model.predict I get issue, but it used to work before with no problems. What is really strange is that it works fine on my laptop but not on google colab. 2 frames /usr/local/lib/python3.7/dist-packages/keras/engine/training....
[]
[]
[ "the model needs to be initialized you can do the model.compiled() which is a good step to do only sometimes Tensorflow loads weights without initializing the values or you can use model.fit() which will prevent the errors.\nFor my examples, the custom layer tells you about how the weights are generated inside the ...
[ -1 ]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074614374_keras_python_tensorflow.txt
Q: wget Python package downloads/saves XML without issue, but not text or html files Have been using this basic code to download and store updated sitemaps from a hosting/crawling service, and it works fine for all the XML files. However, the text and HTML files appear to be in the wrong encoding, but when I force th...
wget Python package downloads/saves XML without issue, but not text or html files
Have been using this basic code to download and store updated sitemaps from a hosting/crawling service, and it works fine for all the XML files. However, the text and HTML files appear to be in the wrong encoding, but when I force them all to a single encoding (UTF-8) there is no change and the files are still unreadab...
[ "After speaking with the sitemap hosting provider (pro-sitemaps.net) it appears that the problem was on their end. The HTML and TXT files I was downloading were being served with the wrong encoding (or something similar to that). Though these files were visible/accessible in the browser from the direct URLs at thei...
[ 0 ]
[]
[]
[ "django", "python", "python_3.x", "urllib", "wget" ]
stackoverflow_0074602922_django_python_python_3.x_urllib_wget.txt
Q: Put yfinance stock data into pandas dataframe Python I have a Pandas DataFrame that looks like this: DataFrame: Ticker Date AAPL 2022-11-22 MSFT 2022-11-22 META 2022-11-22 And I want to add a column that includes the stock price of each stock at that date like this: Ticker Date Price AAPL 2022-11-22 147,47 ...
Put yfinance stock data into pandas dataframe Python
I have a Pandas DataFrame that looks like this: DataFrame: Ticker Date AAPL 2022-11-22 MSFT 2022-11-22 META 2022-11-22 And I want to add a column that includes the stock price of each stock at that date like this: Ticker Date Price AAPL 2022-11-22 147,47 MSFT 2022-11-22 243,71 META 2022-11-2...
[ "no loop is needed , not familiar with yf but nevertheless you can use apply :\ndf['price'] = df.apply(lambda x : yf.download(x.['ticker'], x.['start_date'], x.['start_date']))\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "stock", "yfinance" ]
stackoverflow_0074607047_pandas_python_stock_yfinance.txt
Q: Tkinter: 'image ''pyimage2'' doesn't exist'? My full code from tkinter import * i=0 for i in range(10) : window = Tk() window.title('add image') window = Canvas(window,width= 600, height= 600) window.pack() image=PhotoImage(file=r"C:\\Users\\Konstantinos\\New folder\\hello.png") window.create_image(0,0, anc...
Tkinter: 'image ''pyimage2'' doesn't exist'?
My full code from tkinter import * i=0 for i in range(10) : window = Tk() window.title('add image') window = Canvas(window,width= 600, height= 600) window.pack() image=PhotoImage(file=r"C:\\Users\\Konstantinos\\New folder\\hello.png") window.create_image(0,0, anchor = NW, image=image) window.mainloop() The erro...
[ "The error probably comes from multiple Tk instances. Try removing the for-loop and then it will work. But if your intention was for multiple windows, then you can look into this answer: https://stackoverflow.com/a/36316105/9983213. Feel free to tinker around with the example.\nA smaller example is:\nimport tkinter...
[ 2 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074615153_python_python_3.x_tkinter.txt
Q: Finding a sequence in a dataFrame I'm and amateur working on a project and I need a hand. I need to find a sequence of 5 numbers in order that are consequtive inside a dataframe with only 1 column. They are also in different dataframes. Dataframe b contains about 5000 numbers. E.g. dataframe a = 1.0, 0.0, -2.3, 0....
Finding a sequence in a dataFrame
I'm and amateur working on a project and I need a hand. I need to find a sequence of 5 numbers in order that are consequtive inside a dataframe with only 1 column. They are also in different dataframes. Dataframe b contains about 5000 numbers. E.g. dataframe a = 1.0, 0.0, -2.3, 0.0, 0.3 Dataframe b = 2.0, 1.5, -3.0 ,0....
[ "As I understand you are looking for specific subseries in a series.\nTo illustrate different solutions consider an example\nimport numpy as np\nimport pandas as pd\n\nNVALUES = 10\nNSEGMENT = 3\nISTART = 2\n\ndfb = pd.DataFrame(dict(values=np.random.rand(NVALUES)))\ndfa = pd.DataFrame(dict(values=range(NSEGMENT)))...
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074615187_dataframe_python.txt
Q: Vectorized version of pandas Series.str.find The Series.str.find() function in pandas seems to take only a single integer for the start location. I have a Series containing strings and an array of start positions, and I want to find the position of a given substring starting from the corresponding position of each...
Vectorized version of pandas Series.str.find
The Series.str.find() function in pandas seems to take only a single integer for the start location. I have a Series containing strings and an array of start positions, and I want to find the position of a given substring starting from the corresponding position of each element as follows: a = pd.Series(data=['aaba', '...
[ "I think this is kind of more pythonic way to do so, because you do not have to worry about indexes:\nimport pandas as pd\n\ndef find_from_index(series: pd.Series, to_find: str) -> pd.Series:\n return pd.Series([v.find(to_find, i) for i, v in enumerate(series)])\n\na = pd.Series(data=['aaba', 'ababc', 'cbaauuab'...
[ 0, 0 ]
[]
[]
[ "pandas", "python", "string" ]
stackoverflow_0074615095_pandas_python_string.txt
Q: Pandas groupby doesn't take UTC time into account I have a data frame of several days, that looks something like: df = col1 date 2022-10-31 23:00:00 89.088556 2022-11-01 00:00:00 91.356805 2022-11-01 01:00:00 43.188002 2022-11-01 02:00:00 40.386937 2022-11-0...
Pandas groupby doesn't take UTC time into account
I have a data frame of several days, that looks something like: df = col1 date 2022-10-31 23:00:00 89.088556 2022-11-01 00:00:00 91.356805 2022-11-01 01:00:00 43.188002 2022-11-01 02:00:00 40.386937 2022-11-01 03:00:00 38.045470 ... .....
[ "You may use localization inside group by. This way your group will contain all the times for 1st day and 23:00 for the 31st day, same as in you first table reference.\ndf.groupby(df.index.tz_localize(\"UTC\").tz_convert(\"Europe/Copenhagen\").day).get_group(1)\n\nBtw, a snippet to reproduce your situation:\nimport...
[ 2 ]
[]
[]
[ "datetime", "group_by", "pandas", "python" ]
stackoverflow_0074614438_datetime_group_by_pandas_python.txt
Q: Adding gridlines to each subplot pie chart in matplotlib I have a 2d array with 8 sub arrays. I want to plot each of the array in pie charts as shown: fig, axes = plt.subplots(4, 2,figsize=(15, 15)) axes[0,0].pie(counts_list[0]) axes[0,1].pie(counts_list[1]) axes[1,0].pie(counts_list[2]) axes[1,1].pie(counts_li...
Adding gridlines to each subplot pie chart in matplotlib
I have a 2d array with 8 sub arrays. I want to plot each of the array in pie charts as shown: fig, axes = plt.subplots(4, 2,figsize=(15, 15)) axes[0,0].pie(counts_list[0]) axes[0,1].pie(counts_list[1]) axes[1,0].pie(counts_list[2]) axes[1,1].pie(counts_list[3]) axes[2,0].pie(counts_list[4]) axes[2,1].pie(counts_lis...
[ "The following should work:\nfrom matplotlib import pyplot as plt\n\nfig, ax = plt.subplots()\n\ndata = [32, 45, 67, 12, 1]\n\nax.pie(data)\n\n# turn on frame\nax.set_frame_on(b=True)\n\n# create locations of grid points\nxrange = ax.get_xlim()\nngrids = 7\ndx = (xrange[1] - xrange[0]) / ngrids\ngridvals = [xrange[...
[ 1 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0074615257_matplotlib_numpy_python.txt
Q: Selenium Python: How to set_page_load_timeout, if beyond time return except(not error) I have this code and how to loop if load timeout it will return except and it run next test case def search_action(self, xpath, value): try: self.driver.set_page_load_timeout(1) element = self.driver.find_el...
Selenium Python: How to set_page_load_timeout, if beyond time return except(not error)
I have this code and how to loop if load timeout it will return except and it run next test case def search_action(self, xpath, value): try: self.driver.set_page_load_timeout(1) element = self.driver.find_element(By.XPATH, xpath) element.send_keys(value) element.send_keys(Keys.ENTER...
[ "I guess your problem is not with set_page_load_timeout.\nYou need to use WebDriverWait expected_conditions to wait for element to become clickable.\nwait.until(EC.element_to_be_clickable((By.XPATH, xpath)))\n\nSince you did not share link and xpath details I can't give more detailed answer here.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "webdriverwait", "xpath" ]
stackoverflow_0074615454_python_python_3.x_selenium_webdriverwait_xpath.txt
Q: Import error when calling "import tensorflow" in conda environment I am trying to import TensorFlow using my Conda environment. I received the ImportError message below. I tried to solve it by creating a new environment, installing TensorFlow 2, and trying with this new environment, but the error still appeared. ...
Import error when calling "import tensorflow" in conda environment
I am trying to import TensorFlow using my Conda environment. I received the ImportError message below. I tried to solve it by creating a new environment, installing TensorFlow 2, and trying with this new environment, but the error still appeared. It was work yesterday, and I don't know what is happen today. **>>> imp...
[ "I faced the same issue a couple of days back. I would suggest you to download Anaconda 2020.02 for a seamlessly smooth experience with TensorFlow 2.\nAfter installation;\nYou can execute the following instructions and command to solve the issue: (do not include inverted commas)\nOpen Anaconda Prompt\ntype: create ...
[ 0 ]
[]
[]
[ "anaconda3", "python", "tensorflow2.0" ]
stackoverflow_0074615519_anaconda3_python_tensorflow2.0.txt
Q: How can I split a list of dictionaries in separate lists of dictionaries based on some condition? I am new to python, and I am trying to split a list of dictionaries into separate lists of dictionaries based on some condition. This is how my list looks like this: [{'username': 'AnastasiadesCY', 'created_at': '20...
How can I split a list of dictionaries in separate lists of dictionaries based on some condition?
I am new to python, and I am trying to split a list of dictionaries into separate lists of dictionaries based on some condition. This is how my list looks like this: [{'username': 'AnastasiadesCY', 'created_at': '2020-12-02 18:58:16', 'id': 1.33421029132062e+18, 'language': 'en', 'contenttype': 'text/plain', ...
[ "A better would be to create a dictionary with username as key and value as list of user attributes\nop = defauldict(list)\nfor user_dic in list_of_userdictss:\n op[user_dic.pop('username')].append(user_dic)\nop = OrderedDict(sorted(user_dic.items()))\n\n", "Finding the same thing works the best if we sort the...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "if_statement", "list", "loops", "python" ]
stackoverflow_0066258105_dictionary_if_statement_list_loops_python.txt
Q: How to run async function in FastAPI only once at a time? I'm new to FastAPI and asyncio and don't know how to realise this. I have an endpoint, when called, it should start an AI prediction that takes about 40s in the background. async def asyncio_test_prediction(): print("Starting asnycio func") time.sle...
How to run async function in FastAPI only once at a time?
I'm new to FastAPI and asyncio and don't know how to realise this. I have an endpoint, when called, it should start an AI prediction that takes about 40s in the background. async def asyncio_test_prediction(): print("Starting asnycio func") time.sleep(30); print("Stopping asyncio func") @app.get('/sempos/s...
[]
[]
[ "I suggest changing the expected behavior of your API.\nHow about having two endpoints:\n\n'/sempos/start' - starts the AI prediction and immediately returns the id of the calculation\n'/sempos/result/{id}' - gives a generic message if calculations aren't done, else gives the calculation results JSON\n\nThis way yo...
[ -1 ]
[ "fastapi", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0074614730_fastapi_python_python_3.x_python_asyncio.txt
Q: Pick the file with the shortest name I want to find the .txt file with the shortest name inside a folder. import glob import os inpDir = "C:/Users/ft/Desktop/Folder" os.chdir(inpDir) for file in glob.glob("*.txt"): l = len(file) For the moment I found the length of the str of the name, how can I return the...
Pick the file with the shortest name
I want to find the .txt file with the shortest name inside a folder. import glob import os inpDir = "C:/Users/ft/Desktop/Folder" os.chdir(inpDir) for file in glob.glob("*.txt"): l = len(file) For the moment I found the length of the str of the name, how can I return the shortest name? Thanks
[ "To find the shortest file just compare to the current shortest:\nchosen_file = \"\"\n\nfor file in glob.glob(\"*.txt\"):\n if chosen_file == \"\" or len(file) < len(chosen_file):\n chosen_file = file\n\nprint(f\"{chosen_file} is the shortest file\")\n\n\nOnce you've finished the loop, the chosen_file str...
[ 2, 0, 0 ]
[ "min = 1000\n\nfor file in glob.glob(\"*.txt\"):\n if len(file) < min:\n min = len(file)\n name = file\n\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0074615450_python.txt
Q: unittest, assert if one of two values is in a string Assuming a string of "string" I want my test to pass if one of "x" or "y" passes. If both fail - the test fails. This is what I tried: def check_if_x_or_y_in_string(self): self.assertIn("x", "given string") self.assertIn("y", "given string") It ...
unittest, assert if one of two values is in a string
Assuming a string of "string" I want my test to pass if one of "x" or "y" passes. If both fail - the test fails. This is what I tried: def check_if_x_or_y_in_string(self): self.assertIn("x", "given string") self.assertIn("y", "given string") It keep failing because only one of them can be correct, the ...
[ "assertTrue(\"x\" in s or \"y\" in s).\n– MrBean Bremen\n" ]
[ 0 ]
[]
[]
[ "python", "python_unittest", "unit_testing" ]
stackoverflow_0074615333_python_python_unittest_unit_testing.txt
Q: How to read a python tuple using PyYAML? I have the following YAML file named input.yaml: cities: 1: [0,0] 2: [4,0] 3: [0,4] 4: [4,4] 5: [2,2] 6: [6,2] highways: - [1,2] - [1,3] - [1,5] - [2,4] - [3,4] - [5,4] start: 1 end: 4 I'm loading it using PyYAML and printing the result as follows: ...
How to read a python tuple using PyYAML?
I have the following YAML file named input.yaml: cities: 1: [0,0] 2: [4,0] 3: [0,4] 4: [4,4] 5: [2,2] 6: [6,2] highways: - [1,2] - [1,3] - [1,5] - [2,4] - [3,4] - [5,4] start: 1 end: 4 I'm loading it using PyYAML and printing the result as follows: import yaml f = open("input.yaml", "r") data ...
[ "I wouldn't call what you've done hacky for what you are trying to do. Your alternative approach from my understanding is to make use of python-specific tags in your YAML file so it is represented appropriately when loading the yaml file. However, this requires you modifying your yaml file which, if huge, is probab...
[ 31, 5, 4, 0 ]
[]
[]
[ "python", "pyyaml", "yaml" ]
stackoverflow_0039553008_python_pyyaml_yaml.txt
Q: How to handle CORS for web workers? In one of my js files (game.js), web workers are used which causes problems for CORS. From game.js: var engine = new Worker(options.machinejs|| 'static/js/mainjs/machine.js'); First problem I got was about SharedArrayBuffer is not defined and I solved it by adding the needed he...
How to handle CORS for web workers?
In one of my js files (game.js), web workers are used which causes problems for CORS. From game.js: var engine = new Worker(options.machinejs|| 'static/js/mainjs/machine.js'); First problem I got was about SharedArrayBuffer is not defined and I solved it by adding the needed headers. @app.route("/") def home(): re...
[ "I obviously confused CORS with CORP although they're related.\nThe solution I found was:\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.after_request\ndef add_header_home(response):\n response.headers['Cross-Origin-Embedder-Policy'] = 'require-corp'\n response.headers['Cr...
[ 0 ]
[]
[]
[ "cross_origin_embedder_policy", "cross_origin_resource_policy", "flask", "javascript", "python" ]
stackoverflow_0074613280_cross_origin_embedder_policy_cross_origin_resource_policy_flask_javascript_python.txt
Q: Replace NaN values from DataFrame with values from series I am trying to implement code which will do the following with pandas. def fill_in_capabilities(df): capacity_means = df.groupby("LV_Name").mean(["LEO_Capa", "GTO_Capa"]) for row in df: if np.isnan(row["LEO_Capa"]): row["LEO_Cap...
Replace NaN values from DataFrame with values from series
I am trying to implement code which will do the following with pandas. def fill_in_capabilities(df): capacity_means = df.groupby("LV_Name").mean(["LEO_Capa", "GTO_Capa"]) for row in df: if np.isnan(row["LEO_Capa"]): row["LEO_Capa"] = capacity_means[row["LV_Name"]] return df Basically,...
[ "You can use a function:\ndef fill_in_capabilities(df: pd.DataFrame) -> pd.DataFrame:\n df[[\"LEO_Capa\", \"GTO_Capa\"]] = df[[\"LEO_Capa\", \"GTO_Capa\"]].fillna(\n df.groupby(\"LV_Name\")[[\"LEO_Capa\", \"GTO_Capa\"]].transform(\"mean\")\n )\n\n return df\n\n\ndf = fill_in_capabilities(df)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "nan", "pandas", "python", "series" ]
stackoverflow_0074615607_dataframe_nan_pandas_python_series.txt
Q: Flask for to have result as variable I have below form which selects the data and redirects to the page user_data It selects the date and redirects to another page. Am able to get the data using request.form['Period'] method in python. But this is not getting called in form action <form action = "/user_data/{{per...
Flask for to have result as variable
I have below form which selects the data and redirects to the page user_data It selects the date and redirects to another page. Am able to get the data using request.form['Period'] method in python. But this is not getting called in form action <form action = "/user_data/{{period}}" method="POST"> period variable is e...
[ "two options here:\n\nlet form direct to url /user_data, and based on the Period value renders the page i.e it renders the data for that month.\nas value is based on user selection, JS can be utilized.\n\n<html>\n <body>\n<form action = \"/user_data/{{period}}\" method=\"POST\" id=\"myForm\">\n <label for = \...
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074614627_flask_python.txt
Q: Try using .loc[row_indexer,col_indexer] = value instead again Following line of code: df_under['Work Ratio']=df_under['Work Ratio'].astype(float) is generating Try using .loc[row_indexer,col_indexer] = value instead warning. How to get rid of it? Thank you for help A: This looks like a pandas dataframe and you ...
Try using .loc[row_indexer,col_indexer] = value instead again
Following line of code: df_under['Work Ratio']=df_under['Work Ratio'].astype(float) is generating Try using .loc[row_indexer,col_indexer] = value instead warning. How to get rid of it? Thank you for help
[ "This looks like a pandas dataframe and you would like to change the data type of the column 'Work Ratio'? The warning tells you that by changing df_under['Work Ratio'] you will not change the actual dataframe in place. The warning tells you to access the column by saying\ndf_under.loc[:,'Work Ratio']=df_under['Wor...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074615334_python.txt
Q: Cannot open anaconda suddenly Today I found I cannot open anaconda navigator, which operated just fine before. At the same time, spyder could not be open either, but jupyter notebook and anaconda prompt are available. I tried different methods following instructions online. 1) conda update anaconda-navigator and r...
Cannot open anaconda suddenly
Today I found I cannot open anaconda navigator, which operated just fine before. At the same time, spyder could not be open either, but jupyter notebook and anaconda prompt are available. I tried different methods following instructions online. 1) conda update anaconda-navigator and reboot the system 2) anaconda-naviga...
[ "This error means that you installed pyqt5 with pip along side the pyqt conda package. It could be solved by you uninstalling the pip package.\nTry:\npip uninstall PyQt5\n\nThen update conda:\nconda update conda\n\nand \nconda update anaconda-navigator\n\nIt will surely resolve your problem.\n", "I tried all the ...
[ 40, 5, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "anaconda", "python", "spyder" ]
stackoverflow_0051435579_anaconda_python_spyder.txt
Q: How to filter a collection by multiple conditions I have a csv file named film.csv here is the header line with a few lines to use as an example Year;Length;Title;Subject;Actor;Actress;Director;Popularity;Awards;*Image 1990;111;Tie Me Up! Tie Me Down!;Comedy;Banderas, Antonio;Abril, Victoria;Almodóvar, Pedro;68;No...
How to filter a collection by multiple conditions
I have a csv file named film.csv here is the header line with a few lines to use as an example Year;Length;Title;Subject;Actor;Actress;Director;Popularity;Awards;*Image 1990;111;Tie Me Up! Tie Me Down!;Comedy;Banderas, Antonio;Abril, Victoria;Almodóvar, Pedro;68;No;NicholasCage.png 1991;113;High Heels;Comedy;Bosé, Migu...
[ "You know how to add one filter. There is no such thing as \"additional\" filters. Just add your conditions to the current condition. Since you want all of the conditions to be True to select a record, you'd use the boolean and logic. For example:\nfiltered = (\n col[\"Title\"] \n for col in...
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074615660_csv_python.txt
Q: Palindrome check for items in a list. Return True or False for each Is there a way to have a function take in a list and then return true or false for each item in the list if they are palindromes? Below is what I have tried but I would like the console to look like this: True False True x=[121,13,155551] def pal...
Palindrome check for items in a list. Return True or False for each
Is there a way to have a function take in a list and then return true or false for each item in the list if they are palindromes? Below is what I have tried but I would like the console to look like this: True False True x=[121,13,155551] def palindrome_check(x): for num_from__list in x: if str(num_from__l...
[ "x = [121,13,155551]\n\ndef palindrome_check(x):\n res = []\n for num_from__list in x:\n res.append(str(num_from__list) == str(num_from__list)[::-1])\n return res\n\nprint(palindrome_check(x))\n\nor even better:\nx = [121,13,155551]\n\ndef palindrome_check(x):\n return [str(num_from__list) == str...
[ 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074614956_python.txt
Q: Merge multiple PDFs and keep nested bookmarks I am trying to merge a few PDFs and keep the nested bookmarks all pdfs have a content parent in common when only one is needed, when i use the code below only the bookmarks of the last pdf in the folder are present in the merge, can anyone advise on what i need to chan...
Merge multiple PDFs and keep nested bookmarks
I am trying to merge a few PDFs and keep the nested bookmarks all pdfs have a content parent in common when only one is needed, when i use the code below only the bookmarks of the last pdf in the folder are present in the merge, can anyone advise on what i need to change to have all the bookmarks preserved and a shared...
[ "Every time you run in your for loop:\noutlines = fileReader.getOutlines()\nyou are overwriting the contents of outlines not appending to it. So it is not surprising you end up with only the last.\nWhat is the type of outlines? Is it a list or similar? Consult the PyPDF2 documentation to find out, and work out how ...
[ 0, 0 ]
[]
[]
[ "bookmarks", "pypdf2", "python" ]
stackoverflow_0074571369_bookmarks_pypdf2_python.txt