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: Why does numpy.dot give incorrect results? This code: a = np.array([10], dtype=np.int8) b = np.array([2], dtype=np.int8) print(np.dot(a, b)) a = np.array([10], dtype=np.int8) b = np.array([5], dtype=np.int8) print(np.dot(a, b)) a = np.array([10], dtype=np.int8) b = np.array([20], dtype=np.int8) print(np.dot(a,...
Why does numpy.dot give incorrect results?
This code: a = np.array([10], dtype=np.int8) b = np.array([2], dtype=np.int8) print(np.dot(a, b)) a = np.array([10], dtype=np.int8) b = np.array([5], dtype=np.int8) print(np.dot(a, b)) a = np.array([10], dtype=np.int8) b = np.array([20], dtype=np.int8) print(np.dot(a, b)) produces the following output: 20 50 -56 ...
[ "It can depends on the dtype used. In fact, if I change the dtype:\na = np.array([10])\nb = np.array([2])\nprint(np.dot(a, b))\n\na = np.array([10])\nb = np.array([5])\nprint(np.dot(a, b))\n\na = np.array([10])\nb = np.array([20])\nprint(np.dot(a, b))\n\nThe Output is:\n20\n50\n200\n\n", "This is true for multipl...
[ 1, 1, 0 ]
[]
[]
[ "dot_product", "numpy", "python" ]
stackoverflow_0074359220_dot_product_numpy_python.txt
Q: Writing one CSV file for each text file containg driving license information [J RYBEWYS 1 Mesters: Lambertus # » 05.01.1979 Eindhoven 40.31.01.2017 4» 31.01.2027 4< Gemeente Waaire 5740344641 AM-BE , a T D1NLD1574034464194NB44MK362D54]1 I have more than thousands of text files containing the information shown in t...
Writing one CSV file for each text file containg driving license information
[J RYBEWYS 1 Mesters: Lambertus # » 05.01.1979 Eindhoven 40.31.01.2017 4» 31.01.2027 4< Gemeente Waaire 5740344641 AM-BE , a T D1NLD1574034464194NB44MK362D54]1 I have more than thousands of text files containing the information shown in the example image and I want to write one CSV file for each text file. The text fil...
[ "Python can't find the files (hence the FileNotFoundError), because\ndf_list = [pd.read_csv(file, header = None, encoding='latin1') for file in filelist]\n\ngives a list of filenames (without the actual path to the file). If you add the path, it should read the files without a problem.\ndf_list = [pd.read_csv(f'{ta...
[ 1 ]
[]
[]
[ "csv", "python", "text_files" ]
stackoverflow_0074363681_csv_python_text_files.txt
Q: Pandas - revert a cumsum with NaN values Is there a way to get original column back from column which is a cumsum() of the original column? For example: df = pd.DataFrame({'Original': [1, 0, 0, 1, 0, 5, 0, np.NaN, np.NaN,4, 0, 0], 'CumSum': [1, 1, 1, 2, 2, 7, 7, np.NaN, np.NaN, 11, 11, 11]}) In...
Pandas - revert a cumsum with NaN values
Is there a way to get original column back from column which is a cumsum() of the original column? For example: df = pd.DataFrame({'Original': [1, 0, 0, 1, 0, 5, 0, np.NaN, np.NaN,4, 0, 0], 'CumSum': [1, 1, 1, 2, 2, 7, 7, np.NaN, np.NaN, 11, 11, 11]}) In the above example df, Is it possible to get o...
[ "You can use:\ndf['Original2'] = (df['CumSum'].ffill().diff()\n .mask(df['CumSum'].isna())\n .fillna(df['CumSum'])\n )\n\nOutput:\n Original CumSum Original2\n0 1.0 1.0 1.0\n1 0.0 1.0 0.0\n2 0.0 1.0 0.0\n...
[ 1 ]
[]
[]
[ "cumsum", "pandas", "python" ]
stackoverflow_0074363983_cumsum_pandas_python.txt
Q: How do I find out my fine-tunes models using Python? Hi can anyone help me with Python code to list my fine-tunes models? Is there an equivalent to the openai.file.list() I have tried openai.models.list() openai.fine-tunes.list() A: I just had the same problem. This works for me. openai.FineTune.list()
How do I find out my fine-tunes models using Python?
Hi can anyone help me with Python code to list my fine-tunes models? Is there an equivalent to the openai.file.list() I have tried openai.models.list() openai.fine-tunes.list()
[ "I just had the same problem. This works for me.\nopenai.FineTune.list()\n\n" ]
[ 2 ]
[]
[]
[ "openai", "python" ]
stackoverflow_0074359480_openai_python.txt
Q: Is there a method to check if a portion of text inside a xlsx cell is bold? Using openpyxl we can properly check if a cell is fully bold/not bold, but we cannot work with richtext so having two words, one bolded and one not, will make the check fail. This can be done correctly with xlrd, but it doesn't support xls...
Is there a method to check if a portion of text inside a xlsx cell is bold?
Using openpyxl we can properly check if a cell is fully bold/not bold, but we cannot work with richtext so having two words, one bolded and one not, will make the check fail. This can be done correctly with xlrd, but it doesn't support xlsx files. Converting from xlsx to xls is risky, especially in my use case, since I...
[ "TL;DR: not yet, but upcoming openpyxl v3.1 will be able to satisfy your request.\n\nI took a quick tour through the late 2022 state of python-excel affair with respect to this very feature, which relies on being able to manage Rich Text objects as cell contents:\n\npylightxl was new to me, so I quickly browsed the...
[ 1, 0 ]
[]
[]
[ "excel", "python", "xlsx" ]
stackoverflow_0074363374_excel_python_xlsx.txt
Q: Extracting Powerpoint background images using python-pptx I have several powerpoints that I need to shuffle through programmatically and extract images from. The images then need to be converted into OpenCV format for later processing/analysis. I have done this successfully for images in the pptx, using: for slide...
Extracting Powerpoint background images using python-pptx
I have several powerpoints that I need to shuffle through programmatically and extract images from. The images then need to be converted into OpenCV format for later processing/analysis. I have done this successfully for images in the pptx, using: for slide in presentation: for shape in slide.shapes if 'Pic...
[ "After a fair bit of work I discovered how to do this -- i.e., you don't. As far as I can tell, there is no way to directly extract the backgrounds with either python-pptx or Aspose. Powerpoint -- which, as it turns out, is an archive that can be unzipped with 7zip -- keeps its backgrounds disassembled in the ppt/m...
[ 0 ]
[]
[]
[ "powerpoint", "python", "python_pptx" ]
stackoverflow_0074224766_powerpoint_python_python_pptx.txt
Q: Unable to create table in snowflake from databricks for kafka topic I am connecting a kafka topic, applying some transformation on dataframe and writing that data in snowflake with help of databricks. If table is present, it is successfully writing the data. However, if it is not present, it is giving me an error:...
Unable to create table in snowflake from databricks for kafka topic
I am connecting a kafka topic, applying some transformation on dataframe and writing that data in snowflake with help of databricks. If table is present, it is successfully writing the data. However, if it is not present, it is giving me an error: net.snowflake.client.jdbc.SnowflakeSQLException: SQL compilation error:...
[ "When the mode is changed to \"Overwrite\", it is creating table but old data of previous batch job was getting deleted.\npreactions was creating table but was not suitable for current scenario. As it is creating for each batch and thus failing.\nSo, I used following part to create table if it doesn't exist.\nsf_ut...
[ 0 ]
[]
[]
[ "apache_kafka", "databricks", "pyspark", "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074357282_apache_kafka_databricks_pyspark_python_snowflake_cloud_data_platform.txt
Q: How to justify text in a Button in Python ttk I'm trying to justify (align) text in a button, let's say to the left. I've found some useful code here, based on that I've created code below to check how the label behaves. import tkinter as tk import tkinter.ttk as ttk app = tk.Tk() style = ttk.Style() style.layout...
How to justify text in a Button in Python ttk
I'm trying to justify (align) text in a button, let's say to the left. I've found some useful code here, based on that I've created code below to check how the label behaves. import tkinter as tk import tkinter.ttk as ttk app = tk.Tk() style = ttk.Style() style.layout( 'Left1.TButton',[ ('Button.b...
[ "I've just been using the following style and it's working - this applies the anchor='center' configuration to all of my buttons, but you can create your own style for each wherein you just change 'TButton' to '{insert your style name}.TButton' (more on that https://www.pythontutorial.net/tkinter/ttk-style/ - under...
[ 0, 0 ]
[]
[]
[ "python", "tkinter", "ttk" ]
stackoverflow_0052314309_python_tkinter_ttk.txt
Q: Run a Word VBA Macro with Python I am trying to call a Word macro using Python. I tried to adopt the logic used to run Excel VBA Macros through Python (there are plenty of examples of how to run Excel Macros through python, but I did not find any for word). Here is the code I am trying to use. However, what I get ...
Run a Word VBA Macro with Python
I am trying to call a Word macro using Python. I tried to adopt the logic used to run Excel VBA Macros through Python (there are plenty of examples of how to run Excel Macros through python, but I did not find any for word). Here is the code I am trying to use. However, what I get is that Python keeps running forever a...
[ "Why don't you run your VBA marco indirectly via Cscript/Wscript? You don't have to use comtypes package.\nLet's create a VBS file to run marco:\nSet objExcel = CreateObject(\"Excel.Application\")\nSet objWorkbook = objExcel.Workbooks.Open(\"test.xls\")\n\nobjExcel.Application.Visible = True\nobjExcel.Workbooks.Add...
[ 1 ]
[]
[]
[ "ms_word", "python", "vba" ]
stackoverflow_0057065202_ms_word_python_vba.txt
Q: How to edit a column in pandas data frame based on the value in a different column Column to edit Value to insert Rule protein.carbs.fats banana healthy protein.carbs.fats chips unhealthy I have the above data frame. I need to scan every row in the data frame and insert in 'Column to edit' the value from 'Value...
How to edit a column in pandas data frame based on the value in a different column
Column to edit Value to insert Rule protein.carbs.fats banana healthy protein.carbs.fats chips unhealthy I have the above data frame. I need to scan every row in the data frame and insert in 'Column to edit' the value from 'Value to insert' based on the rule and also edit some of the elements. I could pro...
[ "You could create a function that takes each row at a time using apply:\ndef update_col_to_edit(row):\n str_spl = row['column to edit'].split('.')\n if row['Rule'] == 'healthy':\n return f'{str_spl[0]}.{str_spl[1]}.{row['value to insert']}.{str_spl[2]}'\n else:\n return f'{str_spl[0]}.needHea...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074363844_dataframe_pandas_python.txt
Q: how to count consecutive month that is present in a data frame by id using Python Using Python, I need to count, by id, how many consecutive months exist, leading up to the month of the row. This is a running count that should restart once there was a missing month. Here is an example, with the desired outcome in ...
how to count consecutive month that is present in a data frame by id using Python
Using Python, I need to count, by id, how many consecutive months exist, leading up to the month of the row. This is a running count that should restart once there was a missing month. Here is an example, with the desired outcome in the output column. date <- c("01-01-2021", "02-01-2021", "03-01-2021", "05-01-2021", "0...
[ "You could try:\nimport numpy as np\nimport pandas as pd\n\ndates = pd.to_datetime([\"01-01-2021\", \"02-01-2021\", \"03-01-2021\", \"05-01-2021\", \"06-01-2021\", \"01-01-2021\", \"03-01-2021\", \"04-01-2021\"], format=\"%m-%d-%Y\")\nids = [\"a\",\"a\",\"a\",\"a\",\"a\",\"b\",\"b\",\"b\"]\n\ndf = pd.DataFrame({\n ...
[ 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074363854_dataframe_numpy_pandas_python.txt
Q: Why am I not able to feed my data series from pandas into calmap.yearplot? Trying to create a calendar heat map Beginner question here. What I'm trying to build: A program that takes data from a CSV and creates a calendar heat map from it. I am a language learner (language as in spanish, japanese, etc) and the dat...
Why am I not able to feed my data series from pandas into calmap.yearplot? Trying to create a calendar heat map
Beginner question here. What I'm trying to build: A program that takes data from a CSV and creates a calendar heat map from it. I am a language learner (language as in spanish, japanese, etc) and the data set I'm using is a CSV that shows how many hours I spent immersing in my target language per day. I want the indivi...
[ "The question is a bit old, but in case anyone is interested, I had the same problem and found that this notebook was very helpful to solve the issue: https://github.com/amandasolis/Fitbit/blob/master/FitbitSummaryPlots.ipynb\nimport numpy as np\nimport pandas as pd\nimport calmap\n\nfulldf = pd.read_csv(\"./data.c...
[ 0 ]
[]
[]
[ "calmap", "heatmap", "matplotlib", "pandas", "python" ]
stackoverflow_0067539132_calmap_heatmap_matplotlib_pandas_python.txt
Q: Reading lists as lists and strings as strings from a csv file into a pandas dataframe? I just found out that when storing a dataframe in csv everything gets stored as a string. My problem is now that I have a dataframe where I have a list in the form of : "['a', 'b', 'c']" for some cells in my csvs and some in th...
Reading lists as lists and strings as strings from a csv file into a pandas dataframe?
I just found out that when storing a dataframe in csv everything gets stored as a string. My problem is now that I have a dataframe where I have a list in the form of : "['a', 'b', 'c']" for some cells in my csvs and some in the form: 'a' looking like: col1 col2 [a,b,c] [b,a,c] a b all of the values have...
[ "I found a solution by just checking if a string contains a list and then transforming it to a list.\nfrom ast import literal_eval\n\ndf[col1] = df[col1].apply(lambda x: literal_eval(x) if \"[\" in x else x)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074363725_dataframe_list_pandas_python.txt
Q: Align text in tkinter Button By default text in Button is centered but I want it to be aligned to the left so when I type more text than the button can display it wont cut the start of the sentence/word. Thanks for help. A: You can use anchor="w" when defining the button. However, some platforms may ignore that....
Align text in tkinter Button
By default text in Button is centered but I want it to be aligned to the left so when I type more text than the button can display it wont cut the start of the sentence/word. Thanks for help.
[ "You can use anchor=\"w\" when defining the button. However, some platforms may ignore that. For example, on older version of OSX the text will always be centered.\n", "I used this to justify the text in my buttons to the left. I have multiple buttons with different text lengths. They're easier to read if the t...
[ 10, 0 ]
[]
[]
[ "button", "python", "python_3.x", "tkinter" ]
stackoverflow_0042626496_button_python_python_3.x_tkinter.txt
Q: How to install Python using Windows Command Prompt Is it possible to install Python from cmd on Windows? If so, how to do it? A: https://docs.python.org/3.6/using/windows.html#installing-without-ui Installing Without UI: All of the options available in the installer UI can also be specified from the command l...
How to install Python using Windows Command Prompt
Is it possible to install Python from cmd on Windows? If so, how to do it?
[ "https://docs.python.org/3.6/using/windows.html#installing-without-ui\n\nInstalling Without UI: All of the options available in the installer UI\n can also be specified from the command line, allowing scripted\n installers to replicate an installation on many machines without user\n interaction. These options ma...
[ 14, 1, 0, 0 ]
[]
[]
[ "cmd", "installation", "python", "python_install" ]
stackoverflow_0046056161_cmd_installation_python_python_install.txt
Q: python - execute shell command with DISPLAY specified? I read through a lot of the answers but can't figure out how to execute a command which I currently execute using cron from subprocess or something better? # cron command 00 16 * * 1-5 DISPLAY=:10 /path/to/shell/script.sh > log/file.log 2>&1 The DISPLAY is Xv...
python - execute shell command with DISPLAY specified?
I read through a lot of the answers but can't figure out how to execute a command which I currently execute using cron from subprocess or something better? # cron command 00 16 * * 1-5 DISPLAY=:10 /path/to/shell/script.sh > log/file.log 2>&1 The DISPLAY is Xvfb.
[ "Set the environment variable using os.environ, then run the command using the subprocess module.\nimport subprocess\nimport os\n\nos.environ['DISPLAY'] = ':10'\nwith open('log/file.log') as out:\n subprocess.Popen(['/path/to/shell/script.sh'], stdout=out, stderr=subprocess.STDOUT)\n\n", "Using the env= argume...
[ 1, 0 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0074363811_python_shell.txt
Q: Type hinting dict with key/value type pairs Is it possible with Python type hints to specify the types of a dictionary's keys and values as pairs ? For instance : If key is an int, value should be a str If key is a str, value should be an int If I write : Dict[Union[int, str], Union[int, str]] it allows str -> ...
Type hinting dict with key/value type pairs
Is it possible with Python type hints to specify the types of a dictionary's keys and values as pairs ? For instance : If key is an int, value should be a str If key is a str, value should be an int If I write : Dict[Union[int, str], Union[int, str]] it allows str -> str and int -> int, which are not allowed. And wi...
[ "If using typing.cast is acceptable for your application, then this can be done by making a class that subclasses Dict that has overrides for __setitem__ and __getitem__, casting your dict to that type. From then on, type checkers will infer correct KeyType: ValueType pairs.\nThe caveats of this approach are that y...
[ 1 ]
[]
[]
[ "dictionary", "python", "python_3.x", "type_hinting" ]
stackoverflow_0060114492_dictionary_python_python_3.x_type_hinting.txt
Q: How to close a socket inside an fastapi StreamingResponse generator? The code below doesn't reach out of the with. Is there any way I can close the socket when the client disconnects? import fastapi import uvicorn import socket def gen_video(port): with socket.socket() as s: s.connect(("127.0.0.1", po...
How to close a socket inside an fastapi StreamingResponse generator?
The code below doesn't reach out of the with. Is there any way I can close the socket when the client disconnects? import fastapi import uvicorn import socket def gen_video(port): with socket.socket() as s: s.connect(("127.0.0.1", port)) while True: yield s.recv(1024) app = fastapi.Fa...
[ "An approach using fastapi BackgroundTasks to close the socket\nimport fastapi\nimport uvicorn\nimport socket\n\ndef read_socket(s):\n while True:\n yield s.recv(1024)\n\napp = fastapi.FastAPI()\n\n@app.get(\"/stream\")\nasync def stream(background_tasks: fastapi.background.BackgroundTasks):\n s = sock...
[ 0 ]
[]
[]
[ "fastapi", "python", "python_3.x", "sockets" ]
stackoverflow_0074363541_fastapi_python_python_3.x_sockets.txt
Q: How do I pass user input as a string in an API request? I am trying to take user input (zipCode) and pass that into an API request. How do I format the zipCode user input so that the GET request reads it as a string. import requests zipCode_format = '' def user_input(): zipCode = input('What is your zipcode? ...
How do I pass user input as a string in an API request?
I am trying to take user input (zipCode) and pass that into an API request. How do I format the zipCode user input so that the GET request reads it as a string. import requests zipCode_format = '' def user_input(): zipCode = input('What is your zipcode? Zipcode: ') zipCode_format = "zipCode" return zipCode...
[ "Firstly, function user_input() returns which means that in the left side of function call you need to have a variable in which you pass return from function. Secondly, you need to pass this variable to a function.\nThe third thing is that input() outcome is a string even if you provide number.\nzipCode = input(\"P...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074364154_python_python_3.x.txt
Q: Create a module, Lab04_yourname_module.py that contains the following functions: containsLetter() : checks whether or not the given string word includes the given character ch (Use for loop). The method will return True or False. ruleChecker() : gets a string sentence and checks whether it conforms to a special ru...
Create a module, Lab04_yourname_module.py that contains the following functions:
containsLetter() : checks whether or not the given string word includes the given character ch (Use for loop). The method will return True or False. ruleChecker() : gets a string sentence and checks whether it conforms to a special rule or not. The method returns -1, if the input string obeys the rule (see below). Oth...
[ "First of all, it is necessary to create a CustomString class that inherits from str (python's own class). First, the containsLetter method will receive a string and validate that the letter is in self (remember that self is an object that inherits from str). In this case the .lower() method is applied to both stri...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074364022_python.txt
Q: What does pre_classifier in distilbert do? I was reading huggingface's DistilBertForSequenceClassification implementation code and noticed that they create a classifier and a pre_classifier when initiating the object. Later in the forward method they send the pooled output to the pre_classifier before preparing an...
What does pre_classifier in distilbert do?
I was reading huggingface's DistilBertForSequenceClassification implementation code and noticed that they create a classifier and a pre_classifier when initiating the object. Later in the forward method they send the pooled output to the pre_classifier before preparing and sending it to the classifier. Unfortunately, I...
[ "I found the answer myself. It was rather difficult to find but that is actually the dense layer. Since DistilBert does not have a pooler, it does not need a dense layer. But for sequence classification a pooler is added so the dense layer is also needed. In other words self.pre_classifer in DistilBert is the same ...
[ 0 ]
[]
[]
[ "distilbert", "huggingface_transformers", "python" ]
stackoverflow_0074350758_distilbert_huggingface_transformers_python.txt
Q: Spotify Client Credentials Flow using Python I'm trying to get a token using Spotify's Client Credentials Flow and Python, however I just get the following: {"error":"invalid_client","error_description":"Invalid client"} I'm following this guide - https://developer.spotify.com/documentation/general/guides/authoriz...
Spotify Client Credentials Flow using Python
I'm trying to get a token using Spotify's Client Credentials Flow and Python, however I just get the following: {"error":"invalid_client","error_description":"Invalid client"} I'm following this guide - https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/ Using this example scrip...
[ "I had the same problem while following a tutorial but I manage to find a solution on the Spotify community.\nimport requests\n\nimport base64\n\nclient_id = \"your client id here\"\nclient_secret = \"your client secret here\"\n\nencoded = base64.b64encode((client_id + \":\" + client_secret).encode(\"ascii\")).deco...
[ 1 ]
[]
[]
[ "python", "spotify" ]
stackoverflow_0073122900_python_spotify.txt
Q: Django-ckeditor: editor-element-conflict Django-ckeditor in for loop shows correctly only for the first iteration. For the remaining iterations, the default template form appears as shown below. I see element conflict error in the documentation but it doesn't say anything how to solve. ckeditor.js:21 [CKEDITOR] Er...
Django-ckeditor: editor-element-conflict
Django-ckeditor in for loop shows correctly only for the first iteration. For the remaining iterations, the default template form appears as shown below. I see element conflict error in the documentation but it doesn't say anything how to solve. ckeditor.js:21 [CKEDITOR] Error code: editor-element-conflict. Thank you ...
[ "I've figured out!\nIt happens because fields have the same ID, and CKEditor gets confused because it finds a few elements with the same ID.\nSolution: change IDs dynamically when the page is being generated.\nI don't know the structure of your model, but I can assume that your form is defined like this:\nclass Com...
[ 1 ]
[]
[]
[ "django", "django_ckeditor", "python", "templates" ]
stackoverflow_0072927622_django_django_ckeditor_python_templates.txt
Q: Sorting lists with multiple tie breakers I have data in an array like so: array([[ 5, 5, 5, 6, 9, 6, 6], [10, 4, 10, 3, 5, 3, 3], [10, 3, 10, 4, 5, 3, 4], [ 9, 6, 8, 8, 10, 6, 9], [10, 10, 10, 7, 10, 4, 4], [10, 6, 10, 5, 9, 7, 5], [ 9, 7, 10,...
Sorting lists with multiple tie breakers
I have data in an array like so: array([[ 5, 5, 5, 6, 9, 6, 6], [10, 4, 10, 3, 5, 3, 3], [10, 3, 10, 4, 5, 3, 4], [ 9, 6, 8, 8, 10, 6, 9], [10, 10, 10, 7, 10, 4, 4], [10, 6, 10, 5, 9, 7, 5], [ 9, 7, 10, 7, 10, 8, 10], [ 8, 5, 10, 7, 10, ...
[ "You can achieve it with numpy.frompyfunc.\nThe basic idea is to construct an array with the same rows, each element of which is a tuple containing the number of 10s, 9s, etc. Then apply numpy.argsort to this array and get the result.\nimport numpy as np\n\narr = np.array([[ 5, 5, 5, 6, 9, 6, 6],\n ...
[ 2, 0 ]
[]
[]
[ "numpy", "numpy_ndarray", "python", "sorting" ]
stackoverflow_0074363164_numpy_numpy_ndarray_python_sorting.txt
Q: ValueError:Reshape your data either using array.reshape(-1, 1)if your data has a single feature or array.reshape(1, -1) if it contains a single sample **the code predict the house price with polynomial regression model and fastapi **` make class have an one parameter and have a 4 value class features(BaseModel): ...
ValueError:Reshape your data either using array.reshape(-1, 1)if your data has a single feature or array.reshape(1, -1) if it contains a single sample
**the code predict the house price with polynomial regression model and fastapi **` make class have an one parameter and have a 4 value class features(BaseModel): X2_house_age: float X3_distance_to_the_nearest_MRT_station: float X4_number_of_convenience_stores: float year: int #The train_plynomial_mod...
[ "You should change features array not newfeatures.\nTry reshaping like this and using a numpy array :\nfeatures = np.array(features).reshape((len(features), 1))\n\n" ]
[ 0 ]
[]
[]
[ "fastapi", "linear_regression", "machine_learning", "python", "python_3.x" ]
stackoverflow_0074362051_fastapi_linear_regression_machine_learning_python_python_3.x.txt
Q: Pandas sort column values with "0" values at end of column I have a dataframe which looks like this pd.DataFrame({'A': [5, 2, 0, 0, -3, -2, 1]}).sort_values('A') Out[6]: A 4 -3 5 -2 2 0 3 0 6 1 1 2 0 5 I would like to have "0" values at the end when sorting so my resulting dataframe looks like this. A...
Pandas sort column values with "0" values at end of column
I have a dataframe which looks like this pd.DataFrame({'A': [5, 2, 0, 0, -3, -2, 1]}).sort_values('A') Out[6]: A 4 -3 5 -2 2 0 3 0 6 1 1 2 0 5 I would like to have "0" values at the end when sorting so my resulting dataframe looks like this. A 4 -3 5 -2 6 1 1 2 0 5 2 0 3 0 Is there a simple (1 line o...
[ "Let's try adding a new column and sort by two columns:\ndf.assign(dummy=df.A.eq(0)).sort_values(['dummy','A']).drop('dummy', axis=1)\n\nAnother option, not quite a one-liner, is mask and concat:\nmask = df['A'].eq(0)\ndf = pd.concat([df[~mask].sort_values('A'), df[mask]])\n\nOutput:\n A\n4 -3\n5 -2\n6 1\n1 2\n...
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0064141557_pandas_python.txt
Q: How to extract first element from pandas dataframe? ods_file = io.BytesIO(response.body) df = read_ods(ods_file, sheet_name) df_one = df.apply(lambda c: str(c[0]).strip("[]")) print(df_one) Result from print is: [Report for: 02-Nov-2022] N unnamed.1 N unnamed....
How to extract first element from pandas dataframe?
ods_file = io.BytesIO(response.body) df = read_ods(ods_file, sheet_name) df_one = df.apply(lambda c: str(c[0]).strip("[]")) print(df_one) Result from print is: [Report for: 02-Nov-2022] N unnamed.1 N unnamed.2 N unnamed.3 N Ho...
[ "You can get the first element of the first column like this :\nelement = df_one.iloc[0,0]\n\ncheck : https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html\nfor more details.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074361894_python_python_3.x.txt
Q: How to transform current date and use it as a parameter in function? I want to create a script that run at a specific date everyday given the variable status as a parameter. The status can take two entries: "past" or "present". I want to save the current date as a parameter and use it after in a function to make d...
How to transform current date and use it as a parameter in function?
I want to create a script that run at a specific date everyday given the variable status as a parameter. The status can take two entries: "past" or "present". I want to save the current date as a parameter and use it after in a function to make different calls. So the current time becomes also a parameter. For example,...
[ "You'll probably want to use the datetime moduel python ships with.\nimport time\nfrom datetime import date\n\ntoday = date.today()\n\nday = today.day\nmonth = today.month\nyear = today.year\n\nThat in combination of the time moduel has some great built in functions for converting times from one to the other.\nThe ...
[ 1 ]
[]
[]
[ "api", "parameters", "python", "schedule", "time" ]
stackoverflow_0074364009_api_parameters_python_schedule_time.txt
Q: Using NEOS as a Pyomo solver I have recently started in doing some OR, and have been trying to use Pyomo and NEOS to do some optimation problems. I have been following along with one of the UT Austin Pyomo lectures, and when my GLPT was being difficult to be installed, I moved on to NEOS. I am having some difficul...
Using NEOS as a Pyomo solver
I have recently started in doing some OR, and have been trying to use Pyomo and NEOS to do some optimation problems. I have been following along with one of the UT Austin Pyomo lectures, and when my GLPT was being difficult to be installed, I moved on to NEOS. I am having some difficulty in now receiving a solved answe...
[ "This is a \"problem\" with the design of the current results object. For historical reasons, that field reports the number of solutions contained in the results object and is not the number of solutions generated by the solver. By default, Pyomo solvers directly load the solution returned by the solver into the ...
[ 2, 0 ]
[]
[]
[ "neos_server", "pyomo", "python" ]
stackoverflow_0068384117_neos_server_pyomo_python.txt
Q: Efficient way to use regex compile (Python) with a list of 10.000 strings I got a list which contains approx. 10.000 strings and I want to use a regex pattern to detect this in this list. When I use re.compile it takes a lot of time to only apply one regex pattern. Is there any way with Python to make it faster? H...
Efficient way to use regex compile (Python) with a list of 10.000 strings
I got a list which contains approx. 10.000 strings and I want to use a regex pattern to detect this in this list. When I use re.compile it takes a lot of time to only apply one regex pattern. Is there any way with Python to make it faster? Here my code: import re list_of_strings = ["I like to eat meat", "I don't like...
[ "re.compile is designed to be used only once.\nCompile once then use the compiled regex that is more efficient.\nimport re\n\npattern = re.compile(r\"I like to eat (.*?)\")\nlist_of_strings = [\"I like to eat meat\", \"I don't like to eat meat\", \"I like to eat fish\", \"I don't like to eat fish\"]\n\noutcome = [x...
[ 1, 0 ]
[]
[]
[ "list", "pyspark", "python", "pytorch", "regex" ]
stackoverflow_0074364266_list_pyspark_python_pytorch_regex.txt
Q: adding a same header to multiple columns in python I have a dataframe which shape is (12,75000). I made this dataframe by concatinating 3 separate np.arrays which has no headers. Now, I want to deducate a specific header to each np.array that I concatenated to make my dataframe like the image that I attached. I a...
adding a same header to multiple columns in python
I have a dataframe which shape is (12,75000). I made this dataframe by concatinating 3 separate np.arrays which has no headers. Now, I want to deducate a specific header to each np.array that I concatenated to make my dataframe like the image that I attached. I appreciate any help or comments in advance, Thank you. I ...
[ "You can use a multi-index dataframe. Something like this\nimport pandas as pd\nimport numpy as np\n\nar1 = np.random.randint(5, size =(4, 3)) # create a numpy array of 4 rows and 3 columns with random integers in range 0 to 5\nar2 = np.random.randint(5, size =(4, 3)) # create another array\nar3 = np.random.randint...
[ 0 ]
[]
[]
[ "dataframe", "header", "numpy_ndarray", "pandas", "python" ]
stackoverflow_0074364220_dataframe_header_numpy_ndarray_pandas_python.txt
Q: writing to a list which name comes from an argument passed through function call I have a function that asks for the positions of a chess piece on a board. The function is findPiece(piece) so I can call this function like this: findPiece(whitePawn) The function finds out where all the white pawns are and returns...
writing to a list which name comes from an argument passed through function call
I have a function that asks for the positions of a chess piece on a board. The function is findPiece(piece) so I can call this function like this: findPiece(whitePawn) The function finds out where all the white pawns are and returns this. Now I want to write the positions to the global list whitePawnPositions[] If ...
[ "whitePawnPositions[] is a list. To add elements to lists there is the .append() function. How to deal with lists you can read here again.\nBack to your question. piecePositions is a string and not a list and does not have the .append() function. In python there are several possibilities to concatenate a string. Mo...
[ 0 ]
[]
[]
[ "append", "list", "python", "string" ]
stackoverflow_0074363590_append_list_python_string.txt
Q: SQLAlchemy: how to obtain all distinct values from Array field? I have the following model of a blog post: title = db.Column(db.String()) content = db.Column(db.String()) tags = db.Column(ARRAY(db.String)) Tags field can be an empty list. Now I want to select all distinct tags from the database entries with max p...
SQLAlchemy: how to obtain all distinct values from Array field?
I have the following model of a blog post: title = db.Column(db.String()) content = db.Column(db.String()) tags = db.Column(ARRAY(db.String)) Tags field can be an empty list. Now I want to select all distinct tags from the database entries with max performance - excluding empty arrays. So, say I have 3 records with th...
[ "The distinct() method should still work fine with array columns.\nfrom sqlalchemy import func\n\nunique_vals = BlogPost.query(func.unnest(BlogPost.tags)).distinct().all()\n\nhttps://docs.sqlalchemy.org/en/13/orm/query.html?highlight=distinct#sqlalchemy.orm.query.Query.distinct\nThis would be identical to running a...
[ 0, 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0057732216_flask_flask_sqlalchemy_postgresql_python_sqlalchemy.txt
Q: Video Recording is too fast in opencv python I'm capturing my screen using OpenCV on windows. It works fine but when I try to play my captured video it plays too fast. i.e. I capture from video for 60 seconds but when I play it OpenCV recorded longer and sped up to fit the additional times content into 60 seconds ...
Video Recording is too fast in opencv python
I'm capturing my screen using OpenCV on windows. It works fine but when I try to play my captured video it plays too fast. i.e. I capture from video for 60 seconds but when I play it OpenCV recorded longer and sped up to fit the additional times content into 60 seconds of video i.e. sped up import cv2 import numpy as n...
[ "you need to wait in-between taking screen shots. There may be a more ideal solution, but this would probably suffice:\nfrom time import time, sleep\nrecord_time = 10 #don't overwrite the function we just imported\nstart_time = time()\nfor i in range(int(record_time * fps)):\n # wait for next frame time\n nex...
[ 0 ]
[]
[]
[ "audio", "opencv", "pyaudio", "python", "recording" ]
stackoverflow_0074357306_audio_opencv_pyaudio_python_recording.txt
Q: Error: class uri 'eventlet' invalid or not found I've been running a dockerized flask application that uses Celery to run tasks. To run the app I'm using gunicorn with eventlet and It's been working fine using alpine linux distribution. However I had to move to ubuntu due to some issues with sklearn and other libr...
Error: class uri 'eventlet' invalid or not found
I've been running a dockerized flask application that uses Celery to run tasks. To run the app I'm using gunicorn with eventlet and It's been working fine using alpine linux distribution. However I had to move to ubuntu due to some issues with sklearn and other libraries, and now I'm having problems to run my app. Firs...
[ "I had the same issue, and I found that it is caused by some updates made by eventlet they removed eventlet.wsgi.ALREADY_HANDLED but gunicorn is still using it. So , you better downgrade the eventlet version.\npip install gunicorn==20.1.0 eventlet==0.30.2\nHere is a reference https://github.com/eventlet/eventlet/...
[ 21, 1, 0 ]
[]
[]
[ "celery", "docker", "flask_socketio", "gunicorn", "python" ]
stackoverflow_0058589138_celery_docker_flask_socketio_gunicorn_python.txt
Q: How to override the pip command to Python3.x instead of Python2.7? I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command pip2 to use Python2 and when I use the command pip3 Python3.x will be used. The problem is that the default of pip is set to Python2.7 and I wan...
How to override the pip command to Python3.x instead of Python2.7?
I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command pip2 to use Python2 and when I use the command pip3 Python3.x will be used. The problem is that the default of pip is set to Python2.7 and I want it to be Python3.x. How can I change that? edit: No, I am not running...
[ "Run this:\npip3 install --upgrade --force pip\n\nor even more explicit:\npython3 -m pip install --upgrade --force pip\n\nThis will install pip for Python 3 and make Python 3 version of pip default.\nValidate with:\npip -V\n\n", "I always just run it via Python itself, this way:\npython3 -m pip install some_modul...
[ 73, 46, 10, 6, 1, 1, 0, 0 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0038938205_pip_python_python_3.x.txt
Q: Sort the odd numbers in the list How can I sort ascending the odd numbers in a list of integers, but leaving the even numbers in their original places? Example: sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] My code: def sort_array(source_array): odd_numbers = [n for n in source_array if n%2!=0] ...
Sort the odd numbers in the list
How can I sort ascending the odd numbers in a list of integers, but leaving the even numbers in their original places? Example: sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] My code: def sort_array(source_array): odd_numbers = [n for n in source_array if n%2!=0] odd_numbers = sorted(odd_numbers) H...
[ "Looks like you're almost there - you can make your sorted odd numbers an iterable and re-build your source list with either the original even number or the next sorted odd number, eg:\n>>> data = [5, 3, 2, 8, 1, 4]\n>>> odds = iter(sorted(el for el in data if el % 2))\n>>> [next(odds) if el % 2 else el for el in d...
[ 14, 4, 1, 0, 0, 0 ]
[ "You can get the result you want by iterating over the length of the array and performing a sort only on the items that are odd, which can be determined by modulus division. This algorithm utilizes Bubblesort, which is inefficient, but can operate as a working example of the principal.\npublic static int[] SortArra...
[ -4 ]
[ "python" ]
stackoverflow_0044461172_python.txt
Q: Python Excel Worksheet Conditional Formatting Based Off Of Another Sheet I have an Excel Workbook with two sheets: Sheet 1 and Sheet 2. I want to color format the cells in column 'B' within Sheet1 based off of column Sheet2 'D'. worksheet.conditional_format("'Sheet1'!B2:C999", {"type...
Python Excel Worksheet Conditional Formatting Based Off Of Another Sheet
I have an Excel Workbook with two sheets: Sheet 1 and Sheet 2. I want to color format the cells in column 'B' within Sheet1 based off of column Sheet2 'D'. worksheet.conditional_format("'Sheet1'!B2:C999", {"type": "formula", "criteria": '=Sheet2!($D2=1)', ...
[ "After banging my head against the wall for hours, I found the solution in only a few minutes. Here is the solution:\nworksheet.conditional_format('B2:C999', {'type': 'formula',\n 'criteria': '=Sheet2!$D2=1', \n 'format': format1})\n\n" ]
[ 0 ]
[]
[]
[ "conditional_formatting", "excel", "python" ]
stackoverflow_0074363727_conditional_formatting_excel_python.txt
Q: Python, how do I retrieve the data in my list? this confuses me crsr.execute("SELECT * FROM tblmob") res = crsr.fetchall() for i in res: nopol = i [2] print(nopol) and the ouput is row formating like this without the bullet B 9020 BCS B 9243 BQB B 9244 BQB B 9307 KXR B 9552 UXT B 9730 BCK ...
Python, how do I retrieve the data in my list? this confuses me
crsr.execute("SELECT * FROM tblmob") res = crsr.fetchall() for i in res: nopol = i [2] print(nopol) and the ouput is row formating like this without the bullet B 9020 BCS B 9243 BQB B 9244 BQB B 9307 KXR B 9552 UXT B 9730 BCK B 9733 CXS B 9746 WRU B 9782 FXR how can i get only one data from my...
[ "I don't know how your res list look like, but if it is a simple list like this one:\nres = ['B 9020 BCS', 'B 9243 BQB', 'B 9244 BQB', 'B 9307 KXR', 'B 9552 UXT', 'B 9730 BCK', 'B 9733 CXS' ,'B 9746 WRU', 'B 9782 FXR', 'B 9865 NCG']\n\nyou can get the single data by its index, like:\nnopol = res[4]\n\nthis will ret...
[ 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0074364301_mysql_python.txt
Q: When get tensor from multiprocesses by torch.multiprocessing.Queue(), RuntimeError: Couldn't open shared event When the program runs to queue.get(), RuntimeError: Couldn't open shared event: <0000023F7034DF52>, error code: <2>. While, if used numpy instead of tensor, the program works. How to get torch.tensor from...
When get tensor from multiprocesses by torch.multiprocessing.Queue(), RuntimeError: Couldn't open shared event
When the program runs to queue.get(), RuntimeError: Couldn't open shared event: <0000023F7034DF52>, error code: <2>. While, if used numpy instead of tensor, the program works. How to get torch.tensor from multiprocesses? import torch import torch.multiprocessing as mp import numpy as np def solve(queue): for i in ...
[ "Torch tensors are passed as a file descriptor through a socket. Your error occurs when the producer process is finished before the consumer reads the tensor from the queue. One solution is to wait at the end of the consumer process until the tensors are read from the queue, which has been proposed here: https://di...
[ 0 ]
[]
[]
[ "multiprocessing", "python", "pytorch", "queue", "tensor" ]
stackoverflow_0073590545_multiprocessing_python_pytorch_queue_tensor.txt
Q: How to programatically check/uncheck all checkboxes? I have created a list of checkboxes in the loop (for every row in the dataframe): options = [] for idx, row in df.iterrows(): option = st.sidebar.checkbox(label=f"{row['title']} ({row['option']})", key=idx) options.append([row['title'], option]) By defa...
How to programatically check/uncheck all checkboxes?
I have created a list of checkboxes in the loop (for every row in the dataframe): options = [] for idx, row in df.iterrows(): option = st.sidebar.checkbox(label=f"{row['title']} ({row['option']})", key=idx) options.append([row['title'], option]) By default, all the checkboxes are unchecked which is as desired....
[ "Use a combination of callback and session_states.\nimport streamlit as st\n\n\ndef sel_callback():\n st.session_state.a = st.session_state.sel\n st.session_state.b = st.session_state.sel\n\nst.write('### Control')\nst.checkbox('select all', key='sel', on_change=sel_callback)\n\nst.write('### main')\nst.check...
[ 1 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074247312_python_streamlit.txt
Q: Dash Choosing an ID and then Make Plot with Slider I have a dataset which is similar to below one. Please note that there are multiple values for an ID. import pandas as pd import numpy as np import random df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='h'), ...
Dash Choosing an ID and then Make Plot with Slider
I have a dataset which is similar to below one. Please note that there are multiple values for an ID. import pandas as pd import numpy as np import random df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='h'), 'SBP':[random.uniform(110, 160) for n in range(120)],...
[ "You can look at the corrected version below, I fixed multiple issues.\napp = Dash(__name__)\n\n\napp.layout = html.Div([\n html.H4('Interactive Scatter Plot with ABPM dataset'),\n dcc.Graph(id=\"scatter-plot\"),\n html.P(\"Filter by time interval:\"),\n dcc.Dropdown(df.ID.unique(), id='pandas-dropdown-...
[ 1 ]
[]
[]
[ "plotly", "plotly_dash", "python" ]
stackoverflow_0074362661_plotly_plotly_dash_python.txt
Q: Speed up query on 100,000,000 rows I have 2 scripts. 1 to add data to SQLite database and one to query using 3 different queries. The database will have 100 million rows and 2 columns (average 50 characters per record). Problem 1: Once I get to around 10 million each CSV file I add takes hours to import. Problem 2...
Speed up query on 100,000,000 rows
I have 2 scripts. 1 to add data to SQLite database and one to query using 3 different queries. The database will have 100 million rows and 2 columns (average 50 characters per record). Problem 1: Once I get to around 10 million each CSV file I add takes hours to import. Problem 2: When I run the query script it takes i...
[]
[]
[ "It looks like you use a database but don't benefit from the features it provides.\n\nInserting a huge number of records one by one is inefficient.\nDatabases always provide import and dump features.\nHere you can use import and provide a flat file : text or csv for example.\n\nA database is designed to store and s...
[ -1 ]
[ "python", "sqlite" ]
stackoverflow_0074364077_python_sqlite.txt
Q: Dataframe sum on column with condition I edited my question to make a simpler example. I have this DataFrame: D N 01/06/2021 2 01/06/2021 4 01/06/2021 0 02/06/2021 1 02/06/2021 0 03/06/2021 1 03/06/2021 5 03/06/2021 1 04/06/2021 2 05/06/2021 0 05/06/2021 2 05/06/2021 4 08/06/2021 7 09/06/2021 3 09/...
Dataframe sum on column with condition
I edited my question to make a simpler example. I have this DataFrame: D N 01/06/2021 2 01/06/2021 4 01/06/2021 0 02/06/2021 1 02/06/2021 0 03/06/2021 1 03/06/2021 5 03/06/2021 1 04/06/2021 2 05/06/2021 0 05/06/2021 2 05/06/2021 4 08/06/2021 7 09/06/2021 3 09/06/2021 9 How can I ...
[ "Column 'D' is converted using pd.to_datetime. The dataframe is then grouped by column 'D' and the sums of column 'N' are collected. The index is reset and the amount in a three-day window is calculated.\nimport pandas as pd\n\ndf = pd.read_csv('df.csv', header=0)\n\ndf['D'] = pd.to_datetime(df['D'], errors='raise'...
[ 0 ]
[]
[]
[ "dataframe", "python", "sum" ]
stackoverflow_0074347249_dataframe_python_sum.txt
Q: Sending data from flask to html without form I've seen similar questions, but most dealing with input forms and GET/POST methods. I'm still learning, and don't know if I need those or not, but looking to pass a created dataset in my Flask main.py file to a later html. example main.py: from flask import Flask,rende...
Sending data from flask to html without form
I've seen similar questions, but most dealing with input forms and GET/POST methods. I'm still learning, and don't know if I need those or not, but looking to pass a created dataset in my Flask main.py file to a later html. example main.py: from flask import Flask,render_template app = Flask(__name__) #some other site...
[ "If I understand your question correctly, you want to display the golfer rankings within an HTML table at the time of the request.\nSo you get the data from the website and extract the table with the statistics. You can then rename columns and extract the ones you want to display. Now you pass the entire resulting ...
[ 1 ]
[]
[]
[ "flask", "html", "python" ]
stackoverflow_0074363381_flask_html_python.txt
Q: How to loop string inputs that break/end only when "#" is input on a single line? Basically, I want to create a loop that will continue getting string inputs from users until the user types only a "#" on a line. I am coming from C++ so I am a bit lost in this Python project I have in mind. A: try this: last_inpu...
How to loop string inputs that break/end only when "#" is input on a single line?
Basically, I want to create a loop that will continue getting string inputs from users until the user types only a "#" on a line. I am coming from C++ so I am a bit lost in this Python project I have in mind.
[ "try this:\nlast_input = ''\nwhile (last_input != '#'):\n last_input = input()\n\nYou'll probably want to do something else with the data, but this will keep asking until the user provides just #\nAnd if you want to save all the inputs:\nlast_input = ''\nall_input = [] # list to catch user input\nwhile (last_inpu...
[ 1 ]
[ "while True:\n s = input()\n if s == \"#\":\n break\n\n" ]
[ -1 ]
[ "infinite", "input", "loops", "python", "string" ]
stackoverflow_0074364719_infinite_input_loops_python_string.txt
Q: Python LDAP3 - how to get results entries into a Pandas dataframe I am trying to get results from the Python3 (3.9) module LDAP3 into a Pandas DataFrame, so I can manipulate with the content better. I can perform a simple: for entry in conn.entries: print(str(entry.enter_raw_attributes)) Here are example printe...
Python LDAP3 - how to get results entries into a Pandas dataframe
I am trying to get results from the Python3 (3.9) module LDAP3 into a Pandas DataFrame, so I can manipulate with the content better. I can perform a simple: for entry in conn.entries: print(str(entry.enter_raw_attributes)) Here are example printed results: {'sAMAccountName': [b'username1'], 'mail': [b'Jane.Doe@organ...
[ "b' indicates it is a byte-string and is the result of requesting the enter_raw_attributes.\nYou may want to call the attributes you are looking for directly, or convert it to another data type that can be digested.\nHere's an example in the documentation of different ways to work with the returned data:\n>>> # get...
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074364677_dataframe_dictionary_pandas_python.txt
Q: How can I send floating point numbers from a C# application to a python process? I want to run a Python script from C#. This has been working fine, following the approach shown here I am retrieving the values using argv inside the python script The issue arises, when I try to pass float values to my python applica...
How can I send floating point numbers from a C# application to a python process?
I want to run a Python script from C#. This has been working fine, following the approach shown here I am retrieving the values using argv inside the python script The issue arises, when I try to pass float values to my python application. I'm not sure whether argv can't separate the floating point number properly or w...
[ "The reason why this happens appears to be due to an automatic conversion of the floating point number in US format to the German format (My system language is German). This is a common issue in european countries.\nIn order to circumvent this I have used the following operation on these values:\nusing System.Globa...
[ 0 ]
[]
[]
[ "argv", "c#", "interprocess", "python" ]
stackoverflow_0074364016_argv_c#_interprocess_python.txt
Q: Django rest api create email login along with password I've created the employee management system using django rest api. I've created the models, views and serializers like shown below. What i need is I've created employee details like his personal details as a register view, but when he login i want to use email...
Django rest api create email login along with password
I've created the employee management system using django rest api. I've created the models, views and serializers like shown below. What i need is I've created employee details like his personal details as a register view, but when he login i want to use email and password field as a field to sign with jwt token. How t...
[ "Can you tell me why one or more of the pre-existing authentication mechanisms as described here wouldn't work?\nhttps://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#tutorial-4-authentication-permissions\nDjango rest framework supports many out of the box authentication mechanisms, and y...
[ 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "django_rest_framework_jwt", "python" ]
stackoverflow_0074364196_django_django_models_django_rest_framework_django_rest_framework_jwt_python.txt
Q: Python Counter Solution for Anagrams much Slower than Sorting Solution - why? I made two versions of an algorithm to find anagrams of a given word within a language reference. I would have expected the Counter version to be faster, as Counter is hash table based (O(1) access), whereas sorting is generally O(n log ...
Python Counter Solution for Anagrams much Slower than Sorting Solution - why?
I made two versions of an algorithm to find anagrams of a given word within a language reference. I would have expected the Counter version to be faster, as Counter is hash table based (O(1) access), whereas sorting is generally O(n log n), as I understand. Yet the sorting version seems to be about 60x faster. Can anyo...
[ "Build a dictionary where the keys are sorted words and the associated values are lists of words that can be made up of the key.\nThe lookup in the dictionary will be optimum due to the nature of hashed keys.\nimport requests\nfrom collections import defaultdict\nfrom functools import cache\n\nLANGUAGE_REFERENCE_UR...
[ 0 ]
[]
[]
[ "algorithm", "hashtable", "performance", "python", "sorting" ]
stackoverflow_0074362101_algorithm_hashtable_performance_python_sorting.txt
Q: RuntimeError: working outside of application context app.py from flask import Flask, render_template, request,jsonify,json,g import mysql.connector app = Flask(__name__) **class TestMySQL():** @app.before_request def before_request(): try: g.db = mysql.connector.connect(user='root', password='root'...
RuntimeError: working outside of application context
app.py from flask import Flask, render_template, request,jsonify,json,g import mysql.connector app = Flask(__name__) **class TestMySQL():** @app.before_request def before_request(): try: g.db = mysql.connector.connect(user='root', password='root', database='mysql') except mysql.connector.errors.Erro...
[ "Flask has an Application Context, and it seems like you'll need to do something like:\ndef test_connection(self):\n with app.app_context():\n #test code\n\nYou can probably also shove the app.app_context() call into a test setup method as well. Hope this helps.\n", "I followed the answer from @brenns1...
[ 110, 5, 4, 0 ]
[]
[]
[ "flask", "flask_restful", "mysql", "python", "werkzeug" ]
stackoverflow_0031444036_flask_flask_restful_mysql_python_werkzeug.txt
Q: Mock an attribute to intercept a call to its own method inside a class method How can I ensure self.a.set_name is called with the right parameters and values? I would like to patch the object instead of each method individual because there're 15 of them. Here is one of things I've tried which fails with AssertionE...
Mock an attribute to intercept a call to its own method inside a class method
How can I ensure self.a.set_name is called with the right parameters and values? I would like to patch the object instead of each method individual because there're 15 of them. Here is one of things I've tried which fails with AssertionError: Expected 'set_name' to be called once. Called 0 times.: # src/resources.py fr...
[ "You are not patching the correct object. In MyClassB.get_a, you first create a brand new ClassA object and then call set_name on that object. That means that you have to mock the set_name method on ClassA:\nclass TestClassB(TestCase):\n def test_get_a(self):\n b = MyClassB()\n with mock.patch.obje...
[ 0 ]
[]
[]
[ "pytest", "python", "python_unittest" ]
stackoverflow_0074364623_pytest_python_python_unittest.txt
Q: How should be storage_path in simple-youtube-api? I want to make a program that will be uploaded automate video on youtube. I found a python library on the internet: simple-youtube-api But I don't understand how to send authentication information (login, password). I found storage_path in the function method, but...
How should be storage_path in simple-youtube-api?
I want to make a program that will be uploaded automate video on youtube. I found a python library on the internet: simple-youtube-api But I don't understand how to send authentication information (login, password). I found storage_path in the function method, but I don't understand how to put the correct information ...
[ "create an empty file and put its name as a value in storage_path, it will populated automatically after your first run with the appropriate token.\n" ]
[ 0 ]
[]
[]
[ "python", "youtube", "youtube_api", "youtube_data_api" ]
stackoverflow_0067852556_python_youtube_youtube_api_youtube_data_api.txt
Q: I am making a bot in nextcord and I need to figure out how to disable a view I am trying to make an economy bot and one of the games is RPS. I am trying to figure out how to disable a view after a button is pressed. My code: import nextcord import random client=nextcord.Client(intents=nextcord.Intents....
I am making a bot in nextcord and I need to figure out how to disable a view
I am trying to make an economy bot and one of the games is RPS. I am trying to figure out how to disable a view after a button is pressed. My code: import nextcord import random client=nextcord.Client(intents=nextcord.Intents.all()) def checkwin(useroption): optionIndex=random.randint(1,3) ...
[ "To remove all the buttons, you can edit the message with view=None.\nawait interaction.edit(view=None)\n\nTo disable all buttons, you can iterate over the children, setting disabled to True, then editing the message with the updated view.\nfor child in self.children:\n child.disabled = True\nawait interaction.e...
[ 1 ]
[]
[]
[ "nextcord", "python" ]
stackoverflow_0074351525_nextcord_python.txt
Q: Colours in Windows cmd with Python I am trying to get colours to work in Python using windows cmd but it is not working. I've tried a few packages, but they all result in something similar. At the moment, my code looks like this: from colors import * print(color('some text', fg='rgb(255, 0, 0)')) However, this j...
Colours in Windows cmd with Python
I am trying to get colours to work in Python using windows cmd but it is not working. I've tried a few packages, but they all result in something similar. At the moment, my code looks like this: from colors import * print(color('some text', fg='rgb(255, 0, 0)')) However, this just prints [38;2;255;0;0msome text[0m in...
[ "Re-enable ANSI console color for Windows 10.16257 and later: run\nreg add HKCU\\Console /v VirtualTerminalLevel /t REG_DWORD /d 1\n\nRestart Windows command prompt (cmd.exe).\n", "You have to use os.system('') before print(color('some text', fg='rgb(255, 0, 0)')) Remember to import os* module using*import os.\nL...
[ 1, 0 ]
[]
[]
[ "cmd", "colors", "python" ]
stackoverflow_0053619319_cmd_colors_python.txt
Q: Selenium Web driver ( driver.find_element(By.XPATH, '')) IS NOT WORKING Python https://www.espncricinfo.com/player/aamer-jamal-793441 This is the URL and here i am trying to access Full Name "Aamer Jamal". with the help of selenium web driver. But I dont know why it gives NoSuchElementException `the code is writt...
Selenium Web driver ( driver.find_element(By.XPATH, '')) IS NOT WORKING Python
https://www.espncricinfo.com/player/aamer-jamal-793441 This is the URL and here i am trying to access Full Name "Aamer Jamal". with the help of selenium web driver. But I dont know why it gives NoSuchElementException `the code is written below: from selenium import webdriver from selenium.webdriver.common.by import By...
[ "You have to use WebDriverWait expected_conditions explicit waits, not a long hardcoded pauses. You also have to learn how to create correct locators. Long absolute XPaths and CSS Selectors are extremely breakable. The following code works:\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChain...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping", "xpath" ]
stackoverflow_0074364375_python_selenium_selenium_webdriver_web_scraping_xpath.txt
Q: ImportError No module named pyaudio I am writing a program in Python on RaspberryPi, But I am getting an error ImportError No module named pyaudio After that I tried git clone http://people.csail.mit.edu/hubert/git/pyaudio.git but again get another fatal: destination path 'pyaudio' already exists and is not an ...
ImportError No module named pyaudio
I am writing a program in Python on RaspberryPi, But I am getting an error ImportError No module named pyaudio After that I tried git clone http://people.csail.mit.edu/hubert/git/pyaudio.git but again get another fatal: destination path 'pyaudio' already exists and is not an empty directory. Can you please guide me...
[ "Remove the directory PyAudio which already presen in /home/pi and then try these steps\nsudo apt-get install git\n\nsudo git clone http://people.csail.mit.edu/hubert/git/pyaudio.git\n\nsudo apt-get install libportaudio0 libportaudio2 libportaudiocpp0 portaudio19-dev\n\nsudo apt-get install python-dev\n\ncd pyaudio...
[ 17, 10, 8, 6, 2, 0, 0 ]
[ "pip install pyaudio\n\nthis worked for me,hope it helps you too.\n" ]
[ -2 ]
[ "audio_recording", "importerror", "pyaudio", "python", "raspberry_pi" ]
stackoverflow_0028140972_audio_recording_importerror_pyaudio_python_raspberry_pi.txt
Q: nltk english corpus and python count Why when I import from nltk.corpus import words and try to count specific strings I get some duplicates? For example the word skirt gets two hits with words.words().count("skirt") (btw, words.words().count("Skirt") has 0 hits). When getting the index of skirt and slice the list...
nltk english corpus and python count
Why when I import from nltk.corpus import words and try to count specific strings I get some duplicates? For example the word skirt gets two hits with words.words().count("skirt") (btw, words.words().count("Skirt") has 0 hits). When getting the index of skirt and slice the list I don't see any duplicate entry. I had so...
[ "type(words.words() actually returns <class 'list'>, not dict, so it's perfectly possible to have duplicates. If you sort the list using sorted(), indices 187162 and 187163 are both \"skirt\".\n>>> words_sorted = sorted(words.words())\n>>> words_sorted.count(\"skirt\")\n2\n>>> words_sorted.index(\"skirt\")\n187162\...
[ 1 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0074364738_nltk_python.txt
Q: How to search/append a list within a dictionary Say I have a dictionary comprised of integer keys, and a list of integers corresponding to each key. myDict = {0:[1,2,3,4], 1:[1,2,3], 2:[3,4,5]} How do I search the list in key 1 for the integer 4, and if it's not in the list append it so that 1:[1,2,3,4] A: Try t...
How to search/append a list within a dictionary
Say I have a dictionary comprised of integer keys, and a list of integers corresponding to each key. myDict = {0:[1,2,3,4], 1:[1,2,3], 2:[3,4,5]} How do I search the list in key 1 for the integer 4, and if it's not in the list append it so that 1:[1,2,3,4]
[ "Try this:\nmyDict = {0:[1,2,3,4], 1:[1,2,3], 2:[3,4,5]}\n\n# Only if k exists in 'dict'. We append value for that specific key\ndef search_append(d, k, v):\n if (k in d) and (not v in d[k]):\n d[k].append(v)\n\nsearch_append(myDict, 1, 4)\nprint(myDict)\n{0: [1, 2, 3, 4], 1: [1, 2, 3, 4], 2: [3, 4, 5]}\n...
[ 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074364890_dictionary_list_python.txt
Q: How can I restart the game by pressing "r"? My plans are to restart the game / reset the character to the middle of the map. import keyboard as kb from ursina import * from ursina.prefabs.first_person_controller import FirstPersonController app = Ursina() window.fps_counter.enabled = False player = FirstPersonCon...
How can I restart the game by pressing "r"?
My plans are to restart the game / reset the character to the middle of the map. import keyboard as kb from ursina import * from ursina.prefabs.first_person_controller import FirstPersonController app = Ursina() window.fps_counter.enabled = False player = FirstPersonController() Sky() boxes = [] def random_color(): ...
[ "What do you mean with reset? Reset the hole game or just the player position?\nTo reset player position you can do something like this:\nfrom ursina import *\n\napp = Ursina()\n\n# Change this to whatever your player is. In your case First person controller \nplayer = Entity(model = 'cube')\n\nplayer_reset_positio...
[ 0 ]
[]
[]
[ "python", "ursina" ]
stackoverflow_0074327704_python_ursina.txt
Q: Constructing Pandas DataFrame from Nested Dictionaries I have a nested dictionary with three layers, the bottom layer being a mixture of dictionaries and values and want to convert it into a dataframe with keys from the last layer as column names and keys from the first layer as ids. dict = {"id1": {"att_1": 1, ...
Constructing Pandas DataFrame from Nested Dictionaries
I have a nested dictionary with three layers, the bottom layer being a mixture of dictionaries and values and want to convert it into a dataframe with keys from the last layer as column names and keys from the first layer as ids. dict = {"id1": {"att_1": 1, "att_2": {"att2_1": "value1", ...
[ "you can define a function to traverse and find all attributes by dfs, as folow:\nfrom collections import defaultdict\n\ndef convert(node):\n t = defaultdict(list)\n def dfs(node):\n for k, v in node.items():\n if isinstance(v, dict):\n dfs(v)\n else...
[ 0, 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074364188_dictionary_pandas_python.txt
Q: Split 1 row into multiple rows of hourly data based on datetime column keeping one column values as sliding window in pandas I have a dataset that shows Actual vs Predicted values Start Time End Time Actual Predicted 4/1/2022 20:00 4/2/2022 22:00 0.749123 [[0.41], [0.34]] 4/1/2022 21:00 4/2/2022 23:00 0.770175 ...
Split 1 row into multiple rows of hourly data based on datetime column keeping one column values as sliding window in pandas
I have a dataset that shows Actual vs Predicted values Start Time End Time Actual Predicted 4/1/2022 20:00 4/2/2022 22:00 0.749123 [[0.41], [0.34]] 4/1/2022 21:00 4/2/2022 23:00 0.770175 [[0.32], [0.28]] I want to split this up into different hours such that one row only contains one hour of data and Actu...
[ "I'm not too sure what exactly you want the result to look like but the pandas .explode() method should definetly be helpful.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074364955_dataframe_list_pandas_python.txt
Q: how to fix 504 gateway timeout error in Gunicorn gunicorn app:app -b :8080 --timeout 120 --workers=3 --threads=3 --worker-connections=1000 I am new to devops and I am currently using this command to run my app on port 9=8080 but if I receive too many requests I am getting 504 gateway timeout error. I know workers...
how to fix 504 gateway timeout error in Gunicorn
gunicorn app:app -b :8080 --timeout 120 --workers=3 --threads=3 --worker-connections=1000 I am new to devops and I am currently using this command to run my app on port 9=8080 but if I receive too many requests I am getting 504 gateway timeout error. I know workers =3 means if three requests come simultaneously they w...
[ "There are a few ways to fix a 504 gateway timeout error in Gunicorn with Django. One way is to increase the number of workers. Another way is to increase the timeout value.\n" ]
[ 0 ]
[]
[]
[ "devops", "django", "flask", "gunicorn", "python" ]
stackoverflow_0074356609_devops_django_flask_gunicorn_python.txt
Q: How to lock a sheet on Excel using Openyxl and tkinter I am trying to protect an excel sheet with Openyxl in Python, I have tried in different ways but without success. The idea is to create a data entry so that the user can enter data and then verify it in excel without the possibility of modifying it. Only super...
How to lock a sheet on Excel using Openyxl and tkinter
I am trying to protect an excel sheet with Openyxl in Python, I have tried in different ways but without success. The idea is to create a data entry so that the user can enter data and then verify it in excel without the possibility of modifying it. Only supervisors can modify the information, so they must have the pas...
[ "I have solved it with the help document of Openpyxl. https://openpyxl.readthedocs.io/en/stable/protection.html At first I didn't understand it but then I understood how it works First you have to import the configuration \"from openpyxl.workbook.protection import WorkbookProtection\" then create a password for the...
[ 0 ]
[]
[]
[ "openpyxl", "python", "tkinter" ]
stackoverflow_0074362219_openpyxl_python_tkinter.txt
Q: A merge in pandas is returning only NaN values I'm trying to merge two dataframes: 'new_df' and 'df3'. new_df contains years and months, and df3 contains years, months and other columns. I've cast most of the columns as object, and tried to merge them both. The merge 'works' as doesn't return an error, but my fina...
A merge in pandas is returning only NaN values
I'm trying to merge two dataframes: 'new_df' and 'df3'. new_df contains years and months, and df3 contains years, months and other columns. I've cast most of the columns as object, and tried to merge them both. The merge 'works' as doesn't return an error, but my final datafram is all empty, only the year and month col...
[ "Your issue is with the data types for month and year in both columns - they're of type object which gets a bit weird during the join.\nHere's a great answer that goes into depth about converting types to numbers, but here's what the code might look like before joining:\n# convert column \"year\" and \"month\" of n...
[ 1 ]
[]
[]
[ "merge", "pandas", "python" ]
stackoverflow_0074364905_merge_pandas_python.txt
Q: Can an object have a `Callable` type hint without specifying input arguments and return value? The following code... import typing func:typing.Callable[[int, float], str] Annotates func as a callable accepting two inputs. The two inputs are an int and a float. It also indicates that the return value is a string. ...
Can an object have a `Callable` type hint without specifying input arguments and return value?
The following code... import typing func:typing.Callable[[int, float], str] Annotates func as a callable accepting two inputs. The two inputs are an int and a float. It also indicates that the return value is a string. Is it possible to type hint something as a callable without specifying input argument types or outpu...
[ "The typing module explicitly states you can use ... in place of the signature, thought the return type seems mandatory.\n\nIt is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis for the list of arguments in the type hint: Callable[..., Retur...
[ 3, 0 ]
[]
[]
[ "python", "python_3.x", "type_hinting" ]
stackoverflow_0058758994_python_python_3.x_type_hinting.txt
Q: With pandas, how to speed up iteration that requires using the previous rows calculated value? Here's the code in question: import pandas as pd df = pd.DataFrame( [ list(range(200)), list(range(200, 400)) ], index=['col_1', 'col_2'] ).transpose() col_1_index = df.columns.get_loc('col_...
With pandas, how to speed up iteration that requires using the previous rows calculated value?
Here's the code in question: import pandas as pd df = pd.DataFrame( [ list(range(200)), list(range(200, 400)) ], index=['col_1', 'col_2'] ).transpose() col_1_index = df.columns.get_loc('col_1') col_2_index = df.columns.get_loc('col_2') target_1 = 2 for i in range(2, len(df)): if ( ...
[ "Well itertuples or apply are not especially fast, see this answer. Your main problem is you access cells several times in the loop and assign value to a cell at each loop. One can be more efficient by just looping on values from col_1 and have a variable to keep the previous value calculated, append the result in ...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074362011_dataframe_pandas_python.txt
Q: How do i upload a folder containing metadata to pinata using a script in python-brownie? I've been trying for the past 24 hours but can't find a solution. This is the code: import os from pathlib import Path import requests PINATA_BASE_URL = "https://api.pinata.cloud/" endpoint = "pinning/pinFileToIPFS" # Change ...
How do i upload a folder containing metadata to pinata using a script in python-brownie?
I've been trying for the past 24 hours but can't find a solution. This is the code: import os from pathlib import Path import requests PINATA_BASE_URL = "https://api.pinata.cloud/" endpoint = "pinning/pinFileToIPFS" # Change this filepath filepath = "C:/Users/acer/Desktop/Ciao" filename = os.listdir(filepath) print(fi...
[ "Nevermind...\nAfter some research i found the answer to my own question.\nHere is the code:\n# Tulli's script :-)\nfrom brownie import config\nimport requests, os, typing as tp\n\n\nPINATA_BASE_URL = \"https://api.pinata.cloud/\"\nendpoint = \"pinning/pinFileToIPFS\"\n# Here you could use os.getenv(\"VARIABLE_NAME...
[ 1 ]
[]
[]
[ "ipfs", "nft", "pinata", "python", "solidity" ]
stackoverflow_0074350228_ipfs_nft_pinata_python_solidity.txt
Q: How to invoke @Click (Python) but also pass in other parameters that aren't from Click? I have a python script that I am trying to invoke from bash/shell/cli. I have used a module called 'Click' before; however, I don't think it's possible to both pass in parameters using 'Click' AND passing in non-click parameter...
How to invoke @Click (Python) but also pass in other parameters that aren't from Click?
I have a python script that I am trying to invoke from bash/shell/cli. I have used a module called 'Click' before; however, I don't think it's possible to both pass in parameters using 'Click' AND passing in non-click parameters (such as a dictionary or list). Is there a way I can still pass in the non-click parameter...
[ "You don't run find_pr_id directly, try this:\nimport click\n\n@click.group()\n@click.pass_context\ndef cli(ctx):\n ctx.obj = json.loads(response.text)\n\n@cli.command()\n@click.pass_obj\n@click.argument(\"md5hash_passed\")\ndef find_pr_id (request, md5hash_passed):\n values = request[\"values\"]\n for ite...
[ 1 ]
[]
[]
[ "bash", "click", "command_line_interface", "python", "python_3.x" ]
stackoverflow_0074363882_bash_click_command_line_interface_python_python_3.x.txt
Q: Is building a Python module that depends on certain input structure (Pandas DataFrame) a bad practice? I'm working on developing a Python library related to financial modelling. The thing is, a lot of the functions I am creating depend on inputs that are being fed as tables (which I'm treating as Pandas DataFrames...
Is building a Python module that depends on certain input structure (Pandas DataFrame) a bad practice?
I'm working on developing a Python library related to financial modelling. The thing is, a lot of the functions I am creating depend on inputs that are being fed as tables (which I'm treating as Pandas DataFrames) to the functions I am creating. For example, what I do a lot is functions that take a Pandas DataFrame as ...
[ "It is not a bad practice to build a Python module that depends on a certain input structure, such as a Pandas DataFrame. However, it is important to be aware that this dependency can make your module less portable and more difficult to use in other contexts.\n", "Just as you are parameterizing the function on th...
[ 0, 0 ]
[]
[]
[ "dataframe", "devops", "module", "pandas", "python" ]
stackoverflow_0074361666_dataframe_devops_module_pandas_python.txt
Q: AttributeError: module 'tensorflow' has no attribute 'contrib' -- @tf.contrib.eager.defun I have problem connected tensorflow, In my script has decoder @tf.contrib.eager.defun. After running gave only error (AttributeError: module 'tensorflow' has no attribute 'contrib'). Please help me. My version tensor = 2.8.0 ...
AttributeError: module 'tensorflow' has no attribute 'contrib' -- @tf.contrib.eager.defun
I have problem connected tensorflow, In my script has decoder @tf.contrib.eager.defun. After running gave only error (AttributeError: module 'tensorflow' has no attribute 'contrib'). Please help me. My version tensor = 2.8.0 I change some tensorflow command but again this problem
[ "@tf.contrib.eager.defun appears to do some sort of pre-compilation of its decorated function to improve performance and is a TF 1.x method. I couldn't find where it was moved in TF 2.0, so I got it to work by either downgrading TF or removing the decorator (the latter slows down execution speed).\n" ]
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0071689201_python_tensorflow.txt
Q: I don't know how to traverse json from url I have a small code created in python and from an api I would like to go through all the code = url.json()["data"][0]["name"] But I do not know how to do it this is my little code: import requests swf = input("write: ") url = requests.get(f"https://apihabbo.com/api/furn...
I don't know how to traverse json from url
I have a small code created in python and from an api I would like to go through all the code = url.json()["data"][0]["name"] But I do not know how to do it this is my little code: import requests swf = input("write: ") url = requests.get(f"https://apihabbo.com/api/furnis?hotel=es&name={swf}") code = url.json()["...
[ "data['data'][0]['code'] is not a list. The list is data['data'], you need to loop over that.\nfor d in data['data']:\n print(d['code'])\n\n", "You have to iterate through the list of received data points.\nresponse = requests.get(\"https://apihabbo.com/api/furnis?hotel=es&name=Gorro%20con%20Pomp%C3%B3n\")\n\n...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074365103_python.txt
Q: pythonic way to check multiple boolean operators in an if statement I'm sure there is a way to simplify this if statement but I don't remember it and after googling for a while I couldn't find it. Any ideas? if user_input.lower() == 'yes' or user_input.lower() == 'y': print('Done!') A: You can check whether ...
pythonic way to check multiple boolean operators in an if statement
I'm sure there is a way to simplify this if statement but I don't remember it and after googling for a while I couldn't find it. Any ideas? if user_input.lower() == 'yes' or user_input.lower() == 'y': print('Done!')
[ "You can check whether a value is present in an iterable using the in keyword: user_input.lower() in (\"yes\", \"y\") will evaluate to True if the input is either 'yes' or 'y'.\nAlternatively, for more complex checks, you might consider any(), which takes an iterable of boolean statements and returns True if any of...
[ 2 ]
[]
[]
[ "boolean_operations", "if_statement", "python" ]
stackoverflow_0074365100_boolean_operations_if_statement_python.txt
Q: Issues with signal detending using smoothness priors on the last detended elements I tried to use smoothness priors method from neurokit2, to detrend my signal. https://neurokit2.readthedocs.io/en/master/_modules/neurokit2/signal/signal_detrend.html The method was based on the research paper Method by Tarvainen et...
Issues with signal detending using smoothness priors on the last detended elements
I tried to use smoothness priors method from neurokit2, to detrend my signal. https://neurokit2.readthedocs.io/en/master/_modules/neurokit2/signal/signal_detrend.html The method was based on the research paper Method by Tarvainen et al., 2002. (Tarvainen, M. P., Ranta-Aho, P. O., & Karjalainen, P. A. (2002). An advance...
[ "The data matrix B for creating the sparse matrix D_2 was created too short (N-2) and it didn't reach the two last columns in the sparse matrix upon creation.\nChange the line of code above to this one:\nB = np.dot(np.ones((N, 1)), np.array([[1, -2, 1]]))\n\n", "The paper says a second-order difference matrix (N...
[ 0, 0 ]
[]
[]
[ "algorithm", "numpy", "python", "scipy", "signal_processing" ]
stackoverflow_0069810723_algorithm_numpy_python_scipy_signal_processing.txt
Q: Python Foursquare API request error when trying to get venue details I try to make a request from the foursquare api. If I change the request URL it does no longer get me a result when I make a request with this line of code everything is fine: def venue_details(): detail_results = requests.get('https://api.fo...
Python Foursquare API request error when trying to get venue details
I try to make a request from the foursquare api. If I change the request URL it does no longer get me a result when I make a request with this line of code everything is fine: def venue_details(): detail_results = requests.get('https://api.foursquare.com/v2/venues/4e96cf73b8f7d8c690f48384/?client_id=[my client id]&...
[ "You can try it this way:\n def foresquare_location(lat, lon, radius):\n\n CLIENT_ID = 'XXXXXXXX' # your Foursquare ID\n CLIENT_SECRET = 'XXXXXXX' # your Foursquare Secret\n VERSION = '20180604'\n LIMIT = 100\n neighborhood_latitude = lat\n neighborhood_longitude = lon...
[ 1, 1 ]
[]
[]
[ "api", "foursquare", "python", "python_requests" ]
stackoverflow_0074287377_api_foursquare_python_python_requests.txt
Q: Checking if variable from a list exists in imported file I'm trying to build a simple iterative code that goes through a list of variables and checks it from a file. For example, it could have 2 variables foo1 and foo2, and I could do the following try: from file import foo1 except ImportError: foo1 = None tr...
Checking if variable from a list exists in imported file
I'm trying to build a simple iterative code that goes through a list of variables and checks it from a file. For example, it could have 2 variables foo1 and foo2, and I could do the following try: from file import foo1 except ImportError: foo1 = None try: from file import foo2 except ImportError: foo2 = None ...
[ "You can do something like this:\nimport file\n\nmy_list = ['foo1', 'foo2']\n\nfor listElem in my_list:\n if not (value := getattr(file, listElem, None)):\n print (\"Can't find\",listElem,\"in file\")\n globals()[listElem] = value\n\nglobals() is a dictionary that contains all top-level names. What we d...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074365105_python.txt
Q: Python Requests Client Side certificates Exception has occurred: ConnectionError I am trying to move a request that occurs in Postman successfully, to a Python request. I started with the Python code snippet that Postman provides: import requests url = "example.com/request" payload='auth_type=client_credentials'...
Python Requests Client Side certificates Exception has occurred: ConnectionError
I am trying to move a request that occurs in Postman successfully, to a Python request. I started with the Python code snippet that Postman provides: import requests url = "example.com/request" payload='auth_type=client_credentials' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization':...
[ "Well this is entirely embarrassing. I've now realised the error is not to do with the request not working, it's MacOS protecting me from my own code, by not allowing access to the certificate files on the Downloads folder.\n" ]
[ 0 ]
[]
[]
[ "python", "python_requests", "ssl" ]
stackoverflow_0074349344_python_python_requests_ssl.txt
Q: Is there a way to create one function line to sum 2 complex vectors without creating a collection that is not of fixed length Implements a function in one line and without creating a list or tuples or any other collection that is not of fixed length and without using numpy using the given def signature here what i...
Is there a way to create one function line to sum 2 complex vectors without creating a collection that is not of fixed length
Implements a function in one line and without creating a list or tuples or any other collection that is not of fixed length and without using numpy using the given def signature here what i did def inner_product_c(c1: Iterable[complex], c2: Iterable[complex]) -> complex: return list(map(lambda x, y: x*y.conjugate(...
[ "In Python3:\ndef inner_product_c(c1: Iterable[complex], c2: Iterable[complex]) -> complex: \n return sum(list([c1[n]*c2[n].conjugate() f...
[ 0 ]
[]
[]
[ "inner_product", "lambda", "python" ]
stackoverflow_0074364981_inner_product_lambda_python.txt
Q: How to convert a complex nested JSON file to CSV in Python? I'm trying to convert a complex JSON file to CSV using Python. { "commits": [ { "repository": "https://code.google.com/p/closure-compiler/", "sha1": "1f5edbcd2b5b09ec59151137e643d9ce75ef1055", "url": "https://code.google.com/p/closure-compile...
How to convert a complex nested JSON file to CSV in Python?
I'm trying to convert a complex JSON file to CSV using Python. { "commits": [ { "repository": "https://code.google.com/p/closure-compiler/", "sha1": "1f5edbcd2b5b09ec59151137e643d9ce75ef1055", "url": "https://code.google.com/p/closure-compiler/1f5edbcd2b5b09ec59151137e643d9ce75ef1055", "refactorings":...
[ "Using json_normalize()\nleft_df = pd.json_normalize(\n data=data[\"commits\"],\n meta=[\"repository\", \"sha1\", \"url\", [\"refactorings\", \"type\"], [\"refactorings\", \"description\"]],\n record_path=[\"refactorings\", \"leftSideLocations\"]\n)\nleft_df.columns = left_df.columns.str.split(\".\").str[-...
[ 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074363880_json_pandas_python.txt
Q: Function takes wrong variable python I need to change a variable each time the function is called. My function counts the number of time this function has been called: def score_chart(): num_of_charts=+ 1 return num_of_charts At the beginning num_of_charts equals 0. Then I call the function and re-save nu...
Function takes wrong variable python
I need to change a variable each time the function is called. My function counts the number of time this function has been called: def score_chart(): num_of_charts=+ 1 return num_of_charts At the beginning num_of_charts equals 0. Then I call the function and re-save num_of_charts to be equal 1. But if I call i...
[ "Use a parameter to get the old value.\ndef score_chart(num):\n return num + 1\n\nnum_of_charts = 0\nnum_of_charts = score_chart(num_of_charts)\nprint(num_of_charts)\nnum_of_charts = score_chart(num_of_charts)\nprint(num_of_charts)\n\n", "A general and useful way to count calls to any function is to define and...
[ 1, 1, 0, 0 ]
[]
[]
[ "function", "global", "python" ]
stackoverflow_0074364334_function_global_python.txt
Q: Smart algorithm for finding perfect numbers Is there an algorithm that is quicker than O(N^2) for finding perfect numbers from a sample 1:N? Or any general speed improvements to do less computation? I know we can remove odd numbers from the sample if we assume they are not perfect (unproven but we can assume it he...
Smart algorithm for finding perfect numbers
Is there an algorithm that is quicker than O(N^2) for finding perfect numbers from a sample 1:N? Or any general speed improvements to do less computation? I know we can remove odd numbers from the sample if we assume they are not perfect (unproven but we can assume it here regardless).
[ "Here is a way to do it (num is your number):\nif sum(i for i in range (1, num) if num % i == 0) == num:\n print(num, \"is a perfect number\")\nelse:\n print(num, \"is not a perfect number\")\n\nEDIT (credits: @cdlane)\nThere is a one-to-one correspondence between the Mersenne primes and the even perfect numb...
[ 2, 1 ]
[]
[]
[ "algorithm", "perfect_numbers", "python" ]
stackoverflow_0073501853_algorithm_perfect_numbers_python.txt
Q: Convert an integer into standard form I am trying to create a function to convert an integer into standard form (a * 10 ** n, where 1 ≤ a < 10). I have the following code, which raises countless errors and most likely does not work, but you can see my approach: # The power of ten is always the amount of digits min...
Convert an integer into standard form
I am trying to create a function to convert an integer into standard form (a * 10 ** n, where 1 ≤ a < 10). I have the following code, which raises countless errors and most likely does not work, but you can see my approach: # The power of ten is always the amount of digits minus one power = len(str(num)[:-2]) - 1 ...
[ "I would use a recursive function:\ndef sform(add, power=0):\n if 1 <= abs(add) < 10:\n return add, power\n elif 0 < abs(add) < 1:\n return sform(add*10, power-1)\n elif add == 0:\n return (0, 0)\n return sform(add/10, power+1)\n\ndef test_sform(num):\n add, power = sform(num)\n ...
[ 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074364789_math_python.txt
Q: making a word processer but i am having trouble keeping the words spliting up over serval lines i want to keep all words together and not have half on one line and half on the other. any help is great :) linewidth = int(input("input the length of a line")) string = input("input your string") count1 = 0 count2 = 1 ...
making a word processer but i am having trouble keeping the words spliting up over serval lines
i want to keep all words together and not have half on one line and half on the other. any help is great :) linewidth = int(input("input the length of a line")) string = input("input your string") count1 = 0 count2 = 1 def output(): global count1 global count2 outputstring = string[(count1*linewidth):(count...
[ "linewidth = int(input(\"input the length of a line\"))\nstring = input(\"input your string\")\n\ncurrent_line_width = 0\nfor word in string.split():\n if current_line_width + len(word) + 1 <= linewidth:\n print(word, end=\" \")\n current_line_width += len(word) + 1\n else:\n current_line...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074365338_python.txt
Q: Testing if an element is in the list or not the program is supposed to ask for another input if the name input already has been entered before by checking if that name exists in the list. but the problem is the elements of the list are tuples how can a fix that? from datetime import datetime ToDoList = [] time = d...
Testing if an element is in the list or not
the program is supposed to ask for another input if the name input already has been entered before by checking if that name exists in the list. but the problem is the elements of the list are tuples how can a fix that? from datetime import datetime ToDoList = [] time = datetime.now() date_format = "%Y/%m/%d %H:%M:%S" ...
[ "To check if it is in a list of tuples you can use list comprehension.\nif name in [task[0] for task in ToDoList]:\n print('Task already exists! Select the options again.')\nelse:\n break\n\nThis loops over all the items in ToDoList and checks whether name is in the first element of the tuple.\n", "There ar...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074364879_python.txt
Q: ClassicUPS3 NameError: name 'unicode' is not defined I am trying to use the ClassicUPS3 library to have a UPS API tracker. When I run the code I am getting an error message saying, "NameError: name 'unicode' is not defined". I am not sure if it something to do with the UPS library or if it is something in the resp...
ClassicUPS3 NameError: name 'unicode' is not defined
I am trying to use the ClassicUPS3 library to have a UPS API tracker. When I run the code I am getting an error message saying, "NameError: name 'unicode' is not defined". I am not sure if it something to do with the UPS library or if it is something in the response that is throwing me this error. from ClassicUPS3 impo...
[ "Looking at the source code here, it seems that ClassicalUPS3 relies on a specific format that must be extracted from an XML file, then converted to a dict, then processed.\nI tried to run your example (with my own tracking number), and I also found out that the first member you refer to (ship_status) is not suppor...
[ 0 ]
[]
[]
[ "api", "python", "ups" ]
stackoverflow_0074365263_api_python_ups.txt
Q: how can i convert my file to exe using pyinstaller I have an application that I wrote in kivy. I want to convert this application to exe. Although I follow the steps in the documentation, I get an error when I run the exe file. It didn't work even though I looked at all the examples. The .spec file may also be fau...
how can i convert my file to exe using pyinstaller
I have an application that I wrote in kivy. I want to convert this application to exe. Although I follow the steps in the documentation, I get an error when I run the exe file. It didn't work even though I looked at all the examples. The .spec file may also be faulty # -*- mode: python ; coding: utf-8 -*- from kivy_de...
[ "Your error occure when you forgot to add:\n*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],\n\nin spec file within COLLECT. But your spec file looks fine.\nTry following steps:\n\nWithin spec file change line:\n['..\\tübitak\\main.py'],\nto\n['main.py'],\nThen try to build exe.\n\nReplace your national charact...
[ 0 ]
[ "I personally like to use Py2Exe, it's simple and works great. You can get it here and see if it works good for you.\nOther than that, I would recommend making sure you don't have an error in your code itself- I'd hate to respond to something I can't help with but I really think Py2Exe might be your solution here.\...
[ -1 ]
[ "kivy", "kivy_language", "kivymd", "pyinstaller", "python" ]
stackoverflow_0074324219_kivy_kivy_language_kivymd_pyinstaller_python.txt
Q: Pandas Dataframe to Tuple Dictionary I would like to create a tuple dictionary of a dataframe. Currently, I have a dataframe looking like this: xxxxxxxxx | Period 1 | Period 2 | Customer | -------- | -------- | Customer 1| 31 | 222 | Customer 2| 46 | 187 | I would like to get a tuple dicti...
Pandas Dataframe to Tuple Dictionary
I would like to create a tuple dictionary of a dataframe. Currently, I have a dataframe looking like this: xxxxxxxxx | Period 1 | Period 2 | Customer | -------- | -------- | Customer 1| 31 | 222 | Customer 2| 46 | 187 | I would like to get a tuple dictionary of this: tuple_dict = {('Customer ...
[ "After getting the result from pandas.DataFrame.to_dict() you can iterate over dict and create tuple_dict like the below:\ndct = df.to_dict()\nprint(dct)\n# {\n# 'Period 1': {'Customer 1': 31, 'Customer 2': 46}, \n# 'Period 2': {'Customer 1': 222, 'Customer 2': 187}\n# }\n\nres = {(k2, k1) : v2 for k1,v1 in...
[ 1, 1 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python", "tuples" ]
stackoverflow_0074365375_dataframe_dictionary_pandas_python_tuples.txt
Q: Weighted standard deviation in NumPy numpy.average() has a weights option, but numpy.std() does not. Does anyone have suggestions for a workaround? A: How about the following short "manual calculation"? def weighted_avg_and_std(values, weights): """ Return the weighted average and standard deviation. ...
Weighted standard deviation in NumPy
numpy.average() has a weights option, but numpy.std() does not. Does anyone have suggestions for a workaround?
[ "How about the following short \"manual calculation\"?\ndef weighted_avg_and_std(values, weights):\n \"\"\"\n Return the weighted average and standard deviation.\n\n values, weights -- Numpy ndarrays with the same shape.\n \"\"\"\n average = numpy.average(values, weights=weights)\n # Fast and nume...
[ 168, 48, 32, 6, 1, 1, 0 ]
[]
[]
[ "numpy", "python", "standard_deviation", "statsmodels", "weighted" ]
stackoverflow_0002413522_numpy_python_standard_deviation_statsmodels_weighted.txt
Q: Is there a vectorized way to sample multiples times with np.random.choice() with differents p? I'm trying to implement a variation ratio, and I need T samples from an array C, but each sample has different weights p_t. I'm using this: import numpy as np from scipy import stats batch_size = 1 T = 3 C = np.array(['...
Is there a vectorized way to sample multiples times with np.random.choice() with differents p?
I'm trying to implement a variation ratio, and I need T samples from an array C, but each sample has different weights p_t. I'm using this: import numpy as np from scipy import stats batch_size = 1 T = 3 C = np.array(['A', 'B', 'C']) # p_batch_T dimensions: (batch, sample, class) p_batch_T = np.array([[[0.01, 0.98, 0....
[ "In stead of sampling with the given distribution p_T, we can sample uniformly between [0,1] and compare that to the cumulative distribution:\nLet's start with Y_T, say for p_T = p_batch_T[0]\ncum_dist = p_batch_T.cumsum(axis=-1)\n\nidx_T = (np.random.rand(len(C),1) < cum_dist[0]).argmax(-1)\nY_T = C[idx_T[...,None...
[ 2, 1, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0064673562_arrays_numpy_python.txt
Q: String to pandas dataframe Name too long error Having a comma separated string.When i export it in a CSV file,and then load the resultant CSV in pandas,i get my desired result. But when I try to load the string directly in pandas dataframe,i get error Filename too big. Please help me solve it. A: I found the err...
String to pandas dataframe Name too long error
Having a comma separated string.When i export it in a CSV file,and then load the resultant CSV in pandas,i get my desired result. But when I try to load the string directly in pandas dataframe,i get error Filename too big. Please help me solve it.
[ "I found the error. Actually it was showing that behaviour for large strings.\nI used\nimport io\ndf= pd.read_csv(io.StringIO(str),sep=',', engine = 'python')\n\nIt solved the issue..str is the name of the string.\n" ]
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python", "string" ]
stackoverflow_0074365391_csv_dataframe_pandas_python_string.txt
Q: List comprehension with if statement for a list of dictionary I am learning about list comprehension, and trying to solve an exercise but I am stuck with the right index and arguments. So I have this list of dictionary called 'people', and I need to create a function with 2 arguments (first one, a list of dictiona...
List comprehension with if statement for a list of dictionary
I am learning about list comprehension, and trying to solve an exercise but I am stuck with the right index and arguments. So I have this list of dictionary called 'people', and I need to create a function with 2 arguments (first one, a list of dictionary, like 'people', and the other one, 'minimum_age' with default va...
[ "The basic idea is to do a regular list-comprehension, but if you don't always have the age then you should put an absurdly small default age in the condition clause:\npeople = [{\"name\": \"John\", \"age\": 12}, {\"name\": \"Sam\", \"age\": 36}, {\"name\": \"Frank\"}]\ndef function(people, minimum_age=18): \...
[ 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074365496_dictionary_list_python.txt
Q: Python index starts at 0. Any possibility to set index value as 1 for any terminal? I am porting the Matlab code to Python. In Matlab, indices start at 1, but in python, they start at 0. Is there any way to set the first index as 1 through a command line flag? It will be very useful for programming during index it...
Python index starts at 0. Any possibility to set index value as 1 for any terminal?
I am porting the Matlab code to Python. In Matlab, indices start at 1, but in python, they start at 0. Is there any way to set the first index as 1 through a command line flag? It will be very useful for programming during index iteration.
[ "No, there's no way to do this. Python is a 0-indexed language. Guido Van Rossum (Python creator) explained his reasons behind selecting 0-indexing over 1-indexing in this blog post:\nhttp://python-history.blogspot.com/2013/10/why-python-uses-0-based-indexing.html\n", "As far as Python is concerned, there cannot ...
[ 2, 1, 1, 1 ]
[ "i'm not aware of whether you can change that by default.\nBut you can specify the starting and ending indexes for loops with range, enumerate, etc.\ne.g.\nfor i in range(1, end + 1):\n\n" ]
[ -2 ]
[ "indexing", "python", "python_3.x" ]
stackoverflow_0074365495_indexing_python_python_3.x.txt
Q: Converting Hex to RGB value in Python Working off Jeremy's response here: Converting hex color to RGB and vice-versa I was able to get a python program to convert preset colour hex codes (example #B4FBB8), however from an end-user perspective we can't ask people to edit code & run from there. How can one prompt th...
Converting Hex to RGB value in Python
Working off Jeremy's response here: Converting hex color to RGB and vice-versa I was able to get a python program to convert preset colour hex codes (example #B4FBB8), however from an end-user perspective we can't ask people to edit code & run from there. How can one prompt the user to enter a hex value and then have i...
[ "I believe that this does what you are looking for:\nh = input('Enter hex: ').lstrip('#')\nprint('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))\n\n(The above was written for Python 3)\nSample run:\nEnter hex: #B4FBB8\nRGB = (180, 251, 184)\n\nWriting to a file\nTo write to a file with handle fhandle while pr...
[ 227, 43, 30, 18, 11, 6, 5, 5, 4, 2, 2, 1, 0 ]
[]
[]
[ "colors", "python", "rgb" ]
stackoverflow_0029643352_colors_python_rgb.txt
Q: Get time in GMT in a specific format I want a time in the below-mentioned format, using Python. Tue, 08 Nov 2022 15:35:20 GMT I should be able to get the current time in above format; Then I should be able to add days in it and get the date and time in the same above-mentioned format (for example, I want date fal...
Get time in GMT in a specific format
I want a time in the below-mentioned format, using Python. Tue, 08 Nov 2022 15:35:20 GMT I should be able to get the current time in above format; Then I should be able to add days in it and get the date and time in the same above-mentioned format (for example, I want date falling on after n number of days). Any hel...
[]
[]
[ "You can try to use the below functions:\nfrom datetime import datetime, timedelta\n\ndef get_now():\n return datetime.now().strftime('%a, %d %b %Y %H:%M:%S GMT')\n\ndef n_days_from_now(n):\n now = get_now()\n return (datetime.now() + timedelta(days = n)).strftime('%a, %d %b %Y %H:%M:%S GMT')\n\n" ]
[ -1 ]
[ "date", "gmt", "python", "time" ]
stackoverflow_0074365428_date_gmt_python_time.txt
Q: Getting error while trying to run API with flask_restful I currently have an API that looks like this (for testing): from flask_restful import Resource, request class UploadFile(Resource): def get(self): pass def post(self): is_header_present(request.headers, "User-Agent", None) def is_...
Getting error while trying to run API with flask_restful
I currently have an API that looks like this (for testing): from flask_restful import Resource, request class UploadFile(Resource): def get(self): pass def post(self): is_header_present(request.headers, "User-Agent", None) def is_header_present(headers, search_term, correct_variable): ...
[ "I had a file called opcode.py inside of my base directory so it was trying to load that file instead of the original. Deleting that file worked.\n" ]
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074365621_flask_python.txt
Q: Populating every nth row in a pandas dataframe I have a pandas dataframe, df defined as follows: df = pd.DataFrame({'Year':[1,2,3,...],'A':[2000,4000,6000,...],'B':[200,400,600,...]}) where 'Year' goes from 1-40 but it can be any integer n. I want to calculate a new column as follows df['C'] = 0.06*(df.A + df.B] ...
Populating every nth row in a pandas dataframe
I have a pandas dataframe, df defined as follows: df = pd.DataFrame({'Year':[1,2,3,...],'A':[2000,4000,6000,...],'B':[200,400,600,...]}) where 'Year' goes from 1-40 but it can be any integer n. I want to calculate a new column as follows df['C'] = 0.06*(df.A + df.B] However I wish to calculate column C only for years...
[ "I think you're looking for something like this:\n\n# Required imports\nimport pandas as pd\nimport numpy as np\n\n# Dummy data\ndf = pd.DataFrame(\n {\n 'Year':[1, 2, 3],\n 'A':[2000, 4000, 6000],\n 'B':[200, 400, 600]\n }\n)\n\n# List of yers you want to compute `0.06 * (df.A + df.B)`\n...
[ 1, 0, 0 ]
[]
[]
[ "indexing", "pandas", "python" ]
stackoverflow_0074365599_indexing_pandas_python.txt
Q: pip uninstall GDAL gives AttributeError: 'PathMetadata' object has no attribute 'isdir' I'm trying to pip install geopandas as a fresh installation, so I want to remove existing packages like GDAL and fiona. I've already managed to pip uninstall fiona, but when I try to uninstall or reinstall GDAL it gives the fol...
pip uninstall GDAL gives AttributeError: 'PathMetadata' object has no attribute 'isdir'
I'm trying to pip install geopandas as a fresh installation, so I want to remove existing packages like GDAL and fiona. I've already managed to pip uninstall fiona, but when I try to uninstall or reinstall GDAL it gives the following error message: (base) C:\usr>pip install C:/usr/Anaconda3/Lib/site-packages/GDAL-3.4.1...
[ "I just came across this question after getting the same error. Coincidentally I had just upgraded pip (I was getting tired of the yellow warnings).\nAll I had was to down grade my pip\npip install pip==21.3.1 --user\n\n", "I was seeing the same AttributeError as you when trying to install google-cloud-firestore...
[ 7, 0 ]
[]
[]
[ "gdal", "pip", "python" ]
stackoverflow_0071410741_gdal_pip_python.txt
Q: FileNotFoundError: [Errno 2] No such file or directory while trying to read from a directory in windows The directory of the folders is: C:\Pet_Classification\data\train. Below is the code snippet. train_data_dir = 'C:/Pet_Classification/data/train' train_generator = train_datagen.flow_from_directory( train_d...
FileNotFoundError: [Errno 2] No such file or directory while trying to read from a directory in windows
The directory of the folders is: C:\Pet_Classification\data\train. Below is the code snippet. train_data_dir = 'C:/Pet_Classification/data/train' train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary') Got th...
[ "It can't find you file as the path isn't reachable.\nimport os\n\n#Gets your current Directory \nprint('getcwd: ', os.getcwd())\n\n#Gets your current Directory \nprint('__file__: ', __file__)\n\n# train_data_dir = 'C:/Pet_Classification/data/train'\n\nGet the current working directory and try from there...
[ 0 ]
[]
[]
[ "filenotfounderror", "keras", "python" ]
stackoverflow_0074365566_filenotfounderror_keras_python.txt
Q: How super().__init__() works when I inherit str class? I am trying to inherit str class for fun. I provided two ways, 1) using super() and 2) using str class in the constructor as follows: class Str2(str): def __init__(self, value): super().__init__() # I did not use `value` here, but my code works! ...
How super().__init__() works when I inherit str class?
I am trying to inherit str class for fun. I provided two ways, 1) using super() and 2) using str class in the constructor as follows: class Str2(str): def __init__(self, value): super().__init__() # I did not use `value` here, but my code works! def ishello(self): if self == "Hello": ...
[ "str.__init__ does not do anything (similar to tuple.__init__, among other immutable classes). The actual initialization happens in __new__. Conceptually, this makes sense, since __new__ returns a new object, while __init__ can be run multiple times on an existing one. That means that whether you call super().__ini...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0074365554_python.txt
Q: PyOpenGL glutInit NullFunctionError I am running Anaconda Python 2.7 on a Win7 x64 machine and used pip install PyOpenGL PyOpenGL_accelerate at the Anaconda command line to install PyOpenGL. I have some code (not my own I must confess) that makes use of glutInit import sys import math import numpy import OpenGL...
PyOpenGL glutInit NullFunctionError
I am running Anaconda Python 2.7 on a Win7 x64 machine and used pip install PyOpenGL PyOpenGL_accelerate at the Anaconda command line to install PyOpenGL. I have some code (not my own I must confess) that makes use of glutInit import sys import math import numpy import OpenGL from OpenGL.GL import * from OpenGL.GLUT...
[ "According to the link below the problem was with the glut installation rather than pip install. It seems glut files are not part of PyOpenGL or PyOpenGL_accelerate package. You have to download them seperately.\nhttps://stackoverflow.com/a/39181193/7030177\nWindows user can use the link below to download glut as m...
[ 26, 15, 8, 7, 6, 3, 3, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "glut", "pyopengl", "python", "python_2.7", "python_3.x" ]
stackoverflow_0026700719_glut_pyopengl_python_python_2.7_python_3.x.txt