content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How do you use a for loop to send out emails in Python using win32com I have a df which has contact details of several people, below is a test example of what it looks like: first_name Last_name email Steve Smith email1@outlook.com John Walker email2@outlook.com etc... In short...
How do you use a for loop to send out emails in Python using win32com
I have a df which has contact details of several people, below is a test example of what it looks like: first_name Last_name email Steve Smith email1@outlook.com John Walker email2@outlook.com etc... In short, I want to use Python to send a customised email to each of the people in ...
[ "You can iterate through the entire Dataframe row by row and use f-strings to abtain your goal.\nimport win32com.client as win32\nimport pandas as pd\n\ndf = pd.read_excel(\"test_emails.xlsx\")\n\nfor index, row in df.iterrows():\n outlook = win32.Dispatch('outlook.application')\n mail = outlook.CreateItem(0)...
[ 1 ]
[]
[]
[ "dataframe", "for_loop", "python", "win32com" ]
stackoverflow_0074521476_dataframe_for_loop_python_win32com.txt
Q: How to remove duplicates with different orders from a list? I made a special triangle (or whatever they're called). It works fine but a flaw is it prints out the same triangle in a different order. This is the code: SpecialTriangles = [] for i in range(15): for j in range(15): for k in range(15): ...
How to remove duplicates with different orders from a list?
I made a special triangle (or whatever they're called). It works fine but a flaw is it prints out the same triangle in a different order. This is the code: SpecialTriangles = [] for i in range(15): for j in range(15): for k in range(15): if i**2 + j**2 == k**2: if i**2 + 0 != k*...
[ "You're looking for itertools.combinations:\nfrom itertools import combinations\n\nfor i, j, k in combinations(range(15), 3):\n # do your logic with i, j, k\n\nJust as you requested, combinations() will give each possible triplet just once.\n", "Here is one possible way with itertools.combinations. iterools.co...
[ 6, 1, 1 ]
[ "As the other answers mention, you are looking for combinations of the three elements, i.e. collections of the three indexes irrespectively of their order.\nAs an alternative to leave your code more \"explicit\", you might order the triplet of indexes and append it only if they are not already in SpecialTriangles:\...
[ -1 ]
[ "python" ]
stackoverflow_0074521723_python.txt
Q: How can I keep checking every 30 seconds on multiple processes if alive python I have program that is running 2 process in parallel. After processes are launched, I am trying to check every 30 seconds if processes are still alive. Below is my pseudo code. Both processes takes between 5-10 minutes. I checked both p...
How can I keep checking every 30 seconds on multiple processes if alive python
I have program that is running 2 process in parallel. After processes are launched, I am trying to check every 30 seconds if processes are still alive. Below is my pseudo code. Both processes takes between 5-10 minutes. I checked both processes ran successfully but while processes are alive it is not getting into while...
[ "When you call:\nfor process in processes:\n process.join()\n\nyou are waiting for your two processes to finish before continuing on to your loop. Only after both are finished do you attempt to enter the while loop, but then immediately break as both have already finished.\njoin should be used when you need to ma...
[ 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0074513150_multiprocessing_python.txt
Q: Trigger a Python function exactly on the minute I have a function that I want to trigger at every turn of the minute — at 00 seconds. It fires off a packet over the air to a dumb display that will be mounted on the wall. I know I can brute force it with a while loop but that seems a bit harsh. I have tried using s...
Trigger a Python function exactly on the minute
I have a function that I want to trigger at every turn of the minute — at 00 seconds. It fires off a packet over the air to a dumb display that will be mounted on the wall. I know I can brute force it with a while loop but that seems a bit harsh. I have tried using sched but that ends up adding a second every minute. W...
[ "You might try APScheduler, a cron-style scheduler module for Python.\nFrom their examples:\nfrom apscheduler.scheduler import Scheduler\n\n# Start the scheduler\nsched = Scheduler()\nsched.start()\n\ndef job_function():\n print \"Hello World\"\n\nsched.add_cron_job(job_function, second=0)\n\nwill run job_functi...
[ 7, 5, 4, 4, 2, 2, 0, 0 ]
[ "you could use a while loop and sleep to not eat up the processor too much\n" ]
[ -1 ]
[ "python", "schedule", "time" ]
stackoverflow_0019645720_python_schedule_time.txt
Q: Elastic serach testing on Production Database (Read only ES usecase) How to test ES data without mocking, which is smart enough to figure out, what should be result at the top Did google, found most of the libraries are mocking data, but as we have evolving ES indices and logic changes day by day, what should be b...
Elastic serach testing on Production Database (Read only ES usecase)
How to test ES data without mocking, which is smart enough to figure out, what should be result at the top Did google, found most of the libraries are mocking data, but as we have evolving ES indices and logic changes day by day, what should be best practise to follow.
[ "You could configure your local elasticsearch to connect production DB when it creates the index.\n" ]
[ 0 ]
[]
[]
[ "elasticsearch", "pytest", "python", "testing" ]
stackoverflow_0074522257_elasticsearch_pytest_python_testing.txt
Q: Rust serializes different than python? || Change Endianess in bincode I'm new to Rust but not to programming. So I try to send data to a server via TCPStream (server is able to respond with 500Hz running on a robot) I got a working example python-program from the company which builds the robots. The problem: After...
Rust serializes different than python? || Change Endianess in bincode
I'm new to Rust but not to programming. So I try to send data to a server via TCPStream (server is able to respond with 500Hz running on a robot) I got a working example python-program from the company which builds the robots. The problem: After a couple of days and reading the documentation over and over again I measu...
[ "Inserting\n let serialize_options = bincode::DefaultOptions::new()\n .with_fixint_encoding()\n .with_big_endian();\n\nand editing\n let payload_byte: Vec<u8> = \n serialize_options.serialize(&payload).unwrap();\n\nworked for me\nBig thanks to you\n" ]
[ 0 ]
[]
[]
[ "python", "rust", "serialization", "tcp" ]
stackoverflow_0074508447_python_rust_serialization_tcp.txt
Q: python list comprehension in dictionary def square100(): d = {f"{x}" : f"{x**2}" for x in range(101)} print(d) if __name__ == "__main__": quadrado100() this function return the values in ascending order. def square100(): d = {f"{x} : {x**2}" for x in range(101)} print(d) if __name__ == "__main__": q...
python list comprehension in dictionary
def square100(): d = {f"{x}" : f"{x**2}" for x in range(101)} print(d) if __name__ == "__main__": quadrado100() this function return the values in ascending order. def square100(): d = {f"{x} : {x**2}" for x in range(101)} print(d) if __name__ == "__main__": quadrado100() but this function that should...
[ "The latter is a set comprehension, not a dict comprehension (neither one is a list comprehension); the difference is that there is no : (at top level, outside string quotes and the like) separating a key from a value in a set literal or comprehension, while there is one in a dict literal or comprehension.\nsets ha...
[ 2 ]
[]
[]
[ "dictionary", "dictionary_comprehension", "python" ]
stackoverflow_0074522323_dictionary_dictionary_comprehension_python.txt
Q: Scraping news title from a page with bs4 in python I was trying to scrape the "entry-title" of the last news on the site "https://www.abafg.it/category/avvisi/" and prints [ ] instead, what am i doing the wrong way? The result of what the code returns instead of the "entry-title" of the page i want to scrape the i...
Scraping news title from a page with bs4 in python
I was trying to scrape the "entry-title" of the last news on the site "https://www.abafg.it/category/avvisi/" and prints [ ] instead, what am i doing the wrong way? The result of what the code returns instead of the "entry-title" of the page i want to scrape the info I tried to scrape the class "entry-title" to let me ...
[ "The entry-title class is not of the link a tag, but of the h2 wrapped around it.\nYou can use\nnames = [h.a for h in soup.find_all('h2', class_='entry-title')]\n\nBut I think using CSS selectors would be better here\nnames = soup.select('h2.entry-title > a[href]')\n\nwill select any a tag with a href attribute and...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping", "wordpress" ]
stackoverflow_0074521981_beautifulsoup_python_screen_scraping_wordpress.txt
Q: How to create a python script to parse a xlsx spreadsheet file and generate sql statements? I have a xlsx file with two columns (id, meal) and 100 rows of data, and I want to parse the data to generate a notepad file that has sql update statements. Id Meal 12345 Child 23456 Adult 34567 Senior 34599 Senior I'...
How to create a python script to parse a xlsx spreadsheet file and generate sql statements?
I have a xlsx file with two columns (id, meal) and 100 rows of data, and I want to parse the data to generate a notepad file that has sql update statements. Id Meal 12345 Child 23456 Adult 34567 Senior 34599 Senior I'm unsure on how to implement if/else/else if statements and add data from the xlsx fi...
[ "Using the pandas library, I think we can achieve what you want like this:\nimport pandas as pd\n\ndf = pd.read_excel(path) # read our dataframe from excel\n\nall_statements = [] # initialize an empty list to append to\nfor row in df.itertuples(index=False): # loop over each row\n statement = f\"update system.us...
[ 1 ]
[]
[]
[ "python", "xlsx" ]
stackoverflow_0074522144_python_xlsx.txt
Q: Python context manager that measures time I am struggling to make a piece of code that allows to measure time spent within a "with" statement and assigns the time measured (a float) to the variable provided in the "with" statement. import time class catchtime: def __enter__(self): self.t = time.clock(...
Python context manager that measures time
I am struggling to make a piece of code that allows to measure time spent within a "with" statement and assigns the time measured (a float) to the variable provided in the "with" statement. import time class catchtime: def __enter__(self): self.t = time.clock() return 1 def __exit__(self, type...
[ "Here is an example of using contextmanager\nfrom time import perf_counter\nfrom contextlib import contextmanager\n\n@contextmanager\ndef catchtime() -> float:\n start = perf_counter()\n yield lambda: perf_counter() - start\n\n\nwith catchtime() as t:\n import time\n time.sleep(1)\n\nprint(f\"Execution ...
[ 26, 13, 12, 8, 3, 3, 1, 0 ]
[]
[]
[ "python", "with_statement" ]
stackoverflow_0033987060_python_with_statement.txt
Q: Yamnet audio classification for feature extraction I am currently working on audio classification task and using Yamnet which is a pretrained model from tfhub.. I am using it to extract embeddings from audios and then i use another simple classification model composed of two dense layers, the second model takes as...
Yamnet audio classification for feature extraction
I am currently working on audio classification task and using Yamnet which is a pretrained model from tfhub.. I am using it to extract embeddings from audios and then i use another simple classification model composed of two dense layers, the second model takes as input the embeddings given by yamnet and does the class...
[ "Sounds like your data are not separated equally between each class. Your model overfits with the \"third class\" from your dataset. I would consider investigating the possibility of splitting the data for train, validation and testing using the stratified method so that every class is included during training/vali...
[ 0 ]
[]
[]
[ "audio", "deep_learning", "multiclass_classification", "python", "tensorflow_hub" ]
stackoverflow_0071649169_audio_deep_learning_multiclass_classification_python_tensorflow_hub.txt
Q: SSLCertVerificationError is caught by ValueError and not OSError We had a bug I'm trying to understand why happened. In the documentation it is mentioned that SSLError a subtype of OSError. (https://docs.python.org/3/library/ssl.html#ssl.SSLError) However this code doesn't work as expected - it seems that ValueErr...
SSLCertVerificationError is caught by ValueError and not OSError
We had a bug I'm trying to understand why happened. In the documentation it is mentioned that SSLError a subtype of OSError. (https://docs.python.org/3/library/ssl.html#ssl.SSLError) However this code doesn't work as expected - it seems that ValueError wins over def bar(): raise ssl.SSLCertVerificationError try: ...
[ "It looks like you're getting this behaviour because SSLCertVerificationError extends both OSError and ValueError.\ni.e. running inspect's getmro on this class...:\nimport ssl\nimport inspect\ninspect.getmro(ssl.SSLCertVerificationError)\n\n...gives this\n\n<class 'ssl.SSLCertVerificationError'>\n<class 'ssl.SSLErr...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074519740_python.txt
Q: how to add a newline after each append in list I have a list of tuples in rows which I need to append to another list and add a newline after each entry I tried everything I can think of but I cant seem to do it properly here is the code: niz = [""" (5, 6, 4) (90, 100, 13), (5, 8, 13), (9, 11, 13) (9, 11, 5), (19,...
how to add a newline after each append in list
I have a list of tuples in rows which I need to append to another list and add a newline after each entry I tried everything I can think of but I cant seem to do it properly here is the code: niz = [""" (5, 6, 4) (90, 100, 13), (5, 8, 13), (9, 11, 13) (9, 11, 5), (19, 20, 5), (30, 34, 5) (9, 11, 4) (22, 25, 13), (17, 1...
[ "When you write\nniz = [\"\"\"\n(5, 6, 4)\n(90, 100, 13), (5, 8, 13), (9, 11, 13)\n(9, 11, 5), (19, 20, 5), (30, 34, 5)\n(9, 11, 4)\n(22, 25, 13), (17, 19, 13)\n\"\"\"]\n\nYou are creating a list with a single string, and not a list of tuples. I would do something like this:\nniz = [\"[\",(5, 6, 4), \"\\n\", (90, 1...
[ 0, 0, -2 ]
[]
[]
[ "for_loop", "list", "newline", "python", "tuples" ]
stackoverflow_0074522188_for_loop_list_newline_python_tuples.txt
Q: Python default version not opening by default (Windows) It seems my default python is v3.11 (indicated by the asterisk when doing command line "py -0p") and yet at the same time it says it's v3.10 (command line "python --version") and v3.10 is also the version it opens by default via command line. I've updated the...
Python default version not opening by default (Windows)
It seems my default python is v3.11 (indicated by the asterisk when doing command line "py -0p") and yet at the same time it says it's v3.10 (command line "python --version") and v3.10 is also the version it opens by default via command line. I've updated the environment variables (PY_PYTHON and Path) to point to v3.11...
[ "The easiest way to switch to the newest version is to uninstall the older ones but if you want to keep them, try restarting your cmd.\n" ]
[ 0 ]
[]
[]
[ "default", "python", "version" ]
stackoverflow_0074522309_default_python_version.txt
Q: select.poll doesn't detect available read unless I sleep for some time Context I would like to use select.poll to know when data is available to read, buffer this data, and use said buffer as a subprocess' stdin. The data is being dumped at equally spaced intervals. (see execution example) It's important that read...
select.poll doesn't detect available read unless I sleep for some time
Context I would like to use select.poll to know when data is available to read, buffer this data, and use said buffer as a subprocess' stdin. The data is being dumped at equally spaced intervals. (see execution example) It's important that reading data in the main script is non-blocking, so subprocess can be executed f...
[ "First, your shebang (#!) must be in line 1 , not line 4.\nNobody will be able to replicate the problem without fixing that.\nSecond, I think there is a flaw in your original bash script. The way it's written, the CPU will execute at full speed to generate a bunch of 10 consecutive lines and then sleep 10 seconds.\...
[ 2 ]
[]
[]
[ "polling", "python", "select" ]
stackoverflow_0074520647_polling_python_select.txt
Q: Comparing Two Dataframes Columns against a third column in Second DataFrame I am trying to compare two different dataframes for column "Source2/Source3" against "Spider". If they are a match then create column True/False. Secondly, If there is a match (True) then I want to make sure column "Product_ID' in schedule...
Comparing Two Dataframes Columns against a third column in Second DataFrame
I am trying to compare two different dataframes for column "Source2/Source3" against "Spider". If they are a match then create column True/False. Secondly, If there is a match (True) then I want to make sure column "Product_ID' in scheduler_df is 12345. If this is the case then mark 'True' else 'False'. So far in my co...
[ "we can create the testing for the product_id in scheduler_df:\n scheduler_df['prod_test']=scheduler_df.Product_ID.apply(lambda x:True if x==12345 else False)\n\nthen we create our column isProd:\nconsolidate_df['isProd']=consolidate_df['isScheduler'] & scheduler_df['prod_test'] | consolidate_df['isScheduler'] & sc...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074521177_pandas_python.txt
Q: Declare a global variable with certain type In python, is it possible to declare a global variable with a type? I know this is fine to declare a local variable like this. student: Student Or global student But I'm looking for something like this global student: Student A: I did it like this: from typing import...
Declare a global variable with certain type
In python, is it possible to declare a global variable with a type? I know this is fine to declare a local variable like this. student: Student Or global student But I'm looking for something like this global student: Student
[ "I did it like this:\nfrom typing import Union\nfrom my_class import MyClass\n\nfoo_my_class: Union[MyClass, None] = None\n\ndef setup_function():\n \"\"\" test setup \"\"\"\n global foo_my_class\n foo_my_class = MyClass()\n...\n\nI.e., this is a test module, and I want foo_my_class to be available at glob...
[ 0 ]
[ "There are no set types for python variables, so you just need to declare global variable - which would automatically be any variable declared outside of a function scope.\n" ]
[ -1 ]
[ "global_variables", "python", "types", "variables" ]
stackoverflow_0057928762_global_variables_python_types_variables.txt
Q: Sum all columns by month? I have a dataframe: date C P 0 15.4.21 0.06 0.94 1 16.4.21 0.15 1.32 2 2.5.21 0.06 1.17 3 8.5.21 0.20 0.82 4 9.6.21 0.04 -5.09 5 1.2.22 0.05 7.09 I need to create 2 columns where I Sum both C and P for each...
Sum all columns by month?
I have a dataframe: date C P 0 15.4.21 0.06 0.94 1 16.4.21 0.15 1.32 2 2.5.21 0.06 1.17 3 8.5.21 0.20 0.82 4 9.6.21 0.04 -5.09 5 1.2.22 0.05 7.09 I need to create 2 columns where I Sum both C and P for each month. So new df will have 2 c...
[ "You almost had it, you need to convert first to_datetime:\nout = (df[['C','P']]\n .groupby(pd.to_datetime(df['date'], day_first=True)\n .dt.to_period('M'))\n .sum()\n )\n\nOutput:\n C P\ndate \n2021-02 0.06 1.17\n2021-04 0.21 2.26\n2021-08 0.20 0...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074522628_pandas_python.txt
Q: How to get rid of comma at the end of printing from loop So basically I have the list of many points and I want to extract only unique values. I have written a function but I have 1 problem: how to avoid printing comma at the end of the list? def unique(list1): unique_values = [] for u in list1: if...
How to get rid of comma at the end of printing from loop
So basically I have the list of many points and I want to extract only unique values. I have written a function but I have 1 problem: how to avoid printing comma at the end of the list? def unique(list1): unique_values = [] for u in list1: if u not in unique_values: unique_values.append(u) ...
[ "Replace:\n\n for u in unique_values:\n print(u, end=\", \")\n\nwith the pythonic:\n\n print(', '.join(unique_values))\n\nAlso generally better style to return unique_values and use print(', '.join(unique(wells)))\n", "It might be an overkill but you can use NumPy \"unique\" method, which is probably...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074522488_python.txt
Q: How can i pass a requirement into a sort function, and create a template sort method to either sort one of the object of class "reading" in python #i want to pass the list, and algorithm (bubblesort) into the sort method with a requirement (temp or wind_speed) class Reading: def __init__(self, _temperatur...
How can i pass a requirement into a sort function, and create a template sort method to either sort one of the object of class "reading" in python
#i want to pass the list, and algorithm (bubblesort) into the sort method with a requirement (temp or wind_speed) class Reading: def __init__(self, _temperature, _windspeed): self.temp = _temperature self.windspeed = _windspeed def bubblesort(num): for i in range (len(num)-1, 0...
[ "Here's an example how to pass a function as an argument to another function:\ndef add(x, y):\n return x + y\n\ndef mul(x,y):\n return x * y\n\ndef calculate(x, y, func):\n return func(x, y)\n\nz1 = calculate(1, 1, add)\nz2 = calculate(1, 1, mul)\n\nprint(f\"add = {z1}, mul = {z2}\")\n\n" ]
[ 2 ]
[]
[]
[ "bubble_sort", "objectlistview_python", "python", "sorting" ]
stackoverflow_0074522565_bubble_sort_objectlistview_python_python_sorting.txt
Q: How to fix Django / python free(): invalid pointer? When I run the django manage.py app, I got free(): invalid pointer error. Example: >python manage.py check System check identified no issues (0 silenced). free(): invalid pointer Abortado (imagem do núcleo gravada) The django app is running fine but I'm trying t...
How to fix Django / python free(): invalid pointer?
When I run the django manage.py app, I got free(): invalid pointer error. Example: >python manage.py check System check identified no issues (0 silenced). free(): invalid pointer Abortado (imagem do núcleo gravada) The django app is running fine but I'm trying to get rid off this message. How can I fix this error or g...
[ "I have tested with same environment with same Django version and I ran the check command, which did not yield this problem. I assume it is an issue with Pytorch, as mentioned in here: GitHub issue #21018.\nTo resolve it, you can take the following steps (copy pasted from this SO answer: https://stackoverflow.com/a...
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0073313134_django_python.txt
Q: django-smart-selects not working properly I want to have chained foreign key in my django-admin and thus I am using django-smart-selects. I have followed the documentation properly Install django-smart-selects Add it in installed_apps in settings.py Add this line in my base urls.py url(r'^chaining/', incl...
django-smart-selects not working properly
I want to have chained foreign key in my django-admin and thus I am using django-smart-selects. I have followed the documentation properly Install django-smart-selects Add it in installed_apps in settings.py Add this line in my base urls.py url(r'^chaining/', include('smart_selects.urls')), changed my model ...
[ "Use USE_DJANGO_JQUERY = True instead of JQUERY_URL = True in your settings.py\n", "Use USE_DJANGO_JQUERY = True\nand JQUERY_URL = False\n\nAdd this in your html\n\n <script src=\"/static/smart-selects/admin/js/chainedfk.js\"></script>\n <script src=\"/static/smart-selects/admin/js/bindfields.js\"><...
[ 3, 0, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "django_smart_selects", "python" ]
stackoverflow_0061727169_django_django_admin_django_models_django_smart_selects_python.txt
Q: pyproject.toml/setuptools duplicates files into root site-packages directory I have a problem with how pip/setuptools is installing my package. When installing from the project directory (i.e. pip install .) my project's sub-packages are duplicated and placed in the root site-packages directory. The configuration ...
pyproject.toml/setuptools duplicates files into root site-packages directory
I have a problem with how pip/setuptools is installing my package. When installing from the project directory (i.e. pip install .) my project's sub-packages are duplicated and placed in the root site-packages directory. The configuration is set entirely within pyproject.toml (with a minimal setup.py for compiling a sin...
[ "I've just ran into the same issue.\nIn my case, the build directory used by pip was polluted with the \"subfolders\", probably because of a previous run where my package discovery settings were erroneous.\nBecause of this, although my configuration was (now) correct, these orphaned directories were copied to my si...
[ 0 ]
[]
[]
[ "pyproject.toml", "python", "setuptools" ]
stackoverflow_0073491139_pyproject.toml_python_setuptools.txt
Q: How to save a json file using json.dump without the square bracket I need to save the json file without the beginning and ending [ and ] respectively. Sample data: import pandas as pd import json df = pd.DataFrame({'name' : ['abc', 'pqr', 'xzy'], 'score' : [85, 90, 80], 'addres...
How to save a json file using json.dump without the square bracket
I need to save the json file without the beginning and ending [ and ] respectively. Sample data: import pandas as pd import json df = pd.DataFrame({'name' : ['abc', 'pqr', 'xzy'], 'score' : [85, 90, 80], 'address' : ['ab street', 'pq street', 'xy ave']}) df name score addr...
[ "The jsoning-in-a-loop variant would be something like this:\njl = [\n {\n \"name\": \"abc\",\n \"score\": 85,\n \"address\": \"ab street\"\n },\n {\n \"name\": \"pqr\",\n \"score\": 90,\n \"address\": \"pq street\"\n },\n {\n \"name\": \"xzy\",\n ...
[ 2, 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074522486_json_pandas_python.txt
Q: How do I number the inputs that I take from the user? How do I list inputs. I'm writing an program whereby when the user inputs 20 heights of the students, it automatically determines the tallest and shortest height. I want to ask for the Input in this way : Height of Student No.1 = Height of Student No.2 = ...
How do I number the inputs that I take from the user?
How do I list inputs. I'm writing an program whereby when the user inputs 20 heights of the students, it automatically determines the tallest and shortest height. I want to ask for the Input in this way : Height of Student No.1 = Height of Student No.2 = for x in range(20): height = float(input("Height...
[ "As the error suggests, input() only takes one argument and you gave it two: you gave it your string \"Height of Student No.\" and you gave it x.\nI think what you want here is to include the value of x in your string. This can be accomplished using f-strings like so:\nfor x in range(1,21):\n height = float(inpu...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074522766_python.txt
Q: One connection to DB for app, or a connection on every execution? I'm using psycopg2 library to connection to my postgresql database. Every time I want to execute any query, I make a make a new connection like this: import psycopg2 def run_query(query): with psycopg2.connect("dbname=test user=postgres") as co...
One connection to DB for app, or a connection on every execution?
I'm using psycopg2 library to connection to my postgresql database. Every time I want to execute any query, I make a make a new connection like this: import psycopg2 def run_query(query): with psycopg2.connect("dbname=test user=postgres") as connection: cursor = connection.cursor() cursor.execute(q...
[ "Both ways are bad. The fist one is particularly bad, because opening a database connection is quite expensive. The second is bad, because you will end up with a single connection (which is too few) one connection per process or thread (which is usually too many).\nUse a connection pool.\n", "You should strongly ...
[ 0, 0 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0074511042_postgresql_psycopg2_python.txt
Q: ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0' UBUNTU SERVER (EC2) I am setting up my EC2 instance on AWS with an UBUNTU 18.04 and running into the following error when trying to run this gunicorn command gunicorn --bind 0.0.0.0:8000 zipherJobCards.wsgi:application error: OSErro...
ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0' UBUNTU SERVER (EC2)
I am setting up my EC2 instance on AWS with an UBUNTU 18.04 and running into the following error when trying to run this gunicorn command gunicorn --bind 0.0.0.0:8000 zipherJobCards.wsgi:application error: OSError: cannot load library 'pango-1.0-0': pango-1.0-0: cannot open shared object file: No such file or directory...
[ "I got a similar error and after installing this solved the problem\nsudo apt-get install -y libpangocairo-1.0-0\n", "For mac, I just installed pango using homebrew and it seemed to work.\nRan brew install pango\nRelevant link: https://formulae.brew.sh/formula/pango\n" ]
[ 2, 0 ]
[]
[]
[ "amazon_ec2", "django", "python", "ubuntu_18.04", "weasyprint" ]
stackoverflow_0070031075_amazon_ec2_django_python_ubuntu_18.04_weasyprint.txt
Q: TypeError: counter_label() missing 1 required positional argument: 'label' I can count number but i can't countdown on label tkinter Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\tkinter_in...
TypeError: counter_label() missing 1 required positional argument: 'label'
I can count number but i can't countdown on label tkinter Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "C:\Program Files\Windo...
[ "your recursive call\nlabel.after(1000,counter_label)\n\ncan be modified to include label argument with an anonymous function\nlabel.after(1000,lambda x=label: counter_label(x))\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074522773_python_tkinter.txt
Q: Upload object to Oracle Storage using put_object in Python I'm trying to upload an object to Oracle Storage with oci-cli library in Python. When I try using command-line: oci os object put -ns grddddaaaZZ -bn dev.bucket --name processed/2020-11 --file /path/to/my/file/image.tif I actually get a response like: Upl...
Upload object to Oracle Storage using put_object in Python
I'm trying to upload an object to Oracle Storage with oci-cli library in Python. When I try using command-line: oci os object put -ns grddddaaaZZ -bn dev.bucket --name processed/2020-11 --file /path/to/my/file/image.tif I actually get a response like: Upload ID: 4f...78f0fdc5 Split file into 2 parts for upload. Upload...
[ "You could try uploading some other data first, to see if it's the payload:\nnamespace = 'grddddaaaZZ'\nbucket_name = 'dev.bucket'\nobject_name = 'processed/2020-11/test.txt'\ntest_data = b\"Hello, World!\"\n\nobj = object_storage.put_object(\n namespace,\n bucket_name,\n object_name,\n my_data)\n\nor y...
[ 2, 0 ]
[]
[]
[ "cloud", "oracle", "oracle_cloud_infrastructure", "python" ]
stackoverflow_0065814234_cloud_oracle_oracle_cloud_infrastructure_python.txt
Q: How can I convert multiple columns in a pandas dataframe into a column containing dictionaries of those columns? I have a very large dataframe containing the following columns: RegAddress.CareOf,RegAddress.POBox,RegAddress.AddressLine1,RegAddress.AddressLine2,RegAddress.PostTown,RegAddress.County,RegAddress.Countr...
How can I convert multiple columns in a pandas dataframe into a column containing dictionaries of those columns?
I have a very large dataframe containing the following columns: RegAddress.CareOf,RegAddress.POBox,RegAddress.AddressLine1,RegAddress.AddressLine2,RegAddress.PostTown,RegAddress.County,RegAddress.Country,RegAddress.PostCode I am inserting this dataframe (loaded from a CSV) into a relational database, and so would like...
[ "You can use the .apply() method to achieve this:\nselected_cols = ['RegAddress.CareOf', 'RegAddress.POBox']\n\ndf2 = pd.DataFrame()\ndf2['RegAddress'] = df.apply(\n lambda row: {\n col.split('.')[1]: row[col] for col in row.index\n if col in selected_cols\n },\n axis=1\n)\n\nResult:\n ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074522825_dataframe_pandas_python.txt
Q: How to create multiple data frames & write it to excel file I have two data frames and joined the data with left join from the column "country" i need to create a separate table in excel for each 4 countries from the joined dataframes as per the attached format. Please advise how can i achieve this ? please advise...
How to create multiple data frames & write it to excel file
I have two data frames and joined the data with left join from the column "country" i need to create a separate table in excel for each 4 countries from the joined dataframes as per the attached format. Please advise how can i achieve this ? please advise how can i achieve this? Import Pandas as pd import numpy as np f...
[ "You can loop on df3['Country'].unique():\nfor country in df3['Country'].unique():\n df_ = df3[df3['Country'] == country].to_excel(f'path_to_output_{country}.xlsx',index=False)\n \n\n", "You can use df.groupby:\nfor country, g in df.groupby(\"country\"):\n g.to_excel(f\"file_{country}.xls\", index=False)\n...
[ 0, 0 ]
[]
[]
[ "dataframe", "export_to_excel", "loops", "pandas", "python" ]
stackoverflow_0074522812_dataframe_export_to_excel_loops_pandas_python.txt
Q: Using if statement to find specific string values in a list I have a column within a dataframe that is composed of lists. I am trying to use an if statement to identify values in these lists that contain any special character or number. The numbers I am trying to identify are string values, not numeric. I have tri...
Using if statement to find specific string values in a list
I have a column within a dataframe that is composed of lists. I am trying to use an if statement to identify values in these lists that contain any special character or number. The numbers I am trying to identify are string values, not numeric. I have tried using regex to identify these values, but I don't know exactly...
[ "in reference to this post, the following might be what you need:\nspecial_chars = ['-', '/', '0', '1']\n\n# returns df with only the rows in which the column contains any of these characters\nresult_df = df.loc[df['col_name'].str.contains('|'.join(special_chars))]\n\nthe '|' will function as a regex character.\n" ...
[ 0 ]
[]
[]
[ "if_statement", "list", "python" ]
stackoverflow_0074522890_if_statement_list_python.txt
Q: odient: "takes 1 positional argument but 2 were given" I have been using odient in python for a project and it's been working completely fine. I did the same thing I always do for this problem and for some reason it keeps saying my defined function takes 1 positional argument but 2 were given, even though it's bee...
odient: "takes 1 positional argument but 2 were given"
I have been using odient in python for a project and it's been working completely fine. I did the same thing I always do for this problem and for some reason it keeps saying my defined function takes 1 positional argument but 2 were given, even though it's been fine doing problems like this before. Here is my code: ...
[ "your derivative function passed to odeint needs to expect 2 inputs (y and t), the most straight forward solution is to just make your function take multiple arguments as you seem to have forgotten.\ndef sy(J,t):\n\n" ]
[ 1 ]
[ "In the error it clearly mentioned that the function \"Odient\" takes 1 positional argument but you are trying to put more than 1 argument example.\n#This function take one Parameter \"var\"\ndef foo(var):\n return var\n\n#Calling the function with print statement\n\nprint(foo(var, var2)) #Trying to give more than ...
[ -1 ]
[ "python" ]
stackoverflow_0074522901_python.txt
Q: How to drop columns which have same values in all rows via pandas or spark dataframe? Suppose I've data similar to following: index id name value value2 value3 data1 val5 0 345 name1 1 99 23 3 66 1 12 name2 1 99 23 2 66 5 2 name6 1 9...
How to drop columns which have same values in all rows via pandas or spark dataframe?
Suppose I've data similar to following: index id name value value2 value3 data1 val5 0 345 name1 1 99 23 3 66 1 12 name2 1 99 23 2 66 5 2 name6 1 99 23 7 66 How can we drop all those columns like (value, value2, value3) whe...
[ "What we can do is use nunique to calculate the number of unique values in each column of the dataframe, and drop the columns which only have a single unique value:\nIn [285]:\nnunique = df.nunique()\ncols_to_drop = nunique[nunique == 1].index\ndf.drop(cols_to_drop, axis=1)\n\nOut[285]:\n index id name data1...
[ 62, 7, 4, 1, 1, 0 ]
[]
[]
[ "apache_spark_sql", "duplicates", "multiple_columns", "pandas", "python" ]
stackoverflow_0039658574_apache_spark_sql_duplicates_multiple_columns_pandas_python.txt
Q: Best way to deploy multiple client websites by Wagtail I want to create wagtail websites for my clients. The websites will be identical and have the same features, but the templates should be different. Every time I update a feature to a new version, all websites will get the latest version automatically. By this ...
Best way to deploy multiple client websites by Wagtail
I want to create wagtail websites for my clients. The websites will be identical and have the same features, but the templates should be different. Every time I update a feature to a new version, all websites will get the latest version automatically. By this approach, I don't need to deploy new feature versions (or ba...
[ "I think you will want to include all the template variations in your code base and then choose which one to use at request time. To choose a template file dynamically, you create a get_template method.\nSo the question becomes how do you configure which site uses which template(s). I would suggest looking into wag...
[ 1 ]
[]
[]
[ "django", "python", "wagtail" ]
stackoverflow_0074499599_django_python_wagtail.txt
Q: Why cant I use my newly downloaded python library? So ive tried to install customtkinter and the installation was successfull Using cached customtkinter-4.6.3-py3-none-any.whl (246 kB) Requirement already satisfied: darkdetect in c:\users\omen1\appdata\local\programs\python\python311\lib\site-packages (from cust...
Why cant I use my newly downloaded python library?
So ive tried to install customtkinter and the installation was successfull Using cached customtkinter-4.6.3-py3-none-any.whl (246 kB) Requirement already satisfied: darkdetect in c:\users\omen1\appdata\local\programs\python\python311\lib\site-packages (from customtkinter) (0.7.1) Installing collected packages: custom...
[ "Ensure that the interpreter you're using in VSCode is aligned to where you installed the library.\nFor example if you installed it with Python3, your VSCode may be pointed to Python2 instead.\nAdditionally, according to the PyPi link for that library - \"To use CustomTkinter, just place the /customtkinter folder f...
[ 1 ]
[]
[]
[ "import", "importerror", "python" ]
stackoverflow_0074522343_import_importerror_python.txt
Q: How to merge two queryset on specific column Hello I am using a postgres database on my django app. I have this model: class MyFile(models.Model): uuid = models.UUIDField( default=python_uuid.uuid4, editable=False, unique=True) file = models.FileField(upload_to=upload_to, null=True,...
How to merge two queryset on specific column
Hello I am using a postgres database on my django app. I have this model: class MyFile(models.Model): uuid = models.UUIDField( default=python_uuid.uuid4, editable=False, unique=True) file = models.FileField(upload_to=upload_to, null=True, blank=True) path = models.CharField(max_leng...
[ "Try this if it works\nMyFile.objects.values('group').annotate(file=ArrayAgg('file', ordering='-when'))\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_queryset", "postgresql", "python" ]
stackoverflow_0074522897_django_django_queryset_postgresql_python.txt
Q: Plotting timedelta values gives out of scope axis I have a dataframe that looks like this: commits commitdates Age (in days) Year-Month server_version 0 97 2021-04-07 75 days 2021-04 v1 1 20 2021-05-31 43 days 2021-05 v3 ...
Plotting timedelta values gives out of scope axis
I have a dataframe that looks like this: commits commitdates Age (in days) Year-Month server_version 0 97 2021-04-07 75 days 2021-04 v1 1 20 2021-05-31 43 days 2021-05 v3 2 54 2021-06-21 54 days 2...
[ "All you have to do is to convert your timedelta64 to days and add days as suffix for the yaxis, I answer your question based on this random data:\nimport pandas as pd\nimport numpy as np\n\ns = pd.Series(pd.timedelta_range(start='1 days', end='75 days'))\ndf = pd.DataFrame()\ndf['commits'] = np.random.randint(100,...
[ 1 ]
[]
[]
[ "pandas", "plotly", "python" ]
stackoverflow_0074522268_pandas_plotly_python.txt
Q: django.template.exceptions.TemplateSyntaxError: 'bootstrap_field' received some positional argument(s) after some keyword argument(s) I was trying to modify my django sign_in template with bootstrap field along with some arguments but i was not able too. Exception: C:\Users\hp\Desktop\fastparcel\core\templates\si...
django.template.exceptions.TemplateSyntaxError: 'bootstrap_field' received some positional argument(s) after some keyword argument(s)
I was trying to modify my django sign_in template with bootstrap field along with some arguments but i was not able too. Exception: C:\Users\hp\Desktop\fastparcel\core\templates\sign_in.html, error at line 25 'bootstrap_field' received some positional argument(s) after some keyword argument(s) {% bootstrap_field form...
[ "thanks @raphael\nand the answer was\nremoving the space after placeholder in\n{% bootstrap_field form.username show_lable=False placeholder =\"Email\" %}\n\nto be like\n{% bootstrap_field form.username show_label=False placeholder=\"Email\" %}\n\n" ]
[ 0 ]
[]
[]
[ "backend", "bootstrap_4", "django", "html", "python" ]
stackoverflow_0074522385_backend_bootstrap_4_django_html_python.txt
Q: Python: Grab objects with match string from Python list I have a list that looks something like this: ['CALSIM', '1693', '1938', '1429', '1646', '1199', '1204', '1477', '1268', '1158', '1051', '998', '1135', '2381', '2513', 'Sky19', '1627', '2124', '1859', '2504', '1690', '1784', 'Sky21', 'Sky38', '2833', 'Sky20']...
Python: Grab objects with match string from Python list
I have a list that looks something like this: ['CALSIM', '1693', '1938', '1429', '1646', '1199', '1204', '1477', '1268', '1158', '1051', '998', '1135', '2381', '2513', 'Sky19', '1627', '2124', '1859', '2504', '1690', '1784', 'Sky21', 'Sky38', '2833', 'Sky20'] I want to create a new list from this list that only includ...
[ "You can use a conditional list composition to create a new list:\noriginal_list = ['CALSIM', '1693', '1938', '1429', '1646', '1199', '1204', '1477', '1268', '1158', '1051', '998', '1135', '2381', '2513', 'Sky19', '1627', '2124', '1859', '2504', '1690', '1784', 'Sky21', 'Sky38', '2833', 'Sky20']\n\noutput_list = [x...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074523168_python.txt
Q: Is it possible to put python's turtle into a function? First of all, I'm sorry if I made a stupid mistake because I'm a beginner. Please forgive me I started making a "game" in python using the turtle class for homework. Here is the code: import turtle window = turtle.Screen() window.setup(width=800, height=800) ...
Is it possible to put python's turtle into a function?
First of all, I'm sorry if I made a stupid mistake because I'm a beginner. Please forgive me I started making a "game" in python using the turtle class for homework. Here is the code: import turtle window = turtle.Screen() window.setup(width=800, height=800) window.bgcolor("black") window.tracer(0) player = turtle.Tu...
[ "window.onkeypress(objectup(player), \"w\") means you call objectup(player) and you pass the value it returns to window.onkeypress(..., 'w'). But it doesn't return anything (which means it returns None). You need to pass a function to window.onkeypress that will be called by turtle, something like:\nwindow.onkeypre...
[ 0 ]
[]
[]
[ "function", "python", "turtle_graphics" ]
stackoverflow_0074523090_function_python_turtle_graphics.txt
Q: Using itertools groupby, create groups of elements, if ANY key is same in each element Given a list of strings, how to group them if any value is similar? inputList = ['w', 'd', 'c', 'm', 'w d', 'm c', 'd w', 'c m', 'o', 'p'] desiredOutput = [['d w', 'd', 'w', 'w d',], ['c', 'c m', 'm', 'm c'], ['o'], ['p']] How...
Using itertools groupby, create groups of elements, if ANY key is same in each element
Given a list of strings, how to group them if any value is similar? inputList = ['w', 'd', 'c', 'm', 'w d', 'm c', 'd w', 'c m', 'o', 'p'] desiredOutput = [['d w', 'd', 'w', 'w d',], ['c', 'c m', 'm', 'm c'], ['o'], ['p']] How to sort a list properly by first, next, and last items? My sorting attempt: groupedList = s...
[ "I did it with the bubble sort algorithm.\ndef bubbleSort(arr):\nn = len(arr)\nswapped = False\n\nfor i in range(n-1):\n for j in range(0, n-i-1):\n \n g1 = arr[j][0].split()\n g2 = arr[j + 1][0].split()\n \n if any([k > l for k in g1] for l in g2):\n\n swapped = Tru...
[ 1 ]
[]
[]
[ "group_by", "python", "python_itertools", "string" ]
stackoverflow_0074492029_group_by_python_python_itertools_string.txt
Q: Is it possible to make abstract classes? How can I make a class or method abstract in Python? I tried redefining __new__() like so: class F: def __new__(cls): raise Exception("Unable to create an instance of abstract class %s" %cls) but now if I create a class G that inherits from F like so: class G(F...
Is it possible to make abstract classes?
How can I make a class or method abstract in Python? I tried redefining __new__() like so: class F: def __new__(cls): raise Exception("Unable to create an instance of abstract class %s" %cls) but now if I create a class G that inherits from F like so: class G(F): pass then I can't instantiate G either...
[ "Use the abc module to create abstract classes. Use the abstractmethod decorator to declare a method abstract, and declare a class abstract using one of three ways, depending upon your Python version.\nIn Python 3.4 and above, you can inherit from ABC. In earlier versions of Python, you need to specify your class's...
[ 734, 146, 29, 23, 16, 9, 3, 3, 3, 3, 2, 0 ]
[ "In your code snippet, you could also resolve this by providing an implementation for the __new__ method in the subclass, likewise:\ndef G(F):\n def __new__(cls):\n # do something here\n\nBut this is a hack and I advise you against it, unless you know what you are doing. For nearly all cases I advise you ...
[ -3, -3 ]
[ "abstract", "abstract_class", "class", "inheritance", "python" ]
stackoverflow_0013646245_abstract_abstract_class_class_inheritance_python.txt
Q: Only allow certain things to be imported How can I allow just what I specify to be imported? For example: main.py import random def getnumber(): return random.randint(1, 5) other.py import main print(dir(main)) In this example, I want to import the getnumber function, but not the random module. I know that...
Only allow certain things to be imported
How can I allow just what I specify to be imported? For example: main.py import random def getnumber(): return random.randint(1, 5) other.py import main print(dir(main)) In this example, I want to import the getnumber function, but not the random module. I know that "from main import getnumber" will work, but h...
[ "You can import the module, and then delete particular names from its namespace:\nimport main\ndel main.random\n\nNote that this does not modify the original module's source, just your ability to access those names from your own module. (I can't think of any good reason to do this, but there it is.)\nIf you're try...
[ 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0074523179_module_python.txt
Q: How do I get my code to recall upon the function again to start over? (Python) Here is my code that I am working on. It is supposed to take a number from the user and if its a perfect number it says so, but if its not it asks to enter a new number. When I get to the enter a new number part, it doesn't register my ...
How do I get my code to recall upon the function again to start over? (Python)
Here is my code that I am working on. It is supposed to take a number from the user and if its a perfect number it says so, but if its not it asks to enter a new number. When I get to the enter a new number part, it doesn't register my input. Can someone help me out? def isPerfect(num): if num <= 0: ...
[ "you could just put a while True loop into your main function like so:\ndef main():\n first_run = True\n perfect_num_received = False\n while not perfect_num_received:\n if first_run:\n num = int(input(\"Enter a perfect integer: \"))\n first_run = False\n if isPerfect(nu...
[ 1, 0 ]
[]
[]
[ "function", "integer", "python", "python_3.x", "user_input" ]
stackoverflow_0074523018_function_integer_python_python_3.x_user_input.txt
Q: python: is there any practice to allow using class functions outside of the object I just want to say I am a newbie to OOP so I am not sure what I am supposed to do there. so lets say I have a class that has a whole bunch of functions on data in it: class stuff: def __init__ ... def func1(self, arg1, arg2) ...
python: is there any practice to allow using class functions outside of the object
I just want to say I am a newbie to OOP so I am not sure what I am supposed to do there. so lets say I have a class that has a whole bunch of functions on data in it: class stuff: def __init__ ... def func1(self, arg1, arg2) self.var1=arg1*self.var3 self.var2=arg2*self.var4 ... the func1 uses a lot of va...
[ "\nthe func1 uses a lot of variables from the class (using self), and I\nhave a lot of functions and a lot of variables which is very\nconvenient in a class\n\nthis is a clear violation of the single responsibility principle, so you should consider splitting the class down to multiple classes, each one is responsib...
[ 1, 0, 0, 0 ]
[]
[]
[ "class", "function", "object", "oop", "python" ]
stackoverflow_0074523025_class_function_object_oop_python.txt
Q: Move first date type to specific column - pandas I have a pandas dataframe, loaded from a csv, structured as well: Who created the csv made same mistakes, and I need to move the first date which appears in each raw, to the column "Opening Date". The final result should be: How can I do it witout specifing fom wh...
Move first date type to specific column - pandas
I have a pandas dataframe, loaded from a csv, structured as well: Who created the csv made same mistakes, and I need to move the first date which appears in each raw, to the column "Opening Date". The final result should be: How can I do it witout specifing fom which column extract the date? (the only information I h...
[ "I thought a very explanatory approach.\nFirst, we need a function that recognizes the date type. I didn't understand if there is a specific format in your csv, so when in doubt we will use a function that recognizes any pattern.\nCheck out 'Check if string has date, any format':\nfrom dateutil.parser import parse\...
[ 1 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074522767_csv_dataframe_pandas_python.txt
Q: VS Code using Jupyter: Connecting to kernel: Python 3.6.9: Waiting for Jupyter Session to be idle I am having trouble running my import statement in VS code Jupyter. I split them into individual cells. I find when I run import numpy as np the cell hangs and I get a message Connecting to kernel: Python 3.6.9: Wai...
VS Code using Jupyter: Connecting to kernel: Python 3.6.9: Waiting for Jupyter Session to be idle
I am having trouble running my import statement in VS code Jupyter. I split them into individual cells. I find when I run import numpy as np the cell hangs and I get a message Connecting to kernel: Python 3.6.9: Waiting for Jupyter Session to be idle How do I fix this?
[ "To solve it, I uninstalled the extension Jupyter notebook (which requires a reload), and then installed it.\n", "This may be related to the extended version. I hope this article is helpful to you.\n", "Alright so this one surprised me..\nI was using Jupyter-like code cells \"#%%\" (see docs) to run jupyter not...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "jupyter", "python", "visual_studio_code" ]
stackoverflow_0071509993_jupyter_python_visual_studio_code.txt
Q: IndexError when using Enumerated Indexes in NumPy I am trying to create a fifth-order FIR filter in Python described by the following difference equation (apologies dark mode users but LaTeX is not yet supported on SO): def filter(x): h = np.array([-0.0147, 0.173, 0.342, 0.342, 0.173, -0.0147]) y = np.ze...
IndexError when using Enumerated Indexes in NumPy
I am trying to create a fifth-order FIR filter in Python described by the following difference equation (apologies dark mode users but LaTeX is not yet supported on SO): def filter(x): h = np.array([-0.0147, 0.173, 0.342, 0.342, 0.173, -0.0147]) y = np.zeros_like(x) buf_array = np.zeros_like(h) buf =...
[ "As someone suggested in the comments, this case use requires looping over indexes and elements on their own, as using for index in enumerate(ndarray) will result in index being a tuple rather than being an integer. Furthermore, using for index, item in enumerate(ndarray) is suggested, as shown below:\n# Filter fun...
[ 0 ]
[]
[]
[ "index_error", "numpy", "numpy_ndarray", "python", "signal_processing" ]
stackoverflow_0074499605_index_error_numpy_numpy_ndarray_python_signal_processing.txt
Q: Define a random variable I'm new with Python. I have to create a new rv U(t). Assuming that Z has a standard normal distribution c = 1.57, I have that: U(t) = 0 if Z(t) <= c U(t) = Φ(Z(t)) Z(t) > c Where Φ(·) is the cdf of the standard normal distribution N(0, 1). I start sampling random numbers from the normal d...
Define a random variable
I'm new with Python. I have to create a new rv U(t). Assuming that Z has a standard normal distribution c = 1.57, I have that: U(t) = 0 if Z(t) <= c U(t) = Φ(Z(t)) Z(t) > c Where Φ(·) is the cdf of the standard normal distribution N(0, 1). I start sampling random numbers from the normal distribution and I create an ar...
[ "Use the power of numpy!\nz = np.random.normal(0, 1, 100)\nu = np.zeros(z.shape)\n\nSince you initialized u to zeros, you don't need to do anything for the z <= c cases. For the others, you can use numpy's logical indexing to only set the elements that fulfill the condition\n# Get only the elements of z where z > c...
[ 1 ]
[]
[]
[ "python", "random", "variables" ]
stackoverflow_0074523253_python_random_variables.txt
Q: i want my turtle code start when user press enter key by python I want my pong game that is made by turtle module to start when user press Enter key (python) what I did is just add s to start but I cannot do enter key he should type enter as string word not key A: As @droebi mentioned, I would advise you to slig...
i want my turtle code start when user press enter key by python
I want my pong game that is made by turtle module to start when user press Enter key (python) what I did is just add s to start but I cannot do enter key he should type enter as string word not key
[ "As @droebi mentioned, I would advise you to slightly improve the question, as there are some mistakes that add slight difficulty to read your question.\nBut from what I inferred, you want the user to not press the enter key, but actually type the word enter in the console to start the program.\nThis problem can be...
[ 0 ]
[]
[]
[ "keyboard", "pong", "python", "python_3.x", "turtle_graphics" ]
stackoverflow_0074506303_keyboard_pong_python_python_3.x_turtle_graphics.txt
Q: For all values ​in a row, if a certain word is duplicated more than once, we want to remove it from the list I have the following dataframe en ko Tuberculosis of heart 심장의 결핵 Tuberculosis of myocardium 심근의 결핵 Tuberculosis of endocardium 심내막의 결핵 Tuberculosis of oesophagus 식도의 결핵 Zoster keratoconjunctivitis 대상...
For all values ​in a row, if a certain word is duplicated more than once, we want to remove it from the list
I have the following dataframe en ko Tuberculosis of heart 심장의 결핵 Tuberculosis of myocardium 심근의 결핵 Tuberculosis of endocardium 심내막의 결핵 Tuberculosis of oesophagus 식도의 결핵 Zoster keratoconjunctivitis 대상포진 각막결막염 Zoster blepharitis 대상포진 안검염 Zoster iritis 대상포진 홍채염 I want a result like this. en ko...
[ "You can use:\nimport re\n\n# identify duplicates\ns = df.stack().str.split().explode()\ndups = s[s.duplicated()].groupby(level=1).unique().to_dict()\n# {'en': array(['Tuberculosis', 'of', 'Zoster'], dtype=object),\n# 'ko': array(['결핵', '대상포진'], dtype=object)}\n\n# remove them\ndf.apply(lambda s: s.str.replace('|'...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074522783_dataframe_pandas_python.txt
Q: How to do *custom* action when receiving a warning in Python? I have a script that iterates through thousands of csv's and reads them into pandas, then does a bunch of other stuff with it down the line. Every once and a while, I get this message: sys:1: DtypeWarning: Columns (10,11,23) have mixed types.Specify dty...
How to do *custom* action when receiving a warning in Python?
I have a script that iterates through thousands of csv's and reads them into pandas, then does a bunch of other stuff with it down the line. Every once and a while, I get this message: sys:1: DtypeWarning: Columns (10,11,23) have mixed types.Specify dtype option on import or set low_memory=False. I tried the try/except...
[ "warnings.simplefilter exists exactly for this purpose.\nInside the warning handler you can set conditions to make sure you don't catch unwanted warnings.\nIf the warning happens only \"once in a while\" than you probably want be wasting too much runtime on the warning handler code.\n" ]
[ 0 ]
[]
[]
[ "dtype", "pandas", "python", "warnings" ]
stackoverflow_0074523098_dtype_pandas_python_warnings.txt
Q: Python-Playwright: Is there a way to introspect and/or run commands interactively? I'm trying to move from Selenium to Playwright for some webscraping tasks. Perhaps I got stuck into this bad habit of having Selenium running the browser on the side while testing the commands and selectors on the run. Is there any ...
Python-Playwright: Is there a way to introspect and/or run commands interactively?
I'm trying to move from Selenium to Playwright for some webscraping tasks. Perhaps I got stuck into this bad habit of having Selenium running the browser on the side while testing the commands and selectors on the run. Is there any way to achieve something similar using Playwright? What I achieved so far was running pl...
[ "I'd use the technique from can i run playwright outside of 'with'? and How to start playwright outside 'with' without context managers on the interactive repl:\nPS C:\\Users\\foo\\Desktop> py\nPython 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32\nType \"help\", \"copyrig...
[ 2 ]
[]
[]
[ "playwright_python", "python" ]
stackoverflow_0074517390_playwright_python_python.txt
Q: Problem with If- Else Conditiones, How can I resolve it? The problem is that I want that the code shows the graph if the Value of "Recordinaciones" is > 1, and shows "No hay Recorinaciones Dobles" if <1 but I have some strange issue. Hope someone can help me! The problem is: The truth value of a Series is ambiguo...
Problem with If- Else Conditiones, How can I resolve it?
The problem is that I want that the code shows the graph if the Value of "Recordinaciones" is > 1, and shows "No hay Recorinaciones Dobles" if <1 but I have some strange issue. Hope someone can help me! The problem is: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Here ...
[ "try this:\nRecoordinaciones = rcs.loc[rcs['Recordinaciones'] > 1]['Recordinaciones'].tolist()\n\nif len(Recoordinaciones) == 0:\n print('no values >1')\nelse:\n for r in Recoordinaciones: \n print(r)\n\nbasically the loc function receives a condition with a boolean outcome and locates the rows where t...
[ 0 ]
[]
[]
[ "if_statement", "pandas", "python" ]
stackoverflow_0074523120_if_statement_pandas_python.txt
Q: Convert a list of strings to a list of [0.0 or 1.0] I have couple of lists and one of them looks like this : ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27', ...] with 100 shapes in the list. If the shape number is even, then convert it to 0.0, which is a float number. If the shape number is odd,...
Convert a list of strings to a list of [0.0 or 1.0]
I have couple of lists and one of them looks like this : ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27', ...] with 100 shapes in the list. If the shape number is even, then convert it to 0.0, which is a float number. If the shape number is odd, then convert it to 1.0, which is also a float number. Th...
[ "input_list = ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27']\n\n\ndef converter(s: str) -> float:\n shape_length = len('SHAPE')\n substr = s[shape_length:]\n try:\n shape_integer = int(substr)\n except ValueError:\n raise ValueError(f'failed to extract integer value fro...
[ 2, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074523217_list_python.txt
Q: Collect multiple values out of JSON file via API in python, where some values can be none / [] I want to extract the values of scientific publications from the openalex API. However, since this API does not have complete values for all publications, the resulting JSON file is not always complete. If the file is co...
Collect multiple values out of JSON file via API in python, where some values can be none / []
I want to extract the values of scientific publications from the openalex API. However, since this API does not have complete values for all publications, the resulting JSON file is not always complete. If the file is complete, my code will run without issues. If the API does not have all information available, it can ...
[ "Check for the existence of values before attempting to access them:\ndef parse_json(response):\n charlist = []\n pupdate = display_name = None\n if data['results']:\n pupdate = data['results'][0].get('publication_date')\n display_name = data['results'][0].get('display_name')\n for item in...
[ 0 ]
[]
[]
[ "api", "json", "python", "python_jsons", "python_requests" ]
stackoverflow_0074522684_api_json_python_python_jsons_python_requests.txt
Q: Color problem with Log transform to brighten dark area. Why and how to fix? So I try to enhance this image by applying log transform on it original image The area where there are bright white color turns into color blue on the enhanced image. enhanced image path = '...JPG' image = cv2.imread(path) c = 255 / np.log...
Color problem with Log transform to brighten dark area. Why and how to fix?
So I try to enhance this image by applying log transform on it original image The area where there are bright white color turns into color blue on the enhanced image. enhanced image path = '...JPG' image = cv2.imread(path) c = 255 / np.log(1 + np.max(image)) log_image = c * (np.log(image + 1)) # Specify the data t...
[ "Same cause for the two problems\nNamely this line\nlog_image = c * (np.log(image + 1))\n\nimage+1 is an array of np.uint8, as image is. But if there are 255 components in image, then image+1 overflows. 256 are turned into 0. Which lead to np.log(imag+1) to be log(0) at this points. Hence the error.\nAnd hence the ...
[ 3 ]
[]
[]
[ "image_enhancement", "image_processing", "numpy", "opencv", "python" ]
stackoverflow_0074523327_image_enhancement_image_processing_numpy_opencv_python.txt
Q: how can we make many different kv files and import all the required widget in one main kv file so to modularize the code as you can see in the above images I am make two different screens in .kv files so suppose I have more screens and I don't want to make mess in the same .kv files so like is there a way we can w...
how can we make many different kv files and import all the required widget in one main kv file so to modularize the code
as you can see in the above images I am make two different screens in .kv files so suppose I have more screens and I don't want to make mess in the same .kv files so like is there a way we can write these aboutScreen and HomeScreen in different .kv file and than import it to one .kv file for code modularization. I tri...
[ "Here is an example:\nkivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget error\nYou can also split python code into separate py files as well, like screen1.kv and screen2.py. I'll give you and example if you are interested in.\n", "For my implementation of this I created a sub...
[ 0, 0 ]
[]
[]
[ "kivy", "kivy_language", "python", "python_development_mode", "user_interface" ]
stackoverflow_0074312560_kivy_kivy_language_python_python_development_mode_user_interface.txt
Q: how to segregate the column wrt certain conditions in pyspark dataframe i have a dataframe df as shown below: VehNum Control_circuit control_circuit_status partnumbers errors Flag 4234456 DOC ok A567UR Software Issue 0 4234456 DOC not_okay ...
how to segregate the column wrt certain conditions in pyspark dataframe
i have a dataframe df as shown below: VehNum Control_circuit control_circuit_status partnumbers errors Flag 4234456 DOC ok A567UR Software Issue 0 4234456 DOC not_okay A568UR Software Issue 1 4234456 DOC not_okay ...
[ "using a aggregate window with SUM() will help achieve this\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.types import *\nfrom pyspark.sql import Window\n\ndf = spark.createDataFrame(\n [\n (\"4234456\", \"DOC\", \"ok\", \"A567UR\", \"Software Issue\", 0),\n (\"4234456\", \"DOC\", \"not...
[ 1 ]
[]
[]
[ "pyspark", "python", "python_3.x" ]
stackoverflow_0074522793_pyspark_python_python_3.x.txt
Q: How to get trend component and cyclical component in one series by Python hpfilter? This is my data: Year Z-value 0 1976-01-01 9.170293 1 1977-01-01 9.130933 2 1978-01-01 9.092142 3 1979-01-01 9.179282 4 1980-01-01 9.031123 5 1981-01-01 8.899608 6 1982-01-01 8.533545 7 19...
How to get trend component and cyclical component in one series by Python hpfilter?
This is my data: Year Z-value 0 1976-01-01 9.170293 1 1977-01-01 9.130933 2 1978-01-01 9.092142 3 1979-01-01 9.179282 4 1980-01-01 9.031123 5 1981-01-01 8.899608 6 1982-01-01 8.533545 7 1983-01-01 8.648138 8 1984-01-01 8.895921 9 1985-01-01 9.035276 10 1986-01-01 ...
[ "What about:\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\ncycle, trend = sm.tsa.filters.hpfilter(df['Z-value'], 43)\n\ndf['Year'] = pd.to_datetime(df['Year'])\n\nax = plt.subplot()\n\nax.plot(df['Year'], df['Z-value'], label='Z-Value')\nax2 = ax.twinx()\n\nax2.plot(df['Year'], cycle, ls='--', lab...
[ 0 ]
[]
[]
[ "pandas", "python", "seaborn", "statsmodels" ]
stackoverflow_0074523438_pandas_python_seaborn_statsmodels.txt
Q: Why is ArgumentParser object giving None value even though arguments are being passed through shell script I am calling a python script in a shell script and passing arguments to this python job. Arguments are being loaded from a config file. The variables being called are correctly echoed when testing in the shel...
Why is ArgumentParser object giving None value even though arguments are being passed through shell script
I am calling a python script in a shell script and passing arguments to this python job. Arguments are being loaded from a config file. The variables being called are correctly echoed when testing in the shell script. The HIVE_ labelled arguments are all being marked as None in the argument parser. Shell Script set -e...
[ "This code doesn't do anything with the config file, just stores its name/path in a variable. The config needs to be read in order to use the values.\nset -e\n\nif [ ! -z \"$1\" ]\nthen\nconfig_file=\"$1\"\nelse\nconfig_file=\"./env.sh\"\nfi\n\n. \"${config_file}\"\n\n" ]
[ 0 ]
[]
[]
[ "argparse", "python", "sh" ]
stackoverflow_0074523411_argparse_python_sh.txt
Q: Is there a more efficient and less ugly way to load variable-length data into a nested data structure in Python? I have a number of HDF5 files which are saved in a hierarchical manner (i.e. multiple folders containing multiple files where the files in each folder are related - I am not referring to the hierarchica...
Is there a more efficient and less ugly way to load variable-length data into a nested data structure in Python?
I have a number of HDF5 files which are saved in a hierarchical manner (i.e. multiple folders containing multiple files where the files in each folder are related - I am not referring to the hierarchical structure of individual HDF5 files). I want to read the data (a vector) from each file and store it in a data struct...
[ "A slightly cleaner way of building a nested list of arrays is:\ndata = []\nfor dir in dir_list:\n data1 = []\n file_list = glob.glob(dir + \"/*.hdf5\")\n for file in file_list:\n with h5py.File(file, \"r\") as fid:\n data1.append(fid[\"data\"][:])\n data.append(data1)\n\nIt should do ...
[ 0 ]
[]
[]
[ "list", "nested", "numpy", "python" ]
stackoverflow_0074445746_list_nested_numpy_python.txt
Q: Using Pandas, i'm trying to keep on my DataFrame only 100 rows of each value of my column "neighborhood" I have a super large dataset that i'm trying to shrink. My idea is to keep 100 rows by neighborhood. Here's an overview of my data : index name neighborhood 0 name 1 neighborhood A 1 name 2 neighborhood A 2...
Using Pandas, i'm trying to keep on my DataFrame only 100 rows of each value of my column "neighborhood"
I have a super large dataset that i'm trying to shrink. My idea is to keep 100 rows by neighborhood. Here's an overview of my data : index name neighborhood 0 name 1 neighborhood A 1 name 2 neighborhood A 2 name 3 neighborhood B 3 name 4 neighborhood B 4 name 5 neighborhood C 5 name 6 neighborhood C ...
[ "i think, you can use groupby and *nth:\ndfx=df.groupby('neighborhood').nth[:100]\n\n", "It depends how you want to select the rows.\nfirst n with groupby.head:\nn = 100\nout = df.groupby('neighborhood').head(n)\n\nrandom n rows with groupby.sample:\nn = 100\nout = df.groupby('neighborhood').sample(n=n)\n\n" ]
[ 2, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074523564_dataframe_pandas_python.txt
Q: How to handle (complete or totally remove) incomplete trajectories drawn in a phase portrait? For the following nonlinear system xdot = x + exp(-y) ydot = -y whose phase portrait is: import numpy as np import matplotlib.pyplot as plt xvalues, yvalues = np.meshgrid(np.arange(-5, 5, 0.1), np.arange(-5, 5, 0.1)) xd...
How to handle (complete or totally remove) incomplete trajectories drawn in a phase portrait?
For the following nonlinear system xdot = x + exp(-y) ydot = -y whose phase portrait is: import numpy as np import matplotlib.pyplot as plt xvalues, yvalues = np.meshgrid(np.arange(-5, 5, 0.1), np.arange(-5, 5, 0.1)) xdot = xvalues - np.exp(-yvalues) ydot = - yvalues plt.streamplot(xvalues, yvalues, xdot, ydot, color...
[]
[]
[ "As of Matplotlib version 3.6.0, an optional parameter broken_streamlines has been added for disabling streamline breaks.\nAdding it to your snippet (and halving the density to compensate for the visual clutter) produces the following result:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nxvalues, yvalues ...
[ -1 ]
[ "matplotlib", "plot", "python" ]
stackoverflow_0074312776_matplotlib_plot_python.txt
Q: Get max value across subset of rows and compare to constant to return max in new column I am trying to create a new column in a dataframe that is the maximum value across two columns or a constant value. Whichever is the largest value will be returned to the new column. import numpy as np import pandas as pd df =...
Get max value across subset of rows and compare to constant to return max in new column
I am trying to create a new column in a dataframe that is the maximum value across two columns or a constant value. Whichever is the largest value will be returned to the new column. import numpy as np import pandas as pd df = pd.DataFrame({ 'loan_num': ['111', '333', '555', '777'], 'bllnterm': [0, 240, 360, 2...
[ "You were on the right track, you need to combine max and clip:\ndf['amtz'] = df[['bllnterm', 'amortterm']].max(axis=1).clip(lower=1)\n\nAs assign:\ndf.assign(amtz=df[['bllnterm', 'amortterm']].max(axis=1).clip(lower=1))\n\noutput:\n loan_num bllnterm amortterm amtz\n0 111 0 0 1\n1 ...
[ 2 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074523593_numpy_pandas_python.txt
Q: How to fix this strange error: "RuntimeError: CUDA error: out of memory" I successfully trained the network but got this error during validation: RuntimeError: CUDA error: out of memory A: The error occurs because you ran out of memory on your GPU. One way to solve it is to reduce the batch size until your code...
How to fix this strange error: "RuntimeError: CUDA error: out of memory"
I successfully trained the network but got this error during validation: RuntimeError: CUDA error: out of memory
[ "The error occurs because you ran out of memory on your GPU.\nOne way to solve it is to reduce the batch size until your code runs without this error.\n", "1.. When you only perform validation not training,\nyou don't need to calculate gradients for forward and backward phase.\nIn that situation, your code can be...
[ 36, 35, 32, 25, 9, 9, 3, 1, 1, 0, 0 ]
[ "I faced the same issue with my computer. All you have to do is customize your cfg file that suits your computer.Turns out my computer takes image size below 600 X 600 and when I adjusted the same in config file, the program ran smoothly.Picture Describing my cfg file\n", "For me, I deleted some files in c drive ...
[ -2, -2, -7 ]
[ "python", "pytorch" ]
stackoverflow_0054374935_python_pytorch.txt
Q: SAP, Python and PySide6 - GUI freezes when i execute another class with a long long process this is the ui_main from my python script: import ui_nova from PySide6.QtCore import (QCoreApplication, Signal, QThread, QObject, QRunnable, Slot, QThreadPool) from PySide6 import QtCore from PySide6.QtGui import * from PyS...
SAP, Python and PySide6 - GUI freezes when i execute another class with a long long process
this is the ui_main from my python script: import ui_nova from PySide6.QtCore import (QCoreApplication, Signal, QThread, QObject, QRunnable, Slot, QThreadPool) from PySide6 import QtCore from PySide6.QtGui import * from PySide6 import QtWidgets from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget) from thr...
[ "So, after much more search, i found the solution, which i think can be very usefully for everyone who use QT with SAP.\nBasicly, when you start a sap function using threading, you will receive an error about the Object SAPGUI, so the solution for this is just import pythoncom for your code and insert \"pythoncom.C...
[ 0 ]
[]
[]
[ "multithreading", "pyside", "python", "python_multithreading", "sap_gui" ]
stackoverflow_0074506815_multithreading_pyside_python_python_multithreading_sap_gui.txt
Q: Traversing though list in list python I have to see if M is in the list and if not append to list value is on the list1 = [["A", "B", "C", "D"], ["E", "F", "G", "H"], ["I", "J", "K", "L"]] I have tried: def check_if_in_list(t): for items in list1: if t in list1: Print("True") else:...
Traversing though list in list python
I have to see if M is in the list and if not append to list value is on the list1 = [["A", "B", "C", "D"], ["E", "F", "G", "H"], ["I", "J", "K", "L"]] I have tried: def check_if_in_list(t): for items in list1: if t in list1: Print("True") else: Print("False") lis...
[ "list1 = [[\"A\", \"B\", \"C\", \"D\"], [\"E\", \"F\", \"G\", \"H\"], [\"I\", \"J\", \"K\", \"L\"]]\ndef check_if_in_list(t):\n for items in list1:\n if t in items:\n print(\"True\")\n else:\n print(\"False\")\n items.append(t)\n\ncheck_if_in_list(\"M\")\nFalse\nFal...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074523677_python.txt
Q: How to get foreign key attribute (and many to many attribute) of a model instance in Django in asynchronous queries? In asynchronous queries, I want to get foreign key and many to many attributes of a model instance. In a simple example, I want to print university and courses for all instances of the model Student...
How to get foreign key attribute (and many to many attribute) of a model instance in Django in asynchronous queries?
In asynchronous queries, I want to get foreign key and many to many attributes of a model instance. In a simple example, I want to print university and courses for all instances of the model Student. models.py: from django.db import models class University(models.Model): name = models.CharField(max_length=64) c...
[ "This is the method I used to get foreign key and many to many attributes (for django 4.1 or higher).\nasync def main():\n async for student in Student.objects.all():\n\n print(student.name)\n\n university = await University.objects.aget(id=student.university_id)\n print(university.name)\n\n...
[ 0 ]
[]
[]
[ "async_await", "asynchronous", "django", "python" ]
stackoverflow_0074467521_async_await_asynchronous_django_python.txt
Q: How to generate points within rectangle, at random locations and without overlap? I have an image with width: 1980 and height: 1080. Ultimately, I want to place various shapes within the image, but at random locations and in such a way that they do not overlap. The 0,0 coordinates of the image are in the center. B...
How to generate points within rectangle, at random locations and without overlap?
I have an image with width: 1980 and height: 1080. Ultimately, I want to place various shapes within the image, but at random locations and in such a way that they do not overlap. The 0,0 coordinates of the image are in the center. Before rendering the shapes into the image (I don't need help with this), I need to writ...
[ "Assuming you simply want to randomly define non-overlapping coordinates within the confines of a maximum image size subject to not having images overlap, this might be a good solution.\nimport numpy as np \ndef locateImages(field_height: int, field_width: int, min_sep: int, points: int)-> np.array:\n h_range = ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074514089_python.txt
Q: how to make program stop with a hotkey (outside the console) I made an autoclicker and i can stop it by pressing b but only at the right timing. I didn't find anything that would allow me to stop the program by pressing a button at any time without accessing the console Here's the program: from time import sleep i...
how to make program stop with a hotkey (outside the console)
I made an autoclicker and i can stop it by pressing b but only at the right timing. I didn't find anything that would allow me to stop the program by pressing a button at any time without accessing the console Here's the program: from time import sleep import keyboard import mouse state=True while state: if keyboa...
[ "I already answered at Using a key listener to stop a loop\nYou can simply use the add_hotkey method.\nExample:\nimport keyboard\n\nstate = True\n\ndef stop():\n state = False # The function you want to execute to stop the loop\n\nkeyboard.add_hotkey(\"b\", stop) # add the hotkey\n\n" ]
[ 0 ]
[]
[]
[ "keyboard", "mouse", "python", "python_3.x" ]
stackoverflow_0074523208_keyboard_mouse_python_python_3.x.txt
Q: Python regex: looking for a regex match close to a starting point I am wondering if it is possible to looking for a regex match close to a starting point. The distance between the starting point and the match is an initial parameter. Imagine this scenario. I have an input text, a starting point and a regex like th...
Python regex: looking for a regex match close to a starting point
I am wondering if it is possible to looking for a regex match close to a starting point. The distance between the starting point and the match is an initial parameter. Imagine this scenario. I have an input text, a starting point and a regex like these: str_text = f" bla bla bla bla 12 bla blablabla@bla.com bla bla bla...
[ "One way to do this would be to use the finditer method and manually calculate which matches are closest using the api for the match objects, specifically for your problem, it seems like start would be what you want.\n" ]
[ 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0074521925_python_regex_string.txt
Q: To check whether a number is multiple of second number I want to check whether a number is multiple of second. What's wrong with the following code? def is_multiple(x,y): if x!=0 & (y%x)==0 : print("true") else: print("false") end print("A program in python") x=input("enter a number :") y...
To check whether a number is multiple of second number
I want to check whether a number is multiple of second. What's wrong with the following code? def is_multiple(x,y): if x!=0 & (y%x)==0 : print("true") else: print("false") end print("A program in python") x=input("enter a number :") y=input("enter its multiple :") is_multiple(x,y) error: Type...
[ "You are using the binary AND operator &; you want the boolean AND operator here, and:\nx and (y % x) == 0\n\nNext, you want to get your inputs converted to integers:\nx = int(input(\"enter a number :\"))\ny = int(input(\"enter its multiple :\"))\n\nYou'll get a NameError for that end expression on a line, drop tha...
[ 11, 4, 0, 0 ]
[]
[]
[ "numbers", "python" ]
stackoverflow_0031449216_numbers_python.txt
Q: Use of secondary indexes in a redis database in comparison with SQL statements I'm working with a redis database. I have already implemented Python code to access the redis server. The problem is that the code implemented is very complex and it is not easy maintainable. Secondary indexes in Redis database To simpl...
Use of secondary indexes in a redis database in comparison with SQL statements
I'm working with a redis database. I have already implemented Python code to access the redis server. The problem is that the code implemented is very complex and it is not easy maintainable. Secondary indexes in Redis database To simplify the question I suppose that in my database are present a set of 4 keys inserted ...
[ "\nThis is the first time that I use Redis and if I compare it to the SQL query I think that its usage it is more complex respect of a SQL database\n\nIndeed: Redis' main goal is performance and its data structures and commands are designed with that in mind. There are no native secondary indexes in Redis, as keepi...
[ 1 ]
[]
[]
[ "database", "python", "redis", "sql" ]
stackoverflow_0074520451_database_python_redis_sql.txt
Q: python opencv videoWriter fps rounding I am trying to measure some event in an input video file: "test.mp4". This is done by processing the video in several steps, where each step performs some operations on the video data and writes the intermediate results to a new video file. The fps of the input video is: 29....
python opencv videoWriter fps rounding
I am trying to measure some event in an input video file: "test.mp4". This is done by processing the video in several steps, where each step performs some operations on the video data and writes the intermediate results to a new video file. The fps of the input video is: 29.42346629489295 fps Below I have written a sc...
[ "OpenCV uses some toolkit to do the writing. In my case, on iOS, OpenCV uses the native AVFoundation library. It seems AVFoundation (or the OpenCV api) can't handle well an fps value with many significant digits, like 29.7787878779, and something was being rounded incorrectly either in OpenCV's api or AVFoundation....
[ 0, 0 ]
[]
[]
[ "frame_rate", "mp4", "opencv", "python", "video_encoding" ]
stackoverflow_0049654051_frame_rate_mp4_opencv_python_video_encoding.txt
Q: Plotly: Select data with multiple dropdown menus from dataframe I want to create an interactive figure with plotly graph objects, where I can select the data from two dropdown menus. The menus should select the specific data from a dataframe. My dataframe looks like this: mode y x1 x2 0 A 3 0 6 ...
Plotly: Select data with multiple dropdown menus from dataframe
I want to create an interactive figure with plotly graph objects, where I can select the data from two dropdown menus. The menus should select the specific data from a dataframe. My dataframe looks like this: mode y x1 x2 0 A 3 0 6 1 A 4 1 7 2 A 2 2 8 3 B 1 3 9 4 B 0 4 ...
[ "You need to add df['y'] to the arg as follows:\nimport pandas as pd\nimport plotly.graph_objects as go\n\ndata = {'mode': [\"A\", \"A\", \"A\", \"B\", \"B\", \"B\"],'y': [3, 4, 2, 1, 0, 5], 'x1': [0, 1, 2, 3, 4, 5], 'x2': [6, 7, 8, 9, 10, 11]}\ndf = pd.DataFrame.from_dict(data)\n\nfig = go.Figure()\nfig.add_trace(...
[ 0 ]
[]
[]
[ "drop_down_menu", "pandas", "plotly", "python" ]
stackoverflow_0074519638_drop_down_menu_pandas_plotly_python.txt
Q: Language detection using deepl's python library Is there a way to use the deepl Python client library (or raw API) to detect the source language (without translating it)? The marketing blurb on the API website says, detection is available but I can't find it anywhere in the library or API. A: Currently, our API ...
Language detection using deepl's python library
Is there a way to use the deepl Python client library (or raw API) to detect the source language (without translating it)? The marketing blurb on the API website says, detection is available but I can't find it anywhere in the library or API.
[ "Currently, our API does not support \"just\" detecting the language. Our recommendation would be to try translating a small part of the sentence and use the detected language from the response.\nEven if we had a separate /detectLanguage endpoint, using it would be similar to this approach as you had to send some t...
[ 2, 0 ]
[]
[]
[ "deepl", "python" ]
stackoverflow_0074420850_deepl_python.txt
Q: Optimal way to edit and replace value in a row for a datetime format I have a datetime format which am trying to use for one of my requirement. Here is my code and this is how the input dataframe looks like- data=pd.DataFrame({'A': ['abc','bcd'], 'B': [pd.to_datetime('1/1/18 0:00'), 'apples'], 'C':[pd.to_datetime(...
Optimal way to edit and replace value in a row for a datetime format
I have a datetime format which am trying to use for one of my requirement. Here is my code and this is how the input dataframe looks like- data=pd.DataFrame({'A': ['abc','bcd'], 'B': [pd.to_datetime('1/1/18 0:00'), 'apples'], 'C':[pd.to_datetime('1/2/18 0:00'),'mangoes'], 'D':[pd.to_datetime('1/3/18 0:00'),'orange'],'E...
[ "a way to make your dataframe a little bit more accessible might be to transpose it so you have an actual date column:\ndf_new = df.drop(columns=['A']).T.copy()\ndf_new.rename(columns={0: 'Date', 1: 'Fruit'}, inplace=True)\ndf_new['Date_str'] = df_new['Date'].dt.strftime('%m/%Y')\n\nthis will give you a date column...
[ 1 ]
[]
[]
[ "dataframe", "datetime", "for_loop", "lines_of_code", "python" ]
stackoverflow_0074523774_dataframe_datetime_for_loop_lines_of_code_python.txt
Q: Creating scipy.stats random variable subclass does not result in expected object type I am trying to extend scipy.stats.rv_discrete to provide some simple distributions for the user. For example, in the simplest case they might want a distribution with a constant output. Here's my code for that: from scipy.stats._...
Creating scipy.stats random variable subclass does not result in expected object type
I am trying to extend scipy.stats.rv_discrete to provide some simple distributions for the user. For example, in the simplest case they might want a distribution with a constant output. Here's my code for that: from scipy.stats._distn_infrastructure import rv_sample class const(rv_sample): # a distribution with proba...
[ "This issue is not able to be worked around at the moment, but is part of an overhaul of scipy's distributions as being tracked here: https://github.com/scipy/scipy/issues/15928\n" ]
[ 0 ]
[]
[]
[ "class", "python", "scipy", "statistics" ]
stackoverflow_0060981879_class_python_scipy_statistics.txt
Q: from PIL import Image - DLL load failed while importing _imaging I'm on windows 10 using Python 3.9.12 and pillow-9.3.0 and having some issues while trying to use from PIL import Image. Error i'm getting is: ImportError: DLL load failed while importing _imaging: The specified module could not be found. Anyone has ...
from PIL import Image - DLL load failed while importing _imaging
I'm on windows 10 using Python 3.9.12 and pillow-9.3.0 and having some issues while trying to use from PIL import Image. Error i'm getting is: ImportError: DLL load failed while importing _imaging: The specified module could not be found. Anyone has an idea how to resolve? reinstalled Python 3.9.12 tried installing / u...
[ "Update your python version to 3.11\nBecause Pillow 3.9.0 was builted with python 3.11 beta\nIf you're using chocolatey as package manager use\n$ choco upgrade python -y\n\nIf you're not using a package manager, download and install python from official site\n" ]
[ 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0074523787_python_python_imaging_library.txt
Q: find specific numbers in a sequence Hi I'd like to understand how in the following python program to proceed to add "the latest added number" and the "count of numbers that were added". the output should be like [121 21 11], the code gives 121 but how do I get the other two? sum = 0 k = 1 while sum <= 100: sum =...
find specific numbers in a sequence
Hi I'd like to understand how in the following python program to proceed to add "the latest added number" and the "count of numbers that were added". the output should be like [121 21 11], the code gives 121 but how do I get the other two? sum = 0 k = 1 while sum <= 100: sum = sum + k k = k + 2 print(sum) I don't ...
[ "First off, \"sum\" is a built-in function, so you should not use it as a variable name.\nNext, you can easily build a list of your nums making it easy to get sum, count, last, etc.\nnums = [1]\nwhile sum(nums) <= 100:\n nums.append(nums[-1]+2)\n\nprint(sum(nums), nums[-1], len(nums))\n121 21 11\n\n", "you sho...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074523916_python.txt
Q: How generate all combinations of a binary array without repeating I am trying to generate an array of all combinations of an array, but how can I generate without repeating. My first solution was just remove the repeating elements using some for, but I am dealing with big arrays, with 50 length size or more and th...
How generate all combinations of a binary array without repeating
I am trying to generate an array of all combinations of an array, but how can I generate without repeating. My first solution was just remove the repeating elements using some for, but I am dealing with big arrays, with 50 length size or more and the execution never end. ex: (0,0,1,0) [1,0,0,0] [0,1,0,0] [0,0,1,0] [0,0...
[ "If your array is really just 0s and 1s, another possibility is to use itertools.combinations to determine, where the 1s are in every combination. Example:\nfrom itertools import combinations\n\narray = [0,0,1,1,0,1,0,1,0,0,1,0,1,0,1]\nn = len(array)\nk = sum(array)\n\nfor comb in combinations(range(n), k): # Any c...
[ 3, 0, 0 ]
[]
[]
[ "combinations", "python" ]
stackoverflow_0074523662_combinations_python.txt
Q: Is it possible to do this in class...? I want to know if it's possible to do this in beautifulsoup, look at the class. city = soup.find_all("div", class_="pizdz") s =0 For I in city: C= I.find("a", class="pizdz_{s}") s += 1 I tried to do that, but it didn't work. Can you do the same but in a diff...
Is it possible to do this in class...?
I want to know if it's possible to do this in beautifulsoup, look at the class. city = soup.find_all("div", class_="pizdz") s =0 For I in city: C= I.find("a", class="pizdz_{s}") s += 1 I tried to do that, but it didn't work. Can you do the same but in a different way?
[ "Use an f-string to substitute the variable. And you need to use class_.\nfor s, I in enumerate(city):\n C = I.find(\"A\", class_=f\"pizdz_{s}\")\n\nYou can use enumerate() instead of incrementing s in your own code.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x" ]
stackoverflow_0074524040_beautifulsoup_python_python_3.x.txt
Q: Code completion not giving recommendations Say I'm working with the 'requests' Python library. req = requests.get("http://google.com") Now after this, if I type req., I'm supposed to get a list of all methods I can access. But for some reason I don't, even if I manually press Ctrl+Space. If I try this in iPython,...
Code completion not giving recommendations
Say I'm working with the 'requests' Python library. req = requests.get("http://google.com") Now after this, if I type req., I'm supposed to get a list of all methods I can access. But for some reason I don't, even if I manually press Ctrl+Space. If I try this in iPython, I get autocomplete recommendations. Even if I t...
[ "As Python is a dynamically typed language, you need to ensure it can work out what type things are, and inspect on the libraries on your system correctly. Try to make sure it's obvious what type the object is in your code.\nOne good way as of PyCharm 2.7 (back when versions were numbers) is to enable runtime type ...
[ 23, 8, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "autocomplete", "pycharm", "python" ]
stackoverflow_0015022804_autocomplete_pycharm_python.txt
Q: Errors installing pygraphviz on mac os 11.6 I'm trying to install pygraphviz in order to get layouts for my network. However, I have trouble installing pygraphviz using pip install pygraphviz. I get the following lengthy error: ERROR: Command errored out with exit status 1: command: /opt/anaconda3/bin/python -u...
Errors installing pygraphviz on mac os 11.6
I'm trying to install pygraphviz in order to get layouts for my network. However, I have trouble installing pygraphviz using pip install pygraphviz. I get the following lengthy error: ERROR: Command errored out with exit status 1: command: /opt/anaconda3/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0...
[ "PyGraphviz requires the graphviz library to be installed. The easiest way to do this is probably to use homebrew, as described in the macOS section of the PyGraphviz installation docs.\n", "I had the same problem, however direct recommendations are not working properly.\nSo, the sequence is the following:\n\nbre...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0070151897_python.txt
Q: Read matrix from txt file in Python (no numpy) using function I am beginner and trying to Read a matrix from a text file and return it and use function read_matrix(pathname) but all that I can find and build it and it does not work. Can you help me understand where I did wrong. Please no numpy def read_matrix(path...
Read matrix from txt file in Python (no numpy) using function
I am beginner and trying to Read a matrix from a text file and return it and use function read_matrix(pathname) but all that I can find and build it and it does not work. Can you help me understand where I did wrong. Please no numpy def read_matrix(pathname): matrices=[] m=[] for line in file("matrix.txt",'r'): if l...
[ "if your file looks like this:\ndata.txt:\n\n1 2 3\n4 5 6\n7 8 9\n\nyou can read it to a matrix (list of lists) as follow:\nwith open(\"data.txt\") as fid:\n txt=fid.read()\n\n\nmatrix = [[int(val) for val in line.split()] for line in txt.split('\\n') if line]\n\nyour code could work as follow, however there are...
[ 1 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0074524004_matrix_python.txt
Q: What is the most Pythonic way to dynamically create a DataFrame containing person age in month? I have a list of people with their firstname, lastname and their date of birth in a DataFrame. data = [ ["John", "Wayne", "13.12.2018"], ["Max", "Muster", "02.06.2016"], ["Steve", "Black", "11.04....
What is the most Pythonic way to dynamically create a DataFrame containing person age in month?
I have a list of people with their firstname, lastname and their date of birth in a DataFrame. data = [ ["John", "Wayne", "13.12.2018"], ["Max", "Muster", "02.06.2016"], ["Steve", "Black", "11.04.2017"], ["Amy", "Smith", "10.10.2017"], ["July", "House", "08.05.2018"], ["Anna"...
[ "You can try to vectorize all you operations using numpy broadcasting:\nmonths = pd.date_range(\"2022-01-01\", \"2022-12-01\", freq=\"ME\")\n\nidx = pd.MultiIndex.from_frame(people[['first', 'last']])\n\nout = (pd.DataFrame(\n months.to_numpy() -\n people[['birthdate']].to_numpy(),\n index=idx,\n columns=months.str...
[ 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074523929_dataframe_pandas_python.txt
Q: Recommended way to install and update packages from different channels in conda Conda does a good job explaining what are channels and how to use them. However, I never know what to do when I want to install packages from different channels. For example, most packages recommend installation via the conda-forge (i....
Recommended way to install and update packages from different channels in conda
Conda does a good job explaining what are channels and how to use them. However, I never know what to do when I want to install packages from different channels. For example, most packages recommend installation via the conda-forge (i.e. xarray). However, I occasionally encounter a package that uses a different channel...
[ "There are a few ways to install packages from different channels. One way is to use the --channel option with the conda install command. For example, to install the xarray package from the conda-forge channel, you would use the following command:\nconda install --channel conda-forge xarray\n\nAnother way to instal...
[ 1 ]
[]
[]
[ "conda", "python" ]
stackoverflow_0074265336_conda_python.txt
Q: How to extract specific data in Python from a REST API request I'm using a REST API from RapidApi, and I succeded in printing the whole response, but I need only some specific parameters. Like, to print only the Deprature and Arrival times. When using params:{} it doesn't help, because that prints every parameter ...
How to extract specific data in Python from a REST API request
I'm using a REST API from RapidApi, and I succeded in printing the whole response, but I need only some specific parameters. Like, to print only the Deprature and Arrival times. When using params:{} it doesn't help, because that prints every parameter with the specified argument. I need the inverse, to print a specific...
[ "Try parsing the output using the xml.etree.ElementTree package. From there, you should be able to search through your xml tree to find the relevant data and display it however you wish.\nHere's a snippet to get you started:\n# create element tree object\ntree = ET.parse(xmlfile)\n \n# get root element\nroot = tr...
[ 1, 0 ]
[]
[]
[ "api", "python", "request", "rest" ]
stackoverflow_0074501243_api_python_request_rest.txt
Q: Is it impossible developing with fastApi, uvloop, windows? I'm learning fastapi from Youtube class I succeeded. except for the [uvloop] module I realized that uvloop doesn't install in windows and my development environment is Windows + PyCharm. How are others using this module? Are they only using mac? What shoul...
Is it impossible developing with fastApi, uvloop, windows?
I'm learning fastapi from Youtube class I succeeded. except for the [uvloop] module I realized that uvloop doesn't install in windows and my development environment is Windows + PyCharm. How are others using this module? Are they only using mac? What should I do? Should I view other videos or remove uvloop? or replace ...
[ "Fastapi itself does not depend on uvloop. The transient extra dependency UVIcorn installed with ao called standard extras however does. However, UVicorn[standard] is just an extra dependency and not a required one. So if you just install fastapi without any extras and uvicorn without extras you should be good to g...
[ 1, 0 ]
[]
[]
[ "python", "uvloop" ]
stackoverflow_0070731019_python_uvloop.txt
Q: How to get XPATH elements that have different endings? I am trying to add each product to cart by going with the click over the product and then click the button add product to cart from this site https://www.bershka.com/ro/femeie/accesorii/%C8%99osete-c1010194004.html from selenium import webdriver from selenium....
How to get XPATH elements that have different endings?
I am trying to add each product to cart by going with the click over the product and then click the button add product to cart from this site https://www.bershka.com/ro/femeie/accesorii/%C8%99osete-c1010194004.html from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdri...
[ "Assuming the code from your previous answer, let actions be defined as:\nactions = ActionChains(driver)\n\nDepending on your geographical IP address, you might need:\ntry:\n wait.until(EC.element_to_be_clickable((By.XPATH, '//span[@class=\"bskico-cancel-16\"]'))).click()\n print('removed location popup')\nex...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "web_scraping" ]
stackoverflow_0074523803_python_selenium_selenium_chromedriver_web_scraping.txt
Q: How to nest a json object into an empty json object to create a geojson file? I'm trying to create a geojson file. I have a list of objects and their coordinates in an excel file. I brought in that information into a pandas dataframe and am trying to loop through the records to create a geojson file. I mostly have...
How to nest a json object into an empty json object to create a geojson file?
I'm trying to create a geojson file. I have a list of objects and their coordinates in an excel file. I brought in that information into a pandas dataframe and am trying to loop through the records to create a geojson file. I mostly have everything working but I'm trying to match the schema of geojson.io so I can open ...
[ "I figured it out! I just needed to discover the geojson package.\n\n" ]
[ 0 ]
[]
[]
[ "geojson", "json", "python" ]
stackoverflow_0074523714_geojson_json_python.txt
Q: Mass converting .doc files to .docx i have around 1.2 Million .doc Files (all around 50kb big) in need of conversion to .docx. So far i tried using Word via win32com interface for Python, but it is really really slow (1-2 Files per Second). Is there any faster way to accomplish this? Edit: Code im using so far: de...
Mass converting .doc files to .docx
i have around 1.2 Million .doc Files (all around 50kb big) in need of conversion to .docx. So far i tried using Word via win32com interface for Python, but it is really really slow (1-2 Files per Second). Is there any faster way to accomplish this? Edit: Code im using so far: def convert_doc_to_docx(): dir = "sampl...
[ "As other commenters have suggested wordconv seems to be a good solution and much faster than using win32com. For ~1700 files transfer time was ~389 seconds or about ~.21 seconds per object. This time largely can depend on your system hardware since it is involving a lot of read and write operations as well as some...
[ 1 ]
[]
[]
[ "ms_word", "python" ]
stackoverflow_0074521779_ms_word_python.txt
Q: Calculate the difference between two list, and store the result in a third list. Python How would I calculate the difference between two separate list and store them in a third list. for example... list_1 [('M', 4000.0), ('R', 5320.0)] list_2 [('M', 4222.0), ('R', 5442.0)] I tried the following list_3 = [] list_...
Calculate the difference between two list, and store the result in a third list. Python
How would I calculate the difference between two separate list and store them in a third list. for example... list_1 [('M', 4000.0), ('R', 5320.0)] list_2 [('M', 4222.0), ('R', 5442.0)] I tried the following list_3 = [] list_3.append([list_1] - [list_2]) print(list_3) but I'm met with, a TypeError TypeError: unsupp...
[ "This seems like something better suited to a dictionary\ndict_1 = {'M': 4000.0, 'R': 5320.0}\ndict_2 = {'M': 4222.0, 'R': 5442.0}\n\ndict_3 = {}\ndict_3['M'] = dict_1['M'] - dict_2['M']\ndict_3['R'] = dict_1['R'] - dict_2['R']\n\nIf you're set on using a list of tuples you could do something with\ntuple(map(operat...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074523987_list_python.txt
Q: Pandas - Conditionally finding max of row according to column value while maintaining index order I'm trying to find, hopefully, a one lines to accomplish the following: I have the following dataframe: import pandas as pd import numpy as np SIZE = 10 df = pd.DataFrame({'col1': np.random.randint(100, size=SIZE), ...
Pandas - Conditionally finding max of row according to column value while maintaining index order
I'm trying to find, hopefully, a one lines to accomplish the following: I have the following dataframe: import pandas as pd import numpy as np SIZE = 10 df = pd.DataFrame({'col1': np.random.randint(100, size=SIZE), 'col2': np.random.randint(100, size=SIZE), 'col3': np.random.randi...
[ "There might be a better option... but this does the job by simply applying your rule as a lambda row-wise:\ndf.apply(lambda x: x[[\"col2\", \"col3\"]].max() if x[\"col4\"] else x[\"col1\"], axis=1)\n\n", "A vectorial way would be:\nout = df['col1'].where(df['col4'].eq(0), df[['col2', 'col3']].max(axis=1))\n\nOr:...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074523898_dataframe_pandas_python.txt
Q: remove  from python pandas dataframe I'm trying to remove  and » from a column in a pandas dataframe. it would look something like this: | special_character | | mobileapps (new ad unit) » en-ca » alerts » severe-outlookdesktop | | mobileapps (new a...
remove  from python pandas dataframe
I'm trying to remove  and » from a column in a pandas dataframe. it would look something like this: | special_character | | mobileapps (new ad unit) » en-ca » alerts » severe-outlookdesktop | | mobileapps (new ad unit) » fr-ca » alerts » (video) » vi...
[ "You can add regex\ndf9['special_character_remove']= df9['special_character'].replace({'Â': ' ','»': ' '},regex=True)\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074524325_pandas_python.txt
Q: Can pandas read and archive within an archive? I have an archive file (archive.tar.gz) which contains multiple archive files (file.txt.gz). If I first extract the .txt.gz files to a folder, I can then open them with pandas directly using: import pandas as pd df = pd.read_csv('file.txt.gz', sep='\t', encoding='utf...
Can pandas read and archive within an archive?
I have an archive file (archive.tar.gz) which contains multiple archive files (file.txt.gz). If I first extract the .txt.gz files to a folder, I can then open them with pandas directly using: import pandas as pd df = pd.read_csv('file.txt.gz', sep='\t', encoding='utf-8') But if I explore the archive using the tarfile...
[ "When you open the file by filename, then Pandas will be able to infer that it is compressed with gzip due to the *.gz extension on the filename.\nWhen you pass it a file object, you need to tell it explicitly about the compression so that it can decompress it as it reads the file.\nThis should work:\ndf = pd.read_...
[ 3, 0, 0 ]
[]
[]
[ "pandas", "python", "tarfile" ]
stackoverflow_0060346002_pandas_python_tarfile.txt
Q: How to do a function in python that loops through two or more data frames of different sizes and indexes in pandas? I am looking to create a function that loops through two existing dataframes I have based on some conditions and generates a value relating to those variables. Forgive the wording but for those famil...
How to do a function in python that loops through two or more data frames of different sizes and indexes in pandas?
I am looking to create a function that loops through two existing dataframes I have based on some conditions and generates a value relating to those variables. Forgive the wording but for those familiar with excel the problem would be solved with index match and then normal equations within parentheses. The excel solut...
[ "Your data is structured in 'wide' format which is a bit of an anti-pattern. (It's worth reading up on 'third normal form' - might seem in the weeds but it's one of those foundational concepts in relational/tabular data).\nSo step 1 should be getting it into a standard form (where each row is a unique 'value' with ...
[ 1 ]
[]
[]
[ "excel", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074522391_excel_jupyter_notebook_pandas_python.txt
Q: Segmentation fault (core dumped) when launching python in anaconda When I tried to create a virtual environment using miniconda command 'conda create -n py37 python=3.7', I encountered some problem when I tried to launch python in the virtual environment using command 'python'. It seems python cannot be launched a...
Segmentation fault (core dumped) when launching python in anaconda
When I tried to create a virtual environment using miniconda command 'conda create -n py37 python=3.7', I encountered some problem when I tried to launch python in the virtual environment using command 'python'. It seems python cannot be launched appropriately in the terminal. The error info is listed as followed: (py3...
[ "Ran into a similar issue probably in a completely different context, but try making sure that the python you install is from conda-forge or not the main conda channel. e.g.\nconda create -n py10_test -c conda-forge -y python==3.10\nI found this worked for me.\n" ]
[ 0 ]
[]
[]
[ "anaconda", "miniconda", "python" ]
stackoverflow_0074367207_anaconda_miniconda_python.txt