content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: how to activate virtualenv created by pyenv in bash script? I need to write a script to start gunicorn + django site which developed with pyenv the script is something like #!/bin/bash pyenv activate .ve pyenv exec gunicorn config.wsg...
how to activate virtualenv created by pyenv in bash script?
I need to write a script to start gunicorn + django site which developed with pyenv the script is something like #!/bin/bash pyenv activate .ve pyenv exec gunicorn config.wsgi:application --name mini2 --workers 8 \ --workers 8 --bind=unix:...
[ "There is no need to pyenv activate the virtual environment in your script. Because of how virtual environments work [1], you need only use the absolute path to the Python interpreter binary. You can confirm this path using $ pyenv which python whilst your environment is activated. The most substantive thing that p...
[ 1, 1 ]
[]
[]
[ "bash", "pyenv", "python" ]
stackoverflow_0070241560_bash_pyenv_python.txt
Q: Scraping Google App All Reviews using Selenium and Python I want to scrape all reviews from google play store for a particular app. I have prepared following script: # App Reviews Scraper import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome ...
Scraping Google App All Reviews using Selenium and Python
I want to scrape all reviews from google play store for a particular app. I have prepared following script: # App Reviews Scraper import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup url ...
[ "wait=WebDriverWait(driver,1)\n\n\ntry:\n wait.until(EC.element_to_be_clickable((By.XPATH,\"//span[text()='Show More']\"))).click()\nexcept:\n continue\n\nJust add this to check for the show more element in your infinite scroll.\nImport:\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.su...
[ 0, 0, 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0070322053_python_selenium_web_scraping.txt
Q: Sum of column in Python I would like a code to create a bar chart that displays the sum of the total number of orders per year. My data available are as follows: A column with the order number (ORDERNUMBER), a column with the corresponding year of the order (YEAR_ID). How to display the sum of the number of orders...
Sum of column in Python
I would like a code to create a bar chart that displays the sum of the total number of orders per year. My data available are as follows: A column with the order number (ORDERNUMBER), a column with the corresponding year of the order (YEAR_ID). How to display the sum of the number of orders, for each year ? Thanks, for...
[ "This gives you a table which shows the sum and mean order numbers per year, based on some random data.\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(columns=['ORDERNUMBER', 'YEAR_ID'])\ndf['ORDERNUMBER'] = [1,2,3]*10\ndf['YEAR_ID'] = [2000, 2001, 2030] * 10\n\ndf.groupby(by='YEAR_ID').agg([np.sum, ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074287583_python.txt
Q: sqlite3 is giving me (type,) instead of "type" My Sqlite3 database is giving me (type,) instead of "type" when I'm trying to print something in the database (note that the "type" thing is from the database) here's my code : c.execute("SELECT type FROM accounts") acctype = c.fetchall() print(acctype[0])...
sqlite3 is giving me (type,) instead of "type"
My Sqlite3 database is giving me (type,) instead of "type" when I'm trying to print something in the database (note that the "type" thing is from the database) here's my code : c.execute("SELECT type FROM accounts") acctype = c.fetchall() print(acctype[0]) the output is (type,)
[ "acctype is a list of tuples so:\nprint(acctype[0][0])\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074290022_python_sqlite.txt
Q: How to connect to cassandra nodes created by docker-compose via python datastax I am using the following .yaml file to create a 2 node Cassandra cluster. version: "3.3" networks: cassandra: volumes: cassandra_seed_data: cassandra_node_data: services: cassandra-seed: image: cassandra:3.11 restart:...
How to connect to cassandra nodes created by docker-compose via python datastax
I am using the following .yaml file to create a 2 node Cassandra cluster. version: "3.3" networks: cassandra: volumes: cassandra_seed_data: cassandra_node_data: services: cassandra-seed: image: cassandra:3.11 restart: "no" logging: options: max-size: "5m" max-file: "3" co...
[ "Do you run your python from a container on the same network as the cluster?\nCan you try using a container name instead of the contact point, for example:\ncluster = Cluster(['containerName'], port=9042)...\n\nYou could also try the following with the container name and use that IP instead in your code:\ndocker in...
[ 0 ]
[]
[]
[ "cassandra_3.0", "datastax", "docker_compose", "python" ]
stackoverflow_0074288965_cassandra_3.0_datastax_docker_compose_python.txt
Q: how to add playwright docker image to docker compose? I am building Django app where I want to run Django and playwright images in 1 container in Docker Desktop (locally). Below you can see my docker-compose.yml file: version: '3.8' services: web: build: ./docker_playwright_test command: python manage.p...
how to add playwright docker image to docker compose?
I am building Django app where I want to run Django and playwright images in 1 container in Docker Desktop (locally). Below you can see my docker-compose.yml file: version: '3.8' services: web: build: ./docker_playwright_test command: python manage.py runserver 0.0.0.0:8000 volumes: - ./docker_play...
[ "Step 1: make sure you're in Linux Container in Docker.\nStep 2: Go to C:\\Users\\[User Name]\\.docker\\config.json\nReplace credsStore to credStore\nStep 3: create Dockerfile, .dockerignore and docker-compose.yml file\nStep 4: docker-compose format.\nversion: \"3.9\"\nservices:\nfrontend:\nbuild: .\nports:\n - \"...
[ 4, 3 ]
[]
[]
[ "django", "docker", "docker_compose", "playwright", "python" ]
stackoverflow_0074289437_django_docker_docker_compose_playwright_python.txt
Q: Using class and lists in a very specific instance and adding the properties of a class in the list of another class #so basically I have set up both of my classes here: class item(): def __init__(self, name, value): self.name = name self.value = value class person(): def __init__(self, nam...
Using class and lists in a very specific instance and adding the properties of a class in the list of another class
#so basically I have set up both of my classes here: class item(): def __init__(self, name, value): self.name = name self.value = value class person(): def __init__(self, name, money): self.name = name self.money = money self.items = [] #And then I have the actual obje...
[ "I suggest a little restructuring of the code to make it a bit more OO. Then you just need a function for the Person class that will return the total value of all its Items\nclass Item():\n def __init__(self, name, value):\n self.name = name\n self.value = value\n\nclass Person():\n def __init__...
[ 0 ]
[]
[]
[ "class", "list", "python" ]
stackoverflow_0074289792_class_list_python.txt
Q: Keep first instance of duplicate column name, unless empty then keep second instance of column I have a dataframe with multiple columns, two of these columns have the same name ('mobilephone'), some values are empty, and some aren't but there will always be one of the two columns populated with a phone number: ...
Keep first instance of duplicate column name, unless empty then keep second instance of column
I have a dataframe with multiple columns, two of these columns have the same name ('mobilephone'), some values are empty, and some aren't but there will always be one of the two columns populated with a phone number: mobilephone mobilephone 0 999000111 999000111 1 ...
[ "First, find the index of the second duplicate column. Then change the name of this column and use .loc[] to fill in the gaps:\ncol_name = 'mobilephone'\nindex_second_column = np.where(df.columns.duplicated())[0][0]\ndf.columns.values[index_second_column] += '_1'\n\ndf.loc[df[col_name].isnull(), colname] = df[col_n...
[ 1, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074289835_dataframe_pandas_python.txt
Q: pyqtgraph widget.addLine change color/width I want to use the widget function addLine. In my case it is as following: widget.addLine(x=None, y=0.8) #endless horizontal line Now i want to change the color and width of this line, but i cannot find a fitting function. Is there something available to do this? Additio...
pyqtgraph widget.addLine change color/width
I want to use the widget function addLine. In my case it is as following: widget.addLine(x=None, y=0.8) #endless horizontal line Now i want to change the color and width of this line, but i cannot find a fitting function. Is there something available to do this? Additional, is there a similar function to "add a circle...
[ "Changing the color and width of the line is simple enough using the mkPen() function.\nAs you have not provided all of your code here is a simple demo:\nimport pyqtgraph as pg\n\ny=[1,1,1,1,1]\npg.plot(y, pen=pg.mkPen('b', width=5))\n\nWhich draws a blue line with width 5. See the pyqtgraph documentation here\nThi...
[ 12, 0 ]
[]
[]
[ "pyqtgraph", "python" ]
stackoverflow_0041488864_pyqtgraph_python.txt
Q: Deploy a multi-threaded selenium script to heroku I have a multi-threaded selenium script that looks like so: def price_scrape(): options1 = webdriver.ChromeOptions() options1.add_experimental_option('excludeSwitches', ['enable-logging']) options1.add_argument("window-size=1920x1480") options1.add_...
Deploy a multi-threaded selenium script to heroku
I have a multi-threaded selenium script that looks like so: def price_scrape(): options1 = webdriver.ChromeOptions() options1.add_experimental_option('excludeSwitches', ['enable-logging']) options1.add_argument("window-size=1920x1480") options1.add_argument("disable-dev-shm-usage") options1.add_argu...
[ "search this : IndexError: tuple index out of range\n" ]
[ 0 ]
[]
[]
[ "heroku", "multithreading", "python", "selenium" ]
stackoverflow_0074283991_heroku_multithreading_python_selenium.txt
Q: Get selected option from Menu Tkinter I need to get selected folder number from Menu to manipulate such data next time. Tried to implement optionMenu to make program easier, but I need to create Frame, which contains several Menus. Using callback(menu) method I tried to get the number, however program prints first...
Get selected option from Menu Tkinter
I need to get selected folder number from Menu to manipulate such data next time. Tried to implement optionMenu to make program easier, but I need to create Frame, which contains several Menus. Using callback(menu) method I tried to get the number, however program prints first two numbers. from tkinter import * import ...
[ "Seems like you want to add folder as an argument to callback(), which you can pass in via the lambda\nsub_menu = Menu(menu_frame, tearoff=0)\nfor folder in folders:\n sub_menu.add_command(label=folder, command=lambda f=folder: callback(f))\n\n\ndef callback(folder):\n print(folder)\n\n" ]
[ 1 ]
[]
[]
[ "python", "tk_toolkit", "tkinter", "ttk" ]
stackoverflow_0074290187_python_tk_toolkit_tkinter_ttk.txt
Q: ImportError: No module named 'speech_recognition' in python IDLE I'm trying to use the speech recognition module with python 3.5.1 to make my jarvis AI voice activated! I have looked through stack overflow and found some questions similar to mine but they did not have the answer that i needed, i need an answer ind...
ImportError: No module named 'speech_recognition' in python IDLE
I'm trying to use the speech recognition module with python 3.5.1 to make my jarvis AI voice activated! I have looked through stack overflow and found some questions similar to mine but they did not have the answer that i needed, i need an answer individualized for this. I have downloaded all the necessary packages and...
[ "Install Speech Recognition using\n\npip install SpeechRecognition\n\n", "I upgraded my python to 3.7 in mac, but then I was facing similar issue.\n\npip3 install SpeechRecognition\n\nthis worked for me\n", "Try this in windows command prompt for python 3.7 32 bit \npython -m pip install -U pip\n\npip install w...
[ 17, 3, 2, 1, 1, 0, 0, 0, 0, 0 ]
[ "What worked for me was, I installed jupyter notebooks again and on anaconda prompt and then I executed\npip install SpeechRecognition\nfollowed by\npip install PyAudio-0.2.11-cp39-cp39-win_amd64.whl\nagain.\n", "user must be root\nso use \nsudo pip install --upgrade pip\n\nIt will work.\n" ]
[ -1, -3 ]
[ "module", "python", "speech_recognition", "speech_to_text" ]
stackoverflow_0041797920_module_python_speech_recognition_speech_to_text.txt
Q: How to compute upper bound for the absolute and relative error of an expression Let's say I have an expression such as a − πb / π^2 + b, where the value of a is approximately 1.21, approximated value of b 1.9 and π 3.14. How could I compute upper bound for the absolute and relative error for the entire expression ...
How to compute upper bound for the absolute and relative error of an expression
Let's say I have an expression such as a − πb / π^2 + b, where the value of a is approximately 1.21, approximated value of b 1.9 and π 3.14. How could I compute upper bound for the absolute and relative error for the entire expression in python? I have not been able to find any function or method to do this.
[ "You can just use the round() function.\nExample:\nround(1.4) -> 1\nround(1.6) -> 2\nround(1.9) -> 2\n\n" ]
[ 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074289635_math_python.txt
Q: django makemigrations and migrate on heroku server don't create tables Python Version 2.7 Django Version 1.9.7 I have created a Django app on heroku. I can't get the heroku server to migrate properly. In the past I have done all the makemigrations locally and then pushed them to the server. It has worked in the...
django makemigrations and migrate on heroku server don't create tables
Python Version 2.7 Django Version 1.9.7 I have created a Django app on heroku. I can't get the heroku server to migrate properly. In the past I have done all the makemigrations locally and then pushed them to the server. It has worked in the past. Now I thought I would choose to do the migrations all on the server ...
[ "I had a similar problem.\nI just ssh into heroku dyno with:\nheroku run bash ( from your heroku application folder ofc )\nThan run all the migration and makemigration commands with createsuperuser if needed.\nWorks with sqlite and postgre for me.\n", "\nRun these commands locally\n\n\npython manage.py makemigrat...
[ 26, 1, 1, 0, 0 ]
[]
[]
[ "database", "django", "heroku", "python" ]
stackoverflow_0038330432_database_django_heroku_python.txt
Q: Django Rest Framework make model calculations using pandas or not (seeking efficient way) I am using django_rest_framework for a web application. I have created the necessary API end points for all the necessary CRUD operations for the respective tables. Now I want to perform calculations on the data of multiple t...
Django Rest Framework make model calculations using pandas or not (seeking efficient way)
I am using django_rest_framework for a web application. I have created the necessary API end points for all the necessary CRUD operations for the respective tables. Now I want to perform calculations on the data of multiple tables and send the calculated result as a Response for the frontend to process. I could think o...
[ "You can do this to retrieve the objects as dataframe:\nqueryset = Costs_workspaces.objects.all()\ndf = pd.DataFrame.from_records(queryset.values())\n\nAnother example with a viewset:\nclass apiname(mixins.ListModelMixin, viewsets.GenericViewSet):\n queryset = your_model.objects.all()\n\n def list(self, reque...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "pandas", "python" ]
stackoverflow_0067368983_django_django_rest_framework_pandas_python.txt
Q: Django 3.2 update AutoField to BigAutoField backward compatibility with foreign key relations I'm running into a problem after updating my project from Django 2.2 to Django 3.2. In Django 2.2 primary keys are created using AutoField meaning in MySql they are considered int(11) and all foreign keys from this table ...
Django 3.2 update AutoField to BigAutoField backward compatibility with foreign key relations
I'm running into a problem after updating my project from Django 2.2 to Django 3.2. In Django 2.2 primary keys are created using AutoField meaning in MySql they are considered int(11) and all foreign keys from this table must also be int(11). In Django 3.2 primary keys are now created with BigAutoField which in MySql c...
[ "Would you consider updating the old database directly via the MySQL console? After that, you can add this \"old (updated)\" database to your project.\n" ]
[ 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0069993873_django_mysql_python.txt
Q: Pandas calculate the number of columns of a given name there are that have a value in a row I have this dataset where I have some columns (not important to the calculations) and then many columns with same starting name. I want to calculate the sum of those columns per one row which contains else than NaN-value. T...
Pandas calculate the number of columns of a given name there are that have a value in a row
I have this dataset where I have some columns (not important to the calculations) and then many columns with same starting name. I want to calculate the sum of those columns per one row which contains else than NaN-value. The set looks something like this: id something number1 number2 number3 number4 1 105 200 ...
[ "# filter column on 'number' and count\ndf['sum_columns']=df.filter(like='number').count(axis=1)\ndf\n\n id something number1 number2 number3 number4 sum_columns\n0 1 105 200 NaN NaN 50.0 2\n1 2 300 2 1.0 1.0 ...
[ 1, 1, 0, 0 ]
[]
[]
[ "count", "dataframe", "pandas", "python", "tablecolumn" ]
stackoverflow_0074290080_count_dataframe_pandas_python_tablecolumn.txt
Q: read csv file from user input in django ERROR : FileNotFoundError: [Errno 2] No such file or directory: '/media/tableConvert.com_v02pvt.csv' Hello there im trying to read a csv file in django backend where user upload and i dont want to save it to my DB so my best try was this : View : def view_submit_form(reque...
read csv file from user input in django
ERROR : FileNotFoundError: [Errno 2] No such file or directory: '/media/tableConvert.com_v02pvt.csv' Hello there im trying to read a csv file in django backend where user upload and i dont want to save it to my DB so my best try was this : View : def view_submit_form(request): if request.method == 'POST': ...
[ "You can read it from the request itself without saving it.\nUsing \".file\" command you can fetch the readable state of the file.\ndef view_submit_form(request):\n if request.method == 'POST':\n text = request.POST.get('smstext')\n csv_file = request.FILES.get('csv_file')\n df = pd.read_csv...
[ 3 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074289963_django_django_views_python.txt
Q: How to manipulate and return a string from a recursive function? I wrote the recursive code to get the path taken in a DFS traversal, but I want to get the output into a string variable. Recursion is not my strong suit so I'm having a lot of trouble figuring out the what to return. Here's the code I wrote for the ...
How to manipulate and return a string from a recursive function?
I wrote the recursive code to get the path taken in a DFS traversal, but I want to get the output into a string variable. Recursion is not my strong suit so I'm having a lot of trouble figuring out the what to return. Here's the code I wrote for the algorithm adj_lst = [None, [3, 4], [3], [1, 2], [1]] size = len(adj_ls...
[ "adj_lst = [None, [3, 4], [3], [1, 2], [1]]\nsize = len(adj_lst)\nvisited = [False] * size\n\ndef dfs(starting_node, a_lst, output):\n visited[starting_node] = True\n output += str(starting_node)\n\n for vertex in a_lst[starting_node]:\n if visited[vertex] == False:\n visited[vertex] = Tr...
[ 0 ]
[]
[]
[ "algorithm", "depth_first_search", "graph", "python", "recursion" ]
stackoverflow_0074290178_algorithm_depth_first_search_graph_python_recursion.txt
Q: Django Date calculation Model: class JobCycle(models.Model): dateReceived = models.DateField(blank=True, null=True) dueDate = models.DateField(blank=True, null=True) dateOut = models.DateField(blank=True, null=True) fee = models.IntegerField(blank=True, null=True) ...
Django Date calculation
Model: class JobCycle(models.Model): dateReceived = models.DateField(blank=True, null=True) dueDate = models.DateField(blank=True, null=True) dateOut = models.DateField(blank=True, null=True) fee = models.IntegerField(blank=True, null=True) def __str__(self): ...
[ "You can override the model's save() method:\nBefore or after def __str__ (in the same level) add:\ndef save(self, *args, **kwargs):\n if self.dueDate > self.dateReceived:\n raise ValidationError(\"dueDate must never be later than dateReceived!\")\n super(JobCycle, self).save(*args, **kwargs)\n\nOr, in...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0074245369_django_django_models_django_rest_framework_python.txt
Q: Writing an error statement to a dictionary using a function I want to create a function that write an error state to an error dictionary. this dictionary will be outputted as a JSON for corrections in the real dataset. The error statement must include the row number the column name and a simple sentence. import pa...
Writing an error statement to a dictionary using a function
I want to create a function that write an error state to an error dictionary. this dictionary will be outputted as a JSON for corrections in the real dataset. The error statement must include the row number the column name and a simple sentence. import pandas as pd import numpy as np data=[[np.nan, 'Indiana','test@gma...
[ "You could first get a list with index&column of NaN in required fields, then build an error message for each of them cells in a list comprehension.\nInput\ndata=[[np.nan, 'Indiana','test@gmail.com'], ['Ben', 'Alaska','test@yahoo.com'], ['Alan', 'Florida', np.nan]]\ndf=pd.DataFrame(data,columns=['Name','State','Ema...
[ 1 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074289749_dictionary_pandas_python.txt
Q: Cross Referencing dictionary Items to values in a data frame I have a dictionary with correct values that I want to be cross checked to the values found in a data frame. I want this operation to be in a function for use with other code later on. import pandas as pd d=[['Aland Islands','Cars','test@gmail.com']] df...
Cross Referencing dictionary Items to values in a data frame
I have a dictionary with correct values that I want to be cross checked to the values found in a data frame. I want this operation to be in a function for use with other code later on. import pandas as pd d=[['Aland Islands','Cars','test@gmail.com']] df=pd.DataFrame(d,columns=['country','industry','Email']) errors={}...
[ "# inver the dictionary\nd={i:k for k, v in valid_dict.items() for i in v}\n\n# map industry and when its null, return an error message\n# else the valid industry name\ndf['check']=df['industry'].mask(df['industry'].map(d).isna(), f\"An invalid Value found in {col}\")\ndf\n\ncountry industry Email check\n0...
[ 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074290354_dictionary_pandas_python.txt
Q: NumPy array output differs when using exponentiation Quick question about the output using NumPy arrays in a Jupyter notebook. I've defined a simple array arr = np.array([1, 2, 3], dtype=np.int32), and was doing a few operations just to get used to syntax and whatever, and noticed the following: In: arr * arr Out:...
NumPy array output differs when using exponentiation
Quick question about the output using NumPy arrays in a Jupyter notebook. I've defined a simple array arr = np.array([1, 2, 3], dtype=np.int32), and was doing a few operations just to get used to syntax and whatever, and noticed the following: In: arr * arr Out: array([1, 4 ,9]) In: arr * 5 Out: array([5, 10, 15]) In...
[ "TL:DR summary of the solution in the commented link provided by @user2357112 above:\nIn: arr = np.array([1, 2, 3])\n\nIn: arr.dtype.type\nOut: numpy.int32\n\nIn: (arr ** 2).dtype.type\nOut: numpy.intc\n\nIn: (arr.dtype.type) == (arr ** 2).dtype.type\nOut: False\n\nHence, the dtype is printed. This is cause of some...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074289853_arrays_numpy_python.txt
Q: How to get raid of double quotes when dumping a string that includes single quotes I am trying to add single quotes in dumping the following yaml string: yaml_str = 'Type: modified' But the output includes double quotes which are not required. Here is my code: import sys ...
How to get raid of double quotes when dumping a string that includes single quotes
I am trying to add single quotes in dumping the following yaml string: yaml_str = 'Type: modified' But the output includes double quotes which are not required. Here is my code: import sys import ruamel.yaml ...
[ "Your expectation is completely wrong, so string formatting is not going to help you at all. YAML, like many other languages need to be able to handle scalars that have embedded quotes and YAML has multiple ways to handle that:\n\nif a string to be dumped into a scalar has special characters that need backslash esc...
[ 0 ]
[]
[]
[ "python", "ruamel.yaml", "string" ]
stackoverflow_0074289484_python_ruamel.yaml_string.txt
Q: Iterate over pairs of columns and add value from one under condition in new column Python I have dataframe with steps/action in user behaviour. Sample is provided. There are many steps. Each step contains two columns: subtitle and dimension. df = pd.DataFrame({'idVisit': [1, 2, 3], 'subtitle (st...
Iterate over pairs of columns and add value from one under condition in new column Python
I have dataframe with steps/action in user behaviour. Sample is provided. There are many steps. Each step contains two columns: subtitle and dimension. df = pd.DataFrame({'idVisit': [1, 2, 3], 'subtitle (step 0)': ['download', 'homepage', 'www.example.com'], 'dimension1 (step 0)': ...
[ "Assume idVisit is the index. Then you may try .combine_first() method on every odd column (dimension) with every even one (subtitle):\n# set the index just in case\ndf.set_index('idVisit', inplace=True)\n# loop over subtitles and dimensions zipped together and enumerated\nfor n, (subtitle, dimension) in enumerate(...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074289822_dataframe_pandas_python.txt
Q: When logged in as a user, the cart does not clear after completing the transaction via paypal in my Django project. It works when not logged in I recently completed a YouTube tutorial series from Dennis Ivy on building a Django-based ecommerce website. My website works except for 1 major bug. When the user is logg...
When logged in as a user, the cart does not clear after completing the transaction via paypal in my Django project. It works when not logged in
I recently completed a YouTube tutorial series from Dennis Ivy on building a Django-based ecommerce website. My website works except for 1 major bug. When the user is logged in and goes through the checkout process, the cart does not clear after completing the paypal checkout. When the user is not logged in ("Anonymous...
[ "I believe I fixed it. The price field in the product model was a DecimalField so the total from the front end was not matching the total from the back end. I did the following and it seems to be working.\ndef processOrder(request):\n transaction_id = datetime.datetime.now().timestamp()\n data = json.loads(re...
[ 0 ]
[]
[]
[ "django", "e_commerce", "javascript", "paypal", "python" ]
stackoverflow_0074276606_django_e_commerce_javascript_paypal_python.txt
Q: Convert list to the same format as another list in python I have one matrix, matrix1 in the format I want. This matrix is dependent on two strings length. I am trying to convert matrix2 into the same format (excluding the zeros), but it does not work. string0 = "hello" string1 = "Good" matrix1 = [[[0, 0] for y in ...
Convert list to the same format as another list in python
I have one matrix, matrix1 in the format I want. This matrix is dependent on two strings length. I am trying to convert matrix2 into the same format (excluding the zeros), but it does not work. string0 = "hello" string1 = "Good" matrix1 = [[[0, 0] for y in range(len(string1)+1)] for x in range(len(string0)+1)] print(ma...
[ "Here is an idea, it might not be perfect but perhaps something you can build on.\nimport itertools\n\ndef new_matrix(arr, string):\n # Create a new single array from the matrix first using itertools\n arr = list(itertools.chain.from_iterable(arr))\n # Save the length of our string\n length = len(string...
[ 0 ]
[]
[]
[ "for_loop", "list", "loops", "matrix", "python" ]
stackoverflow_0074289326_for_loop_list_loops_matrix_python.txt
Q: How can I find the penultimate occurrence of a group of vowels in a string in python? I'm trying to find the penultimate vowel group and its index in a string. If the string only contains one vowel group than its that one. For example in the string "impeachment" it would be "ea" at the index 3 And in "warn" it wou...
How can I find the penultimate occurrence of a group of vowels in a string in python?
I'm trying to find the penultimate vowel group and its index in a string. If the string only contains one vowel group than its that one. For example in the string "impeachment" it would be "ea" at the index 3 And in "warn" it would be "a" at the index 1 I tried re.split() and find() but unfortunately these approaches e...
[ "I would do it like this:\nimport re\n\n\ndef find_penultimate_or_last_vowel_group(string):\n print(f\"Word: {string}\")\n \n matches = list(re.finditer(\"[AEIOUaeiou]+\", string))\n if not matches:\n print(\"No vowel-group found!\")\n return\n match = matches[-2] if len(matches) > 1 el...
[ 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074288225_python_string.txt
Q: pysmb listpath method return error "SMB connection not authenticated" I'm using pysmb to connect a server (192.168.1.54) the code are: host = '192.168.1.54' # server IP username = 'Test' password = 'test' my_name = "localmac" remote_name = "servermac" try: conn = SMBConnectio...
pysmb listpath method return error "SMB connection not authenticated"
I'm using pysmb to connect a server (192.168.1.54) the code are: host = '192.168.1.54' # server IP username = 'Test' password = 'test' my_name = "localmac" remote_name = "servermac" try: conn = SMBConnection(username, password, my_name, remote_name, is_direct_tcp=True) except ...
[ "1) If you are sure that the username and password correct, check the version of pysmb.\nI had similar problem with pysmb==1.2.6, so if you're using this version too, update to 1.2.8.\nThe problem was with pysmb's own implementation of MD4 algorithm.\nWhen there is no MD4 in Python's hashlib pysmb uses its own alg...
[ 0 ]
[]
[]
[ "authentication", "pysmb", "python" ]
stackoverflow_0071446275_authentication_pysmb_python.txt
Q: I can scrape a title of a single ebay listing, but am having trouble scraping every single title on the page (Python/BeautifulSoup/lxml) I am trying to scrape the title of every item on an ebay page. This is the page. I first tried to scrape the title of the first listing (lines 5-7 of my code) , and I was success...
I can scrape a title of a single ebay listing, but am having trouble scraping every single title on the page (Python/BeautifulSoup/lxml)
I am trying to scrape the title of every item on an ebay page. This is the page. I first tried to scrape the title of the first listing (lines 5-7 of my code) , and I was successful as the title of the first listing gets printed. But when I try to scrape every single title on the ebay page (lines 8-10), nothing gets pr...
[ "You're calling find(\"h3\", class_=(\"s-item__title\") on the soup every time, you need to call it on every listing in the loop or it will always fetch the first title. Also, keep in mind there were a couple of hidden results on the eBay page for whatever reason, maybe check that out and see if you want to ignore ...
[ 1, 1, 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0063623757_beautifulsoup_python_web_scraping.txt
Q: Merge two dataframes based on chronological order I have two dataframes with 2 columns, the first column is the column duration and takes float values e.g 239.4 hours and the second column is the column event and is either 0 or 1, 0 represents failure and 1 represent success. If the event value change then a new e...
Merge two dataframes based on chronological order
I have two dataframes with 2 columns, the first column is the column duration and takes float values e.g 239.4 hours and the second column is the column event and is either 0 or 1, 0 represents failure and 1 represent success. If the event value change then a new event is triggered. What I want is to track the changes ...
[ "Is this what you are trying to achieve?\nimport pandas as pd\ndf1 = pd.DataFrame({'duration': [0.06, 2340, 145], 'Event': [0, 1, 0]})\ndf2 = pd.DataFrame({'duration': [9.0, 1200, 124], 'Event': [1, 0, 1]})\ndf1.merge(df2, how = 'outer').sort_values(by = ['duration'])\n\nOutput:\n\n\n\n\n\nduration\nEvent\n\n\n\n\n...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "time" ]
stackoverflow_0074290418_dataframe_pandas_python_time.txt
Q: PyMuPDF - How to Data Extract from Unstructured PDFs using PyMuPDF in python? I am following this guide on how to extract data from Unstructured PDFs using PyMuPDF. https://www.analyticsvidhya.com/blog/2021/06/data-extraction-from-unstructured-pdfs/ I am getting an AttributeError: 'NoneType' object has no attribut...
PyMuPDF - How to Data Extract from Unstructured PDFs using PyMuPDF in python?
I am following this guide on how to extract data from Unstructured PDFs using PyMuPDF. https://www.analyticsvidhya.com/blog/2021/06/data-extraction-from-unstructured-pdfs/ I am getting an AttributeError: 'NoneType' object has no attribute 'rect' error when I followed the code and not sure what is going on since I am ne...
[ "The property first_annot of a PyMuPDF Page object either contains the first annotation or None if there are no annotations.\nThis is where your error comes from.\nBut you also seem confused about the fact, that annotations have nothing to do with a page's text - which you extract by method Page.get_text(). Using o...
[ 1, 0 ]
[]
[]
[ "csv", "pdf", "pymupdf", "pypdf2", "python" ]
stackoverflow_0074269493_csv_pdf_pymupdf_pypdf2_python.txt
Q: What is boto3.client('S3') returning? I can see: s = boto3.client('s3') print(type(s)) prints <class 'botocore.client.S3'> But if I try print(botocore.client.S3) I get AttributeError: module 'botocore.client' has no attribute 'S3' How come? Side note: My end goal is to return a mock that is speced to what bo...
What is boto3.client('S3') returning?
I can see: s = boto3.client('s3') print(type(s)) prints <class 'botocore.client.S3'> But if I try print(botocore.client.S3) I get AttributeError: module 'botocore.client' has no attribute 'S3' How come? Side note: My end goal is to return a mock that is speced to what botocore.client.S3 has to offer, but the tech...
[ "Through a bit of trial and error, found out the instance type that can be used:\n>>> import boto3\n>>> import botocore\n>>> isinstance(boto3.client('s3'), botocore.client.BaseClient)\nTrue\n\n", "There's not really a notion of printing a class object like this (they have no repr or str methods). If you want to g...
[ 12, 0, 0, 0 ]
[]
[]
[ "boto3", "python", "python_3.x" ]
stackoverflow_0051118767_boto3_python_python_3.x.txt
Q: How to perform column based replacement in python dataframe df1 Var Val1 Val2 var1 6 7 var2 5 -4 var3 -9 3 var4 3 -2 df2 var S1 S2 S3 S4 var1 1 0 0 2 var2 0 1 2 0 var3 1 0 1 2 var4 1 0 2 0 Expected outcome df3 var S1 S2 S3 S4 var1 6 0 0 7 var2 0 5 -4 0 var3 -9 0 -9 3 var4 3 0 -2 0 Dear Experts pl...
How to perform column based replacement in python dataframe
df1 Var Val1 Val2 var1 6 7 var2 5 -4 var3 -9 3 var4 3 -2 df2 var S1 S2 S3 S4 var1 1 0 0 2 var2 0 1 2 0 var3 1 0 1 2 var4 1 0 2 0 Expected outcome df3 var S1 S2 S3 S4 var1 6 0 0 7 var2 0 5 -4 0 var3 -9 0 -9 3 var4 3 0 -2 0 Dear Experts please help me to solve the que...
[ "you can use np.select():\nimport numpy as np\nloop_cols=list(df2.columns) #save original columns\n\ndf2=df2.merge(df1,how='left',left_on='var',right_on='Var') #merge on 'var'\n\ndef replace(col_name):\n return np.select([df2[col_name]==1,df2[col_name]==2],[df2['Val1'],df2['Val2']],default=df2[col_name])\n \...
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074289471_dataframe_python.txt
Q: How to annotate a function in python that returning an html file Here is my code I also tried it without quotes but it gives me ('html' is not defined) error @app.route('/entry') def entry_page() -> 'html': return render_template('entry.html', the_title='Welcome to searchtools on the...
How to annotate a function in python that returning an html file
Here is my code I also tried it without quotes but it gives me ('html' is not defined) error @app.route('/entry') def entry_page() -> 'html': return render_template('entry.html', the_title='Welcome to searchtools on the web!') app.run()
[ "You can really set anything, but in these scenarios I find it useful to add a comment as a return type. In my case PyCharm also seems to understand that i'm adding a comment and it removes the warnings, as it knows that is indeed fine to do.\nEaxmple:\ndef entry_page() -> 'some kind of valid html':\n return ......
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074277983_python_python_3.x.txt
Q: Could we run ipython commands in python? Suppose I want use jupiter notebook/ipython as an development environment and copy everything to a python scripts afterwards. In ipython we have commands like In [1]: cd .. /Users/myname/Desktop/software In [2]: ls blah_blah_blah/ Suppose I finish my ipython notebook ...
Could we run ipython commands in python?
Suppose I want use jupiter notebook/ipython as an development environment and copy everything to a python scripts afterwards. In ipython we have commands like In [1]: cd .. /Users/myname/Desktop/software In [2]: ls blah_blah_blah/ Suppose I finish my ipython notebook and want to copy everything (suppose I have 10...
[ "Any method for running your IPython code using a standard Python interpreter is going to be a little complicated. For example, see this question, with one of the answers illustrating the call to IPython's 'magic' methods to do a shell command:\nfrom IPython.terminal.embed import InteractiveShellEmbed\n\nipshell = ...
[ 3, 0 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0042939831_ipython_python.txt
Q: line 1, in F,S = list(map(int,input().split())) ValueError: not enough values to unpack (expected 2, got 1) i am getting errors about listing i think its because of some inputs have only one integer i tried seperating them with map split but it didnt work out Question: Enter two integers then compare their values...
line 1, in F,S = list(map(int,input().split())) ValueError: not enough values to unpack (expected 2, got 1)
i am getting errors about listing i think its because of some inputs have only one integer i tried seperating them with map split but it didnt work out Question: Enter two integers then compare their values. The first line of the input consist of a single integer number t which determines the number of tests. In each o...
[ "This erros is happening because you try to separate n and m in the first input.\nHowever, the first input should be a loop control bariable.\nAn example of the code would be:\ncontrol = int(input(\"Control variable: \"))\n\nfor x in range(control):\n n,m = list(map(int, input().split()))\n\n if n > m:\n ...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074290412_python_python_3.x.txt
Q: TextBlob NaiveBayesAnalyzer extremely slow (compared to Pattern) I'm using TextBlob for python to do some sentiment analysis on tweets. The default analyzer in TextBlob is the PatternAnalyzer which works resonably well and is appreciably fast. sent = TextBlob(tweet.decode('utf-8')).sentiment I have now tried to s...
TextBlob NaiveBayesAnalyzer extremely slow (compared to Pattern)
I'm using TextBlob for python to do some sentiment analysis on tweets. The default analyzer in TextBlob is the PatternAnalyzer which works resonably well and is appreciably fast. sent = TextBlob(tweet.decode('utf-8')).sentiment I have now tried to switch to the NaiveBayesAnalyzer and found the runtime to be impractica...
[ "Yes, Textblob will train the analyzer before each run. You can use following code to avoid train the analyzer everytime.\nfrom textblob import Blobber\nfrom textblob.sentiments import NaiveBayesAnalyzer\ntb = Blobber(analyzer=NaiveBayesAnalyzer())\n\nprint tb(\"sentence you want to test\")\n\n", "Adding to Alan'...
[ 17, 0, 0 ]
[]
[]
[ "naivebayes", "python", "textblob" ]
stackoverflow_0033241842_naivebayes_python_textblob.txt
Q: How to convert for loop in list comprehension? Trying to optimize my code I want to convert this for loop in a list comprehension, any help please? fecha_añadir=pd.Timestamp('2200-01-01T12') for x in range(0,len(df_vigencias)): maximo=df_vigencias['max_vigencia'][x] if df_vigencias['FECHA_FINAL_V'+str(int(...
How to convert for loop in list comprehension?
Trying to optimize my code I want to convert this for loop in a list comprehension, any help please? fecha_añadir=pd.Timestamp('2200-01-01T12') for x in range(0,len(df_vigencias)): maximo=df_vigencias['max_vigencia'][x] if df_vigencias['FECHA_FINAL_V'+str(int(maximo))][x] is pd.NaT: df_vigencias['FECHA...
[ "Please have a look at this tutorial:\nHow to Convert Loops to List Comprehensions in Python\n" ]
[ 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0074290704_list_list_comprehension_python.txt
Q: Remove duplicates after a count but also removes count I am trying to use 2 datasets to do a count and after I want to remove the duplicates from Col 1 but i want to keep the number of calls. Basically I have a df like this: Client Number Call Count Bob 3 Bob 3 John 1 Bob 3 So what happens is the duplicates ...
Remove duplicates after a count but also removes count
I am trying to use 2 datasets to do a count and after I want to remove the duplicates from Col 1 but i want to keep the number of calls. Basically I have a df like this: Client Number Call Count Bob 3 Bob 3 John 1 Bob 3 So what happens is the duplicates get removed but the call count also changes and ...
[ "import pandas as pd\ndf1 = pd.DataFrame({'c': ['Bob', 'Bob', 'John', 'Bob'], 'n': [3, 3, 1, 0]})\ndf1 = df1.groupby(['c'], as_index = False).count()\ndf1\n\n\n\n\n\n\nc\nn\n\n\n\n\n0\nBob\n3\n\n\n1\nJohn\n1\n\n\n\n\nThis is what you are trying to achieve right?\n" ]
[ 0 ]
[]
[]
[ "count", "dataframe", "duplicates", "pandas", "python" ]
stackoverflow_0074290626_count_dataframe_duplicates_pandas_python.txt
Q: How can the following issue be resolved in flask? "Method Not Allowed The method is not allowed for the requested URL" Here is the code import os import redis import flask import json import urllib.parse from flask import Flask, Response, request, render_template, abort from flask_cors import CORS, cross_origin #f...
How can the following issue be resolved in flask? "Method Not Allowed The method is not allowed for the requested URL"
Here is the code import os import redis import flask import json import urllib.parse from flask import Flask, Response, request, render_template, abort from flask_cors import CORS, cross_origin #from flask.ext.cors import CORS, cross_origin app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' redis_handle...
[ "Browsers don't run POST methods outside of a <form> entry or AJAX function. Therefore, you're running a GET, which \"isn't allowed\".\nUnclear what you expected, but to see all users, you'll need to edit your route to first add the GET method, then if so, return a response that returns/renders all users rather tha...
[ 0, 0 ]
[]
[]
[ "crud", "flask", "flask_restful", "python", "redis" ]
stackoverflow_0074290642_crud_flask_flask_restful_python_redis.txt
Q: I want to use Selenium to find specific text I was going to use Selenium to crawl the web from selenium import webdriver from selenium.webdriver.common.by import By import time options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome('./chromedriver', options=options) driver....
I want to use Selenium to find specific text
I was going to use Selenium to crawl the web from selenium import webdriver from selenium.webdriver.common.by import By import time options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome('./chromedriver', options=options) driver.get('https://steamdb.info/tag/1742/?all') driver.i...
[ "Correct me if I'm wrong but from what I can see this steam page requires you to log-in, are you sure that when webdriver opens the page that same data is available to you ?\nAdditionally when using By, the correct syntax would be games = driver.find_element(By.CSS_SELECTOR('//*[@class=\"table-products.text-center....
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074290255_python_selenium_selenium_webdriver.txt
Q: scrape script tag with python I want scrape this string "O email não é válido." from this script tag $(function() { ,messages: { "resetPasswordEmail": { required: "O email é de preenchimento obrigatório." ,remot...
scrape script tag with python
I want scrape this string "O email não é válido." from this script tag $(function() { ,messages: { "resetPasswordEmail": { required: "O email é de preenchimento obrigatório." ,remote: "O email não é válido." ...
[ "Welcome to stackoverflow!\nsince what you are checking for is just a \"does this string exist in this other string\", you could simply check if your input contains the substring \"O email não é válido\" you can find out more on how to do this in this post: Does Python have a string 'contains' substring method?\nif...
[ 0 ]
[]
[]
[ "python", "python_regex", "python_requests_html", "regex", "web_scraping" ]
stackoverflow_0074280359_python_python_regex_python_requests_html_regex_web_scraping.txt
Q: Validate classes (hydra-core lists) with pydantic 1. Context How to validate a specific class in pydantic? I'm using pydantic to validate yaml list parameters parsed by hydra, to later be passed to modeling routines. The problem is that the hydra dictionary contains not a list of values, but a class that contains ...
Validate classes (hydra-core lists) with pydantic
1. Context How to validate a specific class in pydantic? I'm using pydantic to validate yaml list parameters parsed by hydra, to later be passed to modeling routines. The problem is that the hydra dictionary contains not a list of values, but a class that contains those values. How can I validate those params? 2. Examp...
[ "Pydantic doesn't accept the DictConfig format. When you try to parse the hydra config with the pydantic model, you must first convert the DictConfig to a native Python Dict. You do this with OmegaConf.to_object(cfg).\nI assume you use Python 3.10 or higher. Note the use of version_base=\"1.2\" to get the latest hy...
[ 0 ]
[]
[]
[ "fb_hydra", "pydantic", "python", "validation" ]
stackoverflow_0072105603_fb_hydra_pydantic_python_validation.txt
Q: Check if a value in a dictionary is a substring of another key-value pair in Python I have a dictionary disease_dict with values in a list element. I would like to fetch key and value for specific keys and then check if the value (as a substring) exists in other keys and fetch all the key --> value pair. For examp...
Check if a value in a dictionary is a substring of another key-value pair in Python
I have a dictionary disease_dict with values in a list element. I would like to fetch key and value for specific keys and then check if the value (as a substring) exists in other keys and fetch all the key --> value pair. For example this is the dictionary. I would like to see if the 'Stroke' or 'stroke' exist in the d...
[ "You have a good starting point and as you probably already know, you need to work on the key to split it. Here is how you could do it:\ndisease_dict = { 'Stroke': ['C10.228.140.300.775', 'C14.907.253.855'], 'Stroke, Lacunar': ['C10.228.140.300.275.800', 'C10.228.140.300.775.600', 'C14.907.253.329.800', 'C14.907.25...
[ 1, 1 ]
[]
[]
[ "dictionary", "pandas", "python", "substring" ]
stackoverflow_0074290108_dictionary_pandas_python_substring.txt
Q: How to do time series clustering with python I want to group 10 stores into 6 clusters but I have these data in multiple years. I tried KMeans from sklearn.cluster but I am under impression that it's good for one period only. I came across K-means and Dynamic Time Wrapping https://tslearn.readthedocs.io/en/stable/...
How to do time series clustering with python
I want to group 10 stores into 6 clusters but I have these data in multiple years. I tried KMeans from sklearn.cluster but I am under impression that it's good for one period only. I came across K-means and Dynamic Time Wrapping https://tslearn.readthedocs.io/en/stable/user_guide/clustering.html and tested on it, but I...
[ "You can pivot your original dataframe, where you take store as an index, put points, assists and rebounds in column broken down by year, then run the cluster by using sklearn Kmeans. In this case, you still have one record (store) in a row, where columns show the value per year for points, assists and rebounds, re...
[ 1 ]
[ "The end goal is to assign 10 stores to 6 clusters based on data. Recent data has more weight than historical data. So clusters should be giving more weight to 2022 data than 2021 data. Secondly , there will be only one group of clusters. Clusters for 2021 will not be calculated separately .\nYou need to use weigh...
[ -1 ]
[ "cluster_analysis", "k_means", "python", "scikit_learn" ]
stackoverflow_0074214332_cluster_analysis_k_means_python_scikit_learn.txt
Q: Delete a dictionary item in a json file Using Python I have a sample json file in python. [ { "WHO": "Joe", "WEEK": [ { "NUMBER": 3, "EXPENSE": [ { "WHAT": "Beer", "AMOUNT": 18.00 }, { "WHAT": "Food", "AMO...
Delete a dictionary item in a json file Using Python
I have a sample json file in python. [ { "WHO": "Joe", "WEEK": [ { "NUMBER": 3, "EXPENSE": [ { "WHAT": "Beer", "AMOUNT": 18.00 }, { "WHAT": "Food", "AMOUNT": 12.00 }, { "WHAT": "...
[ "You don't need a try-except block but just load your json data and iterate over the fields looking for your Car.\nFirst save your json as a file named \"jsondata.json\"\njsondata.json\n[{ \"WHO\": \"Joe\", \"WEEK\": [{\"NUMBER\": 3,\"EXPENSE\":[\n { \"WHAT\": \"Beer\",\n \"AMOUNT\": 18.00\n },\n ...
[ 0 ]
[]
[]
[ "dictionary", "json", "key_value", "python" ]
stackoverflow_0074290461_dictionary_json_key_value_python.txt
Q: Sort a stacked bar chart with transform fold Altair I was wondering if there is any way to sort the bars within a stacked bar chart when the chart contains a transform fold. My data is "wide form": and I want each row of the dataframe to be represented with its own bar in a chart. Hence, I need to first do a tran...
Sort a stacked bar chart with transform fold Altair
I was wondering if there is any way to sort the bars within a stacked bar chart when the chart contains a transform fold. My data is "wide form": and I want each row of the dataframe to be represented with its own bar in a chart. Hence, I need to first do a transform fold. This all works fine and the bars appear to be...
[ "I think you got confused with all the different settings. Let me try to break this down.\n\nThe order of the color legend can be controlled using the scale argument.\n\nalt.Chart(small_df).mark_bar().transform_fold(\n ['Probability A','Probability B','Probability C']\n ).encode(\n x=alt.X('value:Q...
[ 1 ]
[]
[]
[ "altair", "python" ]
stackoverflow_0074283103_altair_python.txt
Q: How to make update table if exists otherwise create I have dynamodb table: tablename: mytable schema: {'primary_key': 'name'} Case 1 Insert document {'name':'john', 'age': 24} if not exists in the table otherwise update the item Do i need to get the item from dynamo and check whether 'name exists' in the begin...
How to make update table if exists otherwise create
I have dynamodb table: tablename: mytable schema: {'primary_key': 'name'} Case 1 Insert document {'name':'john', 'age': 24} if not exists in the table otherwise update the item Do i need to get the item from dynamo and check whether 'name exists' in the beginning to do the operation? import boto3 def lambda_handle...
[ "Understanding the nature of UpdateItem will help you here:\nEdits an existing item's attributes, or adds a new item to the table if it does not already exist.\nCase 1, is handled by default when using UpdateItem, as it will update if item exists and if it does not it will create a new one.\nCase 2, you will need t...
[ 2 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074289397_amazon_dynamodb_amazon_web_services_boto3_python.txt
Q: Flask template not found even when file exists and templates folder is called 'templates'? As the title says, I have problems to render a template which exists in the correct folder which is supposed to have the correct name: flaskapp/ app.py /templates website.html and the usual code from flas...
Flask template not found even when file exists and templates folder is called 'templates'?
As the title says, I have problems to render a template which exists in the correct folder which is supposed to have the correct name: flaskapp/ app.py /templates website.html and the usual code from flask import Flask, render_template app = Flask(__name__) @app.route("/") def main(): retur...
[ "Since you haven't installed your project as a package in the virtualenv, you need to run from the root directory of the project so that Python and Flask get the correct working directory. Otherwise Flask has no idea how to find the templates.\nAlso, you really shouldn't run a Flask application line by line in an I...
[ 1, 1 ]
[]
[]
[ "flask", "python", "templates" ]
stackoverflow_0047117523_flask_python_templates.txt
Q: Tensorboard get blank page I'm new in tensorflow and i follow this tutorial to learn about this framework. Now i'm trying to visualize my graph using Tensorboard but but i get a tensorboard blank page without any result. The code that i use to visualize the graph is: from __future__ import print_function import te...
Tensorboard get blank page
I'm new in tensorflow and i follow this tutorial to learn about this framework. Now i'm trying to visualize my graph using Tensorboard but but i get a tensorboard blank page without any result. The code that i use to visualize the graph is: from __future__ import print_function import tensorflow as tf import numpy as n...
[ "The logdir you're pointing tensorboard to probably does not exist (tensorboard does not throw an error in that case). Did you mean tensorboard --logdir=./logs/?\n", "This may come late, but hopefully it will help someone else.\nIf your browser does not accept cookies, you will run into this issue.\nMake sure you...
[ 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "tensorboard", "tensorflow" ]
stackoverflow_0043279667_python_tensorboard_tensorflow.txt
Q: How to read from Azure Blob Storage with Python delta-rs I'd like to use the Python bindings to the delta-rs to read from my blob storage. https://github.com/delta-io/delta-rs/tree/main/python Currently I am kind of lost, since I cannot figure out how to configure the filesystem on my local machine. Where do i hav...
How to read from Azure Blob Storage with Python delta-rs
I'd like to use the Python bindings to the delta-rs to read from my blob storage. https://github.com/delta-io/delta-rs/tree/main/python Currently I am kind of lost, since I cannot figure out how to configure the filesystem on my local machine. Where do i have to put my credentials? Can I use adlfs for this? from adlfs ...
[ "Unfortunately we don't have great documentation around this at the moment. You should be able to set AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_SAS environment variables a la this integration test.\nThat will ensure the Python bindings can access table metadata, but typically fetching of the data for query is done th...
[ 2, 0 ]
[]
[]
[ "azure_blob_storage", "delta_lake", "python", "rust" ]
stackoverflow_0067199444_azure_blob_storage_delta_lake_python_rust.txt
Q: How can i get the table headers if they are not all text with python and beautifulsoup? Hi guys, I am basically new to coding in general so bare with me. I am trying to retrieve the table headers for this table: https://www.transfermarkt.co.uk/manchester-united-fc/leistungsdaten/verein/985/reldata/%262022/plus/1 ...
How can i get the table headers if they are not all text with python and beautifulsoup?
Hi guys, I am basically new to coding in general so bare with me. I am trying to retrieve the table headers for this table: https://www.transfermarkt.co.uk/manchester-united-fc/leistungsdaten/verein/985/reldata/%262022/plus/1 First i tried with pandas but i could not get my data so i learned about beautifull soup and ...
[ "you can get what's missing from\n>>> [span.get_attribute_list(\"title\")[0] for span in thead.find_all('span')]\n['Appearances',\n 'Goals',\n 'Assists',\n 'Yellow cards',\n 'Second yellow cards',\n 'Red cards',\n 'Substitutions on',\n 'Substitutions off',\n 'Minutes played']\n\nAnd then manually link those results...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_requests", "web_scraping" ]
stackoverflow_0074289350_beautifulsoup_python_python_requests_web_scraping.txt
Q: PYSpark data Frame schema is showing String for every column I am reading CSV file from below code snippet df_pyspark = spark.read.csv("sample_data.csv") df_pyspark and when i try to print data Frame its output is like shown as below: DataFrame[_c0: string, _c1: string, _c2: string, _c3: string, _c4: string, _c5: ...
PYSpark data Frame schema is showing String for every column
I am reading CSV file from below code snippet df_pyspark = spark.read.csv("sample_data.csv") df_pyspark and when i try to print data Frame its output is like shown as below: DataFrame[_c0: string, _c1: string, _c2: string, _c3: string, _c4: string, _c5: string] For each column dataType is showing 'String' even though c...
[ "Use inferSchema parameter during read of CSV file it'll Show the exact/correct datatype according to the values in columns\n df_pyspark = spark.read.csv(\"sample_data.csv\", header=True, inferSchema=True)\n\n +---+----------+---------+--------------------+-----------+----------+\n | id|first_name|last_nam...
[ 1 ]
[]
[]
[ "dataframe", "pyspark", "python" ]
stackoverflow_0074290859_dataframe_pyspark_python.txt
Q: Python socket gethostbyname() returns only one IP address I'm doing some simple experiments using Python socket, where I've a HOSTNAME which resolves with two IP addresses but when I use, socket.gethostbyname('demo.sample.com') I'm getting only one IP address. Why is it showing that way? Is there any other way...
Python socket gethostbyname() returns only one IP address
I'm doing some simple experiments using Python socket, where I've a HOSTNAME which resolves with two IP addresses but when I use, socket.gethostbyname('demo.sample.com') I'm getting only one IP address. Why is it showing that way? Is there any other way I can get multiple IP addresses? EDIT - 1 I got it guys, inste...
[ "From the documentation it is visible that:\n\ngethostbyname returns only a single IPv4 address. And to cite: See gethostbyname_ex() for a more complete interface.\ngethostbyname_ex will return multiple IPv4 address, but check out the usage. And to cite: gethostbyname_ex() does not support IPv6 name resolution, and...
[ 10, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0043672468_python_sockets.txt
Q: How do you set multiple clauses for dataframe loc()? I’m trying to create a new dataframe by grabbing certain rows from another df by setting a couple conditions in the df.loc() df2 = df.loc[((df.CustID == i) & (df['Section'].isin(['group1', 'group2']))), ['CustID', 'Section']].copy() But I’m ...
How do you set multiple clauses for dataframe loc()?
I’m trying to create a new dataframe by grabbing certain rows from another df by setting a couple conditions in the df.loc() df2 = df.loc[((df.CustID == i) & (df['Section'].isin(['group1', 'group2']))), ['CustID', 'Section']].copy() But I’m getting sections that aren’t group1 or group2 so I’m a bit...
[ "From your line of code it looks like you are missing ] try the below code or else help us with the data sample to guide you better.\nAlso single & would work\ndf2 = df.loc[(df.CustID == i) & (df['Section'].isin(['group1', 'group2'])), ['CustID', 'Section']].copy() \n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074290951_pandas_python.txt
Q: timeit on a python file that launches pytest I would like to timeit a python file, but I can't make it work: the python file looks like this (it launches tests): import pytest retcode: int | pytest.ExitCode = pytest.main() if retcode == pytest.ExitCode.OK: print(f"\n---\nAll good\n---\n") I've tried python ...
timeit on a python file that launches pytest
I would like to timeit a python file, but I can't make it work: the python file looks like this (it launches tests): import pytest retcode: int | pytest.ExitCode = pytest.main() if retcode == pytest.ExitCode.OK: print(f"\n---\nAll good\n---\n") I've tried python -m timeit unit_tests.py with quotes around the uni...
[ "The timeit command line interface does not expect a file as input, it expects a string. The NameError is the result of Python trying to execute the filename as a string:\n$ python -c 'test.py'\nTraceback (most recent call last):\n File \"<string>\", line 1, in <module>\nNameError: name 'test' is not defined\n\nI...
[ 1 ]
[]
[]
[ "pytest", "python", "timeit" ]
stackoverflow_0074192865_pytest_python_timeit.txt
Q: Having trouble using nested loops/ accessing data in a list of list This is the question: Define a function named list_dic_gen with two parameters. The first parameter will be a list of strings. The second parameter will be a list whose entries are also lists. You SHOULD assume each entry in the second parameter w...
Having trouble using nested loops/ accessing data in a list of list
This is the question: Define a function named list_dic_gen with two parameters. The first parameter will be a list of strings. The second parameter will be a list whose entries are also lists. You SHOULD assume each entry in the second parameter will have the same length as the first parameter. Your list_dic_gen functi...
[ "Try to empty your acct dictionary at the start of each loop. The dict not being emptied seems to be your issue. Something like:\ndef list_dic_gen(lst,lol):\n acc=[]\n a=0\n for l in lol:\n accd={}\n for o in l:\n accd[lst[a]]=l[a]\n acc.append(accd)\n a+=1\n return acc\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074290615_python.txt
Q: Python multiprocessing process hangs at the end of it I have a python script driving me crazy. Right now i have a infinite loop that checks a data and get into a function in a specific situation. while true: time.sleep(1) peso = getPeso() if peso > 900: processo = multiprocessing.Process(target...
Python multiprocessing process hangs at the end of it
I have a python script driving me crazy. Right now i have a infinite loop that checks a data and get into a function in a specific situation. while true: time.sleep(1) peso = getPeso() if peso > 900: processo = multiprocessing.Process(target=processo_automatico) processo.start() proc...
[ "Solved.\nWhat was that?\nWell, my focus was on the end of the process while the issue was right at the start.\nSee the function getPeso()? That one just gets values from the serial.\nAfter a few hours of getting those values the raspberry py just starts to see random values and you gotta reboot to fix it.\nI wasn'...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_multiprocessing" ]
stackoverflow_0074155068_python_python_3.x_python_multiprocessing.txt
Q: python+django-unchecked checkbox returns "none" I have an HTML form with checkbox: <form action="...function x" method="POST"> {% for x in box %} <tr class="cart_row_{{forloop.counter0}}"name="cart_row_{{forloop.counter0}}"> <td> <input class="form-check-input" type="checkbox"value="-1" checked="0" name="check...
python+django-unchecked checkbox returns "none"
I have an HTML form with checkbox: <form action="...function x" method="POST"> {% for x in box %} <tr class="cart_row_{{forloop.counter0}}"name="cart_row_{{forloop.counter0}}"> <td> <input class="form-check-input" type="checkbox"value="-1" checked="0" name="check_{{forloop.counter0}}"> <label class="form-check-lab...
[ "Checkboxes does not appear in POST data if it is not checked. So you should check like this in your view.\nif 'checkbox_input_name' in request.POST:\n checked = True\n\n" ]
[ 1 ]
[]
[]
[ "django", "forms", "html", "python" ]
stackoverflow_0074290913_django_forms_html_python.txt
Q: Python: socket.gaierror: [Errno 8] When Attempting To Get IP Address in MacOS Big Sur I just upgraded my MacBook to macOS Big Sur. Previously on macOS Mojave, the following code still running and outputs the IP Address of the Macbook. But after I upgraded, it just shows up the Errno 8 error. Which was weird. Have ...
Python: socket.gaierror: [Errno 8] When Attempting To Get IP Address in MacOS Big Sur
I just upgraded my MacBook to macOS Big Sur. Previously on macOS Mojave, the following code still running and outputs the IP Address of the Macbook. But after I upgraded, it just shows up the Errno 8 error. Which was weird. Have anyone encountered this bug before? Thanks. import socket hostname = socket.gethostname() i...
[ "try:\ndef hostname_ip(hostname):\n hostname = 'google.com'\n addr1 = socket.gethostbyname(hostname)\n return addr1[2]\n\n" ]
[ 0 ]
[]
[]
[ "ip_address", "macos", "macos_big_sur", "python", "sockets" ]
stackoverflow_0072810966_ip_address_macos_macos_big_sur_python_sockets.txt
Q: Mean value of 2 group by's if value is not unique pandas I have been struggling with grouping by 2 conditions (or grouping "twice"?), adding an if unique value condition, and do the mean of those groups. I created a sample dataset so it can be better understood: A chef makes dishes, made out of ingredients, which ...
Mean value of 2 group by's if value is not unique pandas
I have been struggling with grouping by 2 conditions (or grouping "twice"?), adding an if unique value condition, and do the mean of those groups. I created a sample dataset so it can be better understood: A chef makes dishes, made out of ingredients, which each cost X. They can be costing differently depending on the ...
[ "The following drops the data regarding chefs who have only prepared one dish:\ndish_ct = df_chef.groupby(['chef_id'])['dish'].nunique()\nchefs = dish_ct[dish_ct > 1].index\ndf_chef = df_chef[df_chef['chef_id'].isin(chefs)]\n\nAfter that, you can use your the same approach as before: the line\nprint(df_chef.groupby...
[ 2, 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074290510_pandas_python.txt
Q: running multiple external commands in parallel in Python I want to run multiple external commands (like opening notepad.exe) at once in parallel through Python. I know how to do it by using the subprocess module. However, I also want to run multiple such commands at once in parallel and ensure that at any time, n ...
running multiple external commands in parallel in Python
I want to run multiple external commands (like opening notepad.exe) at once in parallel through Python. I know how to do it by using the subprocess module. However, I also want to run multiple such commands at once in parallel and ensure that at any time, n commands are running out of a total of m commands until all th...
[ "you should use a Threadpool for this, with subprocess.run as it blocks the running thread.\nimport subprocess\nfrom multiprocessing.pool import ThreadPool\ncommands = []\nbatch_size = 3\n\nfor i in range(10):\n commands.append('notepad.exe')\n\ndef run_in_batches(batch_size, commands_to_run):\n with ThreadPo...
[ 2 ]
[]
[]
[ "parallel_processing", "python", "python_3.x", "subprocess" ]
stackoverflow_0074291040_parallel_processing_python_python_3.x_subprocess.txt
Q: How to convert to size 0 array import numpy as np A = np.array([[2], [1], [3]]) A.shape # (3, 1) A.reshape(3,0) ValueError Traceback (most recent call last) <ipython-input-12-771b3dbc4936> in <module> ----> 1 A.reshape(3,0) ValueError: cannot reshape array of size 3 into shape ...
How to convert to size 0 array
import numpy as np A = np.array([[2], [1], [3]]) A.shape # (3, 1) A.reshape(3,0) ValueError Traceback (most recent call last) <ipython-input-12-771b3dbc4936> in <module> ----> 1 A.reshape(3,0) ValueError: cannot reshape array of size 3 into shape (3,0)
[ "import numpy as np\nA = np.array([[2], [1], [3]])\nA = [a for b in A for a in b]\nprint(A)\n\nResults in: [2, 1, 3]\nif this is what you were looking for\n", "Please tell us about what exactly you want to achive?\nA shape of (3, 1) means you have an array with two axis; one with the length of 3, and the second w...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074290949_python.txt
Q: Appending instanse attribute as list in for loop I've written a simplified example of the logic of the class, which I find confusing. class Result: def __init__(self): self.limit = 10 self.params_with_error = [] def get_result(self, offset_range): qs = {'limit': self.limit} ...
Appending instanse attribute as list in for loop
I've written a simplified example of the logic of the class, which I find confusing. class Result: def __init__(self): self.limit = 10 self.params_with_error = [] def get_result(self, offset_range): qs = {'limit': self.limit} for chunk in range(offset_range): print(...
[ "dictionaries are mutable, you only created 1 dictionary in your entire code snippet.\nqs = {'limit': self.limit}\n\neverything else in the code just references or updates this dictionary, so your final result just has 2 references to the same dictionary, it was never copied.\nself.params_with_error = [qs, qs]\n\nt...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074290666_python.txt
Q: Visualize networkX graph with X, Y coordinates using Bokeh I'm plotting the NetworkX graph using Bokeh where I have node IDs, edges IDs, edges length, width, and edges coordinates as follows: import pandas as pd import networkx as nx ##Graph data d = {'Node 1': [54524, 56577, 53689, 55961, 54524], 'Node 2': [...
Visualize networkX graph with X, Y coordinates using Bokeh
I'm plotting the NetworkX graph using Bokeh where I have node IDs, edges IDs, edges length, width, and edges coordinates as follows: import pandas as pd import networkx as nx ##Graph data d = {'Node 1': [54524, 56577, 53689, 55961, 54524], 'Node 2': [56577, 76969, 54524, 56354, 54525], 'len': [51.3, 107.7, 27...
[ "You can pass whichever layout you want to from_networkx function.\nIt can be a networkx layout (in your code you are using nx.spring_layout) or a dictionnary mapping nodes to coordinates (see doc here).\nIn terms of setting up your hover tool, you can use:\nhover = HoverTool(tooltips=[(\"len\",\"@len\"),(\"Stick I...
[ 1 ]
[]
[]
[ "bokeh", "geospatial", "graph_theory", "networkx", "python" ]
stackoverflow_0074290141_bokeh_geospatial_graph_theory_networkx_python.txt
Q: Comparing performance of python and ctypes equivalent code I tried to compare the performance of both Python and Ctypes version of the sum function. I found that Python is faster than ctypes version. Sum.c file: int our_function(int num_numbers, int *numbers) { int i; int sum = 0; for (i = 0; i < num_n...
Comparing performance of python and ctypes equivalent code
I tried to compare the performance of both Python and Ctypes version of the sum function. I found that Python is faster than ctypes version. Sum.c file: int our_function(int num_numbers, int *numbers) { int i; int sum = 0; for (i = 0; i < num_numbers; i++) { sum += numbers[i]; } return sum; ...
[ "Why\nWell, yes, in such a case, it is not really worth it.\nBecause before calling the c function, you spend lot of time converting numbers in to c_int.\nWhich is not less expansive as an addition.\nUsually we use ctypes when, either the data are generated on the C-side. Or when we generate them from python, but t...
[ 2 ]
[]
[]
[ "ctypes", "performance", "python" ]
stackoverflow_0074290281_ctypes_performance_python.txt
Q: ValueError: could not convert string to float? I am a beginner in terms of coding. Python gives me the same error whenever I try to do calculation. I use python 3.9. I do not make typo when I enter input (this one was 5.2). Could you please help me? """ length of rectangle = a width of rectangle = b calculate the ...
ValueError: could not convert string to float?
I am a beginner in terms of coding. Python gives me the same error whenever I try to do calculation. I use python 3.9. I do not make typo when I enter input (this one was 5.2). Could you please help me? """ length of rectangle = a width of rectangle = b calculate the area and perimeter of the rectangle """ a = 6 b = f...
[ "This code should work. I guess the problem is your input: '5.2&'. You made a typo here. Revove '&' and it will work.\n", "No problem with the code, not the code, whether your input key has some hidden characters attached\n┌──[root@vms81.liruilongs.github.io]-[/]\n└─$vim demo.py\n┌──[root@vms81.liruilongs.github....
[ 0, 0 ]
[ "\"\"\"\nlength of rectangle = a\nwidth of rectangle = b\ncalculate the area and perimeter of the rectangle\n\"\"\"\n\na = 6\nb = float(input(\"width: \"))\n\narea = a*b\nperimeter = (2*a) + (2*b)\n\nprint(\"area: \" , area , \" perimeter: \" , perimeter)\n\n" ]
[ -1 ]
[ "python", "string", "valueerror" ]
stackoverflow_0074291000_python_string_valueerror.txt
Q: How to solve an explicit wait which isn't waiting long enough selenium python I'm trying to program a sequence of events which are dependent on the last in selenium. First click login which loads a new page, then click a scrollbox on that page, then click a button inside the scrollbox which won't be loaded until t...
How to solve an explicit wait which isn't waiting long enough selenium python
I'm trying to program a sequence of events which are dependent on the last in selenium. First click login which loads a new page, then click a scrollbox on that page, then click a button inside the scrollbox which won't be loaded until the scrollbox has been clicked. I am trying to stop using time.sleep(x) as I've read...
[ "If you need selenium to wait longer you just have to change the timeout. If all you need is 2 seconds more then try\nscroll_box = WebDriverWait(driver, 7).until(\n ec.element_to_be_clickable((By.XPATH, \"//*[@id=\\\"searchBarFilterDropdown\\\"]\")))\n scroll_box.click()\n\nwhen using WebDriverWait, in th...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "webdriverwait" ]
stackoverflow_0072232072_python_selenium_webdriverwait.txt
Q: Launch the same script several times I try to launch the same script several times on python. I have finished my script but I don't know how to launch my script several times. A: You can try to make a shell command if you have access to a Unix-Shell. Something like this might work: number_of_times=5 for i in $(s...
Launch the same script several times
I try to launch the same script several times on python. I have finished my script but I don't know how to launch my script several times.
[ "You can try to make a shell command if you have access to a Unix-Shell. Something like this might work:\nnumber_of_times=5\nfor i in $(seq 1 $number_of_times); do \n # Your command here:\n python3 main.py\ndone\n\nAssuming you're using python3 and some script main.py\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074291228_python.txt
Q: Replace string for numeric labels for classification For a classification problem I want to replace different country codes by numbers representing the class. The column below is a subset of the complete column acq_cc values representing more than 70 unique countries. I want to replace the 2 letter country code by...
Replace string for numeric labels for classification
For a classification problem I want to replace different country codes by numbers representing the class. The column below is a subset of the complete column acq_cc values representing more than 70 unique countries. I want to replace the 2 letter country code by a number acq_cc = {KY, US, CN, SG, US, SG, US, US, CZ, C...
[ "To do this you can use the pandas built-in:\nacq_cc = pd.factorize(var, sort=True)[0]\n\nwhere in var you can directly pass the pandas column or your acq_cc\n" ]
[ 4 ]
[]
[]
[ "integer", "pandas", "python", "replace", "string" ]
stackoverflow_0074291201_integer_pandas_python_replace_string.txt
Q: python sum all previous values in array at each index I have an array: my_array = [1, 4, 1, 13, 9] and would like to create a new array that for each index in my_array is the sum of all the previous index values summed_array = [0, 1, 5, 6, 19] I tried something like for ind,i in enumerate(my_array): print i,...
python sum all previous values in array at each index
I have an array: my_array = [1, 4, 1, 13, 9] and would like to create a new array that for each index in my_array is the sum of all the previous index values summed_array = [0, 1, 5, 6, 19] I tried something like for ind,i in enumerate(my_array): print i, my_array[ind-1] but can't figure out how to get the summa...
[ ">>> from numpy import cumsum, ones\n>>> a = ones(10)\n>>> print(cumsum(a))\narray([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])\n\n", "A pure Python implementation:\ndef cumilative_sum(lst):\n total, result = 0, []\n for ele in lst:\n result.append(total)\n total += ele\n r...
[ 9, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "numpy", "python", "python_2.7", "sum" ]
stackoverflow_0033883758_numpy_python_python_2.7_sum.txt
Q: Best practice to update dataframe columns with multiple conditions and joins Let's say I have 2 dataframes: df1 = pd.DataFrame([["SAP ", 1, 'CHANGE_NEEDED', 10, 11], ["SAP123", 1, 'CORRECT_VALUE', 10, 11], ["NOTSAP123", 1, 'INCORRECT_VALUE', 10, 11], ...
Best practice to update dataframe columns with multiple conditions and joins
Let's say I have 2 dataframes: df1 = pd.DataFrame([["SAP ", 1, 'CHANGE_NEEDED', 10, 11], ["SAP123", 1, 'CORRECT_VALUE', 10, 11], ["NOTSAP123", 1, 'INCORRECT_VALUE', 10, 11], ["NOTSAP456", 1, 'INCORRECT_VALUE', 10, 11]], col...
[ "Couple of ideas that can help:\n\nJoining df1 and df2 would definitely be the preferred way here. Using df1.merge(df2, on=['RCD_ORIG_CD', 'VEN_ID', 'VLC_VEN_ID'], ...) (or similar) is clearer and more error-prone than matching them manually column-by-column.\nIf different parts of the input dataframe require diffe...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074290883_dataframe_pandas_python.txt
Q: How to embed a conditional in list comprehension? Assume this dataset: df = pd.DataFrame({ 'name': ['John','William', 'Nancy', 'Susan', 'Robert', 'Lucy', 'Blake', 'Sally', 'Bruce', 'Mike'], 'injury': ['right hand broken', 'lacerated left foot', 'foot broken', 'right foot fractured', '', 'sprained finger', ...
How to embed a conditional in list comprehension?
Assume this dataset: df = pd.DataFrame({ 'name': ['John','William', 'Nancy', 'Susan', 'Robert', 'Lucy', 'Blake', 'Sally', 'Bruce', 'Mike'], 'injury': ['right hand broken', 'lacerated left foot', 'foot broken', 'right foot fractured', '', 'sprained finger', 'chest pain', 'swelling in arm', 'laceration to arms, h...
[ "you can use .dropna() before the lambda\ndf[\"injury\"].str.replace(\",\", \"\").str.split(\" \", expand=False).dropna().apply(lambda x: \", \".join(set([i for i in x if i in selected_words])))\n\n0 hand\n1 foot\n2 foot\n3 foot\n4 ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074290855_python.txt
Q: Using python variable in shell data in google colab I am using google colab which combine the shell script and python script such as For example a = "test" print(a) !cd /content/drive/MyDrive/test First and second line is python and third line is shell. Now I want to use pytho variable in shell such as a = "test"...
Using python variable in shell data in google colab
I am using google colab which combine the shell script and python script such as For example a = "test" print(a) !cd /content/drive/MyDrive/test First and second line is python and third line is shell. Now I want to use pytho variable in shell such as a = "test" print(a) !cd /content/drive/MyDrive/{a} Is it possible?...
[ "Yes. To use a variable inside a shell command with ! you can wrap it using {}\nYour example is correct\n" ]
[ 1 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0074288452_google_colaboratory_python.txt
Q: Making custom prefix command for my discord bot I am getting the following error Ignoring exception in on_message Traceback (most recent call last): File "C:\python\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "d:\VS CODE ALL FILES\cn utility\main.py", line...
Making custom prefix command for my discord bot
I am getting the following error Ignoring exception in on_message Traceback (most recent call last): File "C:\python\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "d:\VS CODE ALL FILES\cn utility\main.py", line 1034, in on_message await client.process_co...
[ "A lot of times this can happen when you have created the custom prefix function and setup without removing and then adding back your bot. This is because you have the prefix and guild id added when your bot joins a new server. I'm assuming that you're using a json file which adds a default prefix as well as the gu...
[ 1 ]
[]
[]
[ "discord.py", "keyerror", "python" ]
stackoverflow_0074288049_discord.py_keyerror_python.txt
Q: TypeError: Object of type Response is not JSON serializable I am trying to use Python and APIs to build an SQL table with the names of the first 100 Pokemon in the Poke API. Here's my code import psycopg2, json, requests, hidden # Load secrets secrets = hidden.secrets() conn = psycopg2.connect(host=secrets['host...
TypeError: Object of type Response is not JSON serializable
I am trying to use Python and APIs to build an SQL table with the names of the first 100 Pokemon in the Poke API. Here's my code import psycopg2, json, requests, hidden # Load secrets secrets = hidden.secrets() conn = psycopg2.connect(host=secrets['host'], port=secrets['port'], database=secrets['datab...
[ "requests.get() returns the entire response, not just the body text.\nIf you want the body text, use the text attribute of the response object:\nresponse = requests.get(results[x]['url'])\njs_body = json.dumps(response.text)\n\n" ]
[ 2 ]
[]
[]
[ "api", "json", "psycopg2", "python", "sql" ]
stackoverflow_0074291298_api_json_psycopg2_python_sql.txt
Q: Type annotations for *args and **kwargs I'm trying out Python's type annotations with abstract base classes to write some interfaces. Is there a way to annotate the possible types of *args and **kwargs? For example, how would one express that the sensible arguments to a function are either an int or two ints? type...
Type annotations for *args and **kwargs
I'm trying out Python's type annotations with abstract base classes to write some interfaces. Is there a way to annotate the possible types of *args and **kwargs? For example, how would one express that the sensible arguments to a function are either an int or two ints? type(args) gives Tuple so my guess was to annotat...
[ "For variable positional arguments (*args) and variable keyword arguments (**kw) you only need to specify the expected value for one such argument.\nFrom the Arbitrary argument lists and default argument values section of the Type Hints PEP:\n\nArbitrary argument lists can as well be type annotated, so that the def...
[ 407, 51, 36, 28, 6, 5, 3, 0 ]
[]
[]
[ "python", "python_typing", "type_hinting" ]
stackoverflow_0037031928_python_python_typing_type_hinting.txt
Q: How to run function in background in Django view I have Django project with one view. When I refresh page I want to call some function which is very complicated and take same time to execute. How and what is the best way to do it in backround? import time import psycopg2 from django.http import HttpResponse def l...
How to run function in background in Django view
I have Django project with one view. When I refresh page I want to call some function which is very complicated and take same time to execute. How and what is the best way to do it in backround? import time import psycopg2 from django.http import HttpResponse def long_time_function(sec): time.sleep(sec) print(...
[ "Maybe you can take a look at the async support. async\n", "With asyncio, you can run multiple async functions in background concurrently and asynchronously in Django view as shown below.\n# \"store/views.py\"\n\nimport asyncio\nfrom django.http import HttpResponse\n\nasync def test1(num):\n print(\"Test1\")\n...
[ 1, 1 ]
[]
[]
[ "background_process", "django", "django_views", "python" ]
stackoverflow_0071914965_background_process_django_django_views_python.txt
Q: What is the meaning of single and double underscore before an object name? What do single and double leading underscores before an object's name represent in Python? A: Single Underscore In a class, names with a leading underscore indicate to other programmers that the attribute or method is intended to be be us...
What is the meaning of single and double underscore before an object name?
What do single and double leading underscores before an object's name represent in Python?
[ "Single Underscore\nIn a class, names with a leading underscore indicate to other programmers that the attribute or method is intended to be be used inside that class. However, privacy is not enforced in any way.\nUsing leading underscores for functions in a module indicates it should not be imported from somewhere...
[ 1486, 476, 372, 242, 153, 81, 20, 20, 17, 8, 8, 7, 6, 4, 3, 1, 0, 0 ]
[]
[]
[ "identifier", "naming_conventions", "oop", "python" ]
stackoverflow_0001301346_identifier_naming_conventions_oop_python.txt
Q: Python Panda Read_CSV not separating columns appropriately In one of my classes, we are required to load and append 6 CSV files together, using python. These files do NOT have the headers included. I have tried for hours, multiple methods for either directly combining the CSV files or reading them individually a...
Python Panda Read_CSV not separating columns appropriately
In one of my classes, we are required to load and append 6 CSV files together, using python. These files do NOT have the headers included. I have tried for hours, multiple methods for either directly combining the CSV files or reading them individually and appending them, using different guides online. For what shou...
[ "It's because some of the files are encoded in UTF-16.\nYou can find an encoding and specify the encoding when calling pandas.read_csv() like this.\nimport codecs\nimport pandas as pd\n\ndef find_encoding(path):\n with open(path, 'rb') as f:\n bytes = f.read(4)\n for bom, encoding in (\n (codecs...
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074230519_csv_dataframe_pandas_python.txt
Q: Follow-up question to my previous question Previously, I have asked for help on a school project due in a few days, it's a digit span test in python that requires the implementation of Object Orient Programming. I have further improved on my code, here it is currently: import time import random import os appeart...
Follow-up question to my previous question
Previously, I have asked for help on a school project due in a few days, it's a digit span test in python that requires the implementation of Object Orient Programming. I have further improved on my code, here it is currently: import time import random import os appeartimeframe = float(1) os.system('cls') print("Welc...
[ "\nafter you call randomlist = [] you never reset the content of the list. After your player won or lost you should reset the list (e.g before you fill it with random numbers again)\n\nDo some reading on main OOP Concepts like classes and methods and how they are implemented in python.\n\n\nhttps://realpython.com/p...
[ 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0074290800_oop_python.txt
Q: IronPython code not working in 3.4 but worked in 2.7 So I have installed IronPython 3.4 to replace the IronPython 2.7 I was using. The code below worked fine in 2.7 but when I use it in 3.4 I am getting the error: Microsoft.Scripting.SyntaxErrorException: 'invalid syntax' Any ideas? Thanks. using System; using Sys...
IronPython code not working in 3.4 but worked in 2.7
So I have installed IronPython 3.4 to replace the IronPython 2.7 I was using. The code below worked fine in 2.7 but when I use it in 3.4 I am getting the error: Microsoft.Scripting.SyntaxErrorException: 'invalid syntax' Any ideas? Thanks. using System; using System.Collections.Generic; using System.Linq; using System.T...
[ "IronPython 3.4 uses python 3.4 syntax where as IronPython 2.7 uses python 2.7.\nIn python 2.7 print is a statement, where as in python 3 print is a function(which means you need to use parentheses to wrap the arguments). So to make your code work you have to change the following section from\npythonEngine.CreateSc...
[ 1 ]
[]
[]
[ ".net", "c#", "ironpython", "python", "syntax" ]
stackoverflow_0074291379_.net_c#_ironpython_python_syntax.txt
Q: What am I doing wrong? Can't call earlier functions def addition(num1, num2): answerAdd=num1+num2 print(answerAdd) def subtraction(num1, num2): answerSub=num1-num2 print(answerSub) def main(): num1=int(input('Enter the first number: ')) num2=int(input('Enter the second number: ')) print...
What am I doing wrong? Can't call earlier functions
def addition(num1, num2): answerAdd=num1+num2 print(answerAdd) def subtraction(num1, num2): answerSub=num1-num2 print(answerSub) def main(): num1=int(input('Enter the first number: ')) num2=int(input('Enter the second number: ')) print(addition, subtraction) main() I've tried renaming the c...
[ "You need to send the two parameters to the two functions:\nprint(addition(num1, num2), subtraction(num1, num2))\n\n", "A couple of problems:\n\nprint and return are not interchangeable. When you need your function to return a value you use return, when you merely need it to print something than use print. Your f...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074291419_python.txt
Q: Python Pandas - Set multiple variable types based on column names I have labeled my dataset columns systematically where the suffix of categorical variables have "_c" at the end and numeric fields have "_n". I would like python pandas code that will set the variable types based on the naming of the column headers....
Python Pandas - Set multiple variable types based on column names
I have labeled my dataset columns systematically where the suffix of categorical variables have "_c" at the end and numeric fields have "_n". I would like python pandas code that will set the variable types based on the naming of the column headers. So for all "_c" variables I need to set them to "category" and all "_...
[ "for col in df.columns:\n if col.endswith('_c'):\n df[col]=df[col].astype(str)\n if col.endswith('_n'):\n df[col]=df[col].astype(int)\ndf\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074291325_pandas_python.txt
Q: What parameters do I provide to the fit function of the FeatureAgglomeration in sklearn for precomputed distances? I want to use FeatureAgglomeration in SKLearn with a number of data points (each defined by multiple features) and a pre-defined affinity (or distance) matrix. I've used AgglomerativeClustering, with ...
What parameters do I provide to the fit function of the FeatureAgglomeration in sklearn for precomputed distances?
I want to use FeatureAgglomeration in SKLearn with a number of data points (each defined by multiple features) and a pre-defined affinity (or distance) matrix. I've used AgglomerativeClustering, with affinity set to precomputed, and in the fit function I've provided a matrix with my precomputed distances to much succes...
[ "I faced the same issue and the documentation is not helpful here. However, I figured out that fit() expects a distance matrix and transform() the feature matrix to be reduced in dimensionality. This becomes clear when reading the source code of FeatureAgglomeration, particularly the following two parts\nhttps://gi...
[ 0 ]
[]
[]
[ "cluster_analysis", "hierarchical_clustering", "python", "scikit_learn" ]
stackoverflow_0071390709_cluster_analysis_hierarchical_clustering_python_scikit_learn.txt
Q: Spotify Charts scrape data I want to scrape data from Spotify Charts for my Big Data projects, but since Spotify recently changed, it doesn't allow users to see the charts without logging in, my python code didn't work like before, because https://charts.spotify.com/ would redirect me to their home page instead of...
Spotify Charts scrape data
I want to scrape data from Spotify Charts for my Big Data projects, but since Spotify recently changed, it doesn't allow users to see the charts without logging in, my python code didn't work like before, because https://charts.spotify.com/ would redirect me to their home page instead of the link i want to scrape the d...
[ "I can't help you with the scraping process, but in case you're just interested in the data itself (as I was), this dataset on Kaggle has all the chart information from 2017 up until the end of 2021.\nIn case you also want to scrape more recent data, you could try reaching out to the guy who collected all that data...
[ 1 ]
[]
[]
[ "python", "spotify" ]
stackoverflow_0070558809_python_spotify.txt
Q: With "args" vs without "args" to pass arguments to a thread in Python I could pass "Test" with args to test() as shown below: import threading def test(arg): print(arg) # "Test" # Here thread = threading.Thread(target=test, args=("Test",)) thread.start() thread.join() A...
With "args" vs without "args" to pass arguments to a thread in Python
I could pass "Test" with args to test() as shown below: import threading def test(arg): print(arg) # "Test" # Here thread = threading.Thread(target=test, args=("Test",)) thread.start() thread.join() And, I could also pass "Test" without args to test() as shown below: import ...
[ "This does not call test in a new thread:\nthread = threading.Thread(target=test(\"Test\"))\nthread.start()\n\nHere's how Python interprets those lines of code:\n\nMain thread calls test(\"Test\").\ntest(\"Test\") returns None.\nMain thread calls Thread(target=None).*\nMain thread starts the new thread.\nNew thread...
[ 3 ]
[]
[]
[ "arguments", "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0074289000_arguments_multithreading_python_python_3.x_python_multithreading.txt
Q: Removing strings based on other strings in pandas Column A Column B JELLY ROSEN 15 JELLY STREET APT 111 JERSEY CITY, NJ 15 JELLY STREET APT 111 JERSEY CITY, NJ ROB ROSEN & STEVEN ROSEN 29 MAIN ST JERSEY CITY, NJ 29 MAIN ST JERSEY CITY, NJ I need the following: |** Column C ** | | JELLY ROSEN| | ROB ROSEN & STE...
Removing strings based on other strings in pandas
Column A Column B JELLY ROSEN 15 JELLY STREET APT 111 JERSEY CITY, NJ 15 JELLY STREET APT 111 JERSEY CITY, NJ ROB ROSEN & STEVEN ROSEN 29 MAIN ST JERSEY CITY, NJ 29 MAIN ST JERSEY CITY, NJ I need the following: |** Column C ** | | JELLY ROSEN| | ROB ROSEN & STEVEN ROSEN| I've tried something like this: d...
[ "You can try the below function to get the values into column c\ndef replace_values(x):\n cola, colb = x\n return cola.replace(colb,'')\n\ndf['Column C'] = df[['Column A', 'Column B']].apply(replace_values, axis=1)\n\n", "You can use regex :\nimport re\ndf[\"COLUMN C\"] = list(map(lambda x: re.match(r\"([^0...
[ 0, 0 ]
[]
[]
[ "pandas", "python", "string" ]
stackoverflow_0074291348_pandas_python_string.txt
Q: Geopandas buffer and intersect I am using the geojson file from the [OpenData Vancouver][1] website and I am trying to find the zoning classifications that fall within 5 kms of a "Historical Area". So, I am buffering all historical areas by 5kms (My data is projected), performing the intersect operation and using ...
Geopandas buffer and intersect
I am using the geojson file from the [OpenData Vancouver][1] website and I am trying to find the zoning classifications that fall within 5 kms of a "Historical Area". So, I am buffering all historical areas by 5kms (My data is projected), performing the intersect operation and using the intersect results as an index: b...
[ "Two core points\n\nneed to work in meters for a 5km buffer. Hence have used estimate_utm_crs() for projection. Have also use cap_style and join_style for a more reflective buffered polygon.\nhave used sjoin() instead of mask approach in your code. This will effectively give duplicates, so de-dupe using pandas ...
[ 0 ]
[]
[]
[ "geopandas", "geospatial", "python" ]
stackoverflow_0074290307_geopandas_geospatial_python.txt
Q: Vectorizing loop of row-plus-matrix operations I have matrices A (r x k) and B (m x k), and I want to add each row A[:,i] of the first to B in its entirety and return a separate matrix for each row of the first (equivalently, a 3d matrix of dimension r x m x k). I.e.: import numpy as np v = np.array([[1,2],[3,4]]...
Vectorizing loop of row-plus-matrix operations
I have matrices A (r x k) and B (m x k), and I want to add each row A[:,i] of the first to B in its entirety and return a separate matrix for each row of the first (equivalently, a 3d matrix of dimension r x m x k). I.e.: import numpy as np v = np.array([[1,2],[3,4]]) w = np.zeros((5,2)) def mysum(a,b): return np...
[ "Your arrays are:\nIn [193]: v.shape, w.shape\nOut[193]: ((2, 2), (5, 2))\n\nand the result shape: (2, 5, 2)\nWe can use broadcasting to do this:\nIn [195]: v[:,None,:]+w # (2,1,2) + (5,2)\nOut[195]: \narray([[[1., 2.],\n [1., 2.],\n [1., 2.],\n [1., 2.],\n [1., 2.]],\n\n ...
[ 1 ]
[]
[]
[ "for_loop", "multidimensional_array", "numpy", "python", "vectorization" ]
stackoverflow_0074290979_for_loop_multidimensional_array_numpy_python_vectorization.txt
Q: How to use python-docx-template to insert bullet points? I'm trying to insert bullet point text with docx-template. I know that it can be done with the standard docx like below; document.add_paragraph('text to be bulleted', style='List Bullet') But I just can't get the same thing to work on docx-template; rt = R...
How to use python-docx-template to insert bullet points?
I'm trying to insert bullet point text with docx-template. I know that it can be done with the standard docx like below; document.add_paragraph('text to be bulleted', style='List Bullet') But I just can't get the same thing to work on docx-template; rt = RichText() rt.add('text to be bulleted', style='List Bullet') ...
[ "Until this is officially supported (open issue), you might use a workaround (but only fixed indentations):\nIn your word document add this (with a real single bullet list item):\n{% for bullet in bullets %}\n ● {{ bullet }}{% endfor %}\n\nNote that the {% endfor %} must be in the same line to avoid blank lines be...
[ 1 ]
[]
[]
[ "python", "python_docx" ]
stackoverflow_0071835308_python_python_docx.txt
Q: Run Django on multiple ports Could someone tell me how I can run Django on two ports simultaneously? The default Django configuration only listens on port 8000. I'd like to run another instance on port xxxx as well. I'd like to redirect all requests to this second port to a particular app in my Django application....
Run Django on multiple ports
Could someone tell me how I can run Django on two ports simultaneously? The default Django configuration only listens on port 8000. I'd like to run another instance on port xxxx as well. I'd like to redirect all requests to this second port to a particular app in my Django application. I need to accomplish this with t...
[ "Just run two instances of ./manage.py runserver. You can set a port by simply specifying it directly: ./manage.py runserver 8002 to listen on port 8002.\nEdit I don't really understand why you want to do this. If you want two servers serving different parts of your site, then you have in effect two sites, which wi...
[ 18, 6, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003883497_django_python.txt
Q: How to find a distribution function from the max, min and average of a sample Given that I know the, Max, Min and Average of sample (I don't have access to the sample itself). I would like to write a generic function to generate a sample with the same characteristics. From this answer I gather that this is no simp...
How to find a distribution function from the max, min and average of a sample
Given that I know the, Max, Min and Average of sample (I don't have access to the sample itself). I would like to write a generic function to generate a sample with the same characteristics. From this answer I gather that this is no simple task since many distribuitions can be found with the same characteristics. max, ...
[ "Triangular distribution should perform your desired task since it takes three parameters (min, mode, max) as inputs that match your criteria. You can think of other distributions such as standard, uniform, and so on; however, all of their input parameters either lack or partially take one of the three input parame...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "python", "scipy", "statistics" ]
stackoverflow_0074184794_python_scipy_statistics.txt
Q: Local Variable refrenced before assignment I'm trying to index a list using a variable and "test" should check if indexer is out of date and then updating it through "maybe", I've tried using "global" but I don't think I understand it fully and I've also tried to put "indexer = indexer" but that also won't work. A...
Local Variable refrenced before assignment
I'm trying to index a list using a variable and "test" should check if indexer is out of date and then updating it through "maybe", I've tried using "global" but I don't think I understand it fully and I've also tried to put "indexer = indexer" but that also won't work. Any solutions? indexer = 0 list = ["no", "yes"] m...
[ "<< is not used for comparing values. see explanation.\nWhat you need is:\nif indexer < maybe:\n indexer = maybe\n\n", "Globals in general are a bad idea since they produce implicit assignations. Instead, is better to use return to explicitly update the values.\nIf you want the function to take arguments creat...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074291365_python.txt
Q: Indexing a BCOO in Jax I came across another problem in my attempts to learn jax: I have a sparse BCOO array, and an array holding indices. I need to obtain all values at these indices in the BCOO array. It would be ideal if the returned array would be a sparse BCOO as well. Using the usual slicing syntax seems to...
Indexing a BCOO in Jax
I came across another problem in my attempts to learn jax: I have a sparse BCOO array, and an array holding indices. I need to obtain all values at these indices in the BCOO array. It would be ideal if the returned array would be a sparse BCOO as well. Using the usual slicing syntax seems to not work. Is there a standa...
[ "[Edit: 2022-11-15] As of jax version 0.3.25, this kind of sparse indexing is directly supported in JAX:\nimport jax\nprint(jax.__version__)\n# 0.3.25\n\nsparse_array = sparse.bcoo_fromdense(full_array)\nresult = sparse_array[jnp.arange(3),indices]\n\nprint(result.todense())\n# [[2 2 2]\n# [0 0 0]\n# [1 1 1]]\n\n...
[ 0 ]
[]
[]
[ "jax", "python", "sparse_matrix" ]
stackoverflow_0074281298_jax_python_sparse_matrix.txt
Q: How do I save each iteration of a for loop in one big DataFrame - Python I want to gather all the historical prices of each stock in the S&P500 in Python. I'm using a package from IEX Cloud which gives me the historical prices of an individual stock. I want a for loop to run through a list of the tickers/symbols f...
How do I save each iteration of a for loop in one big DataFrame - Python
I want to gather all the historical prices of each stock in the S&P500 in Python. I'm using a package from IEX Cloud which gives me the historical prices of an individual stock. I want a for loop to run through a list of the tickers/symbols from the stock index so that I get all the data in a single DataFrame. This is ...
[ "Create an empty list to append to and concat everything together after you iterate over all the tickers\nimport pyEX as p\nimport pandas as pd\n\n\nstock_list = stocks['Ticker'].tolist()\nc = p.Client(api_token='TOKEN', version='stable')\ntimeframe = '2y'\n\ndfs = [] # create an empty list\nfor sym in stock_list:...
[ 0 ]
[]
[]
[ "api", "dataframe", "for_loop", "python", "stock" ]
stackoverflow_0074291712_api_dataframe_for_loop_python_stock.txt
Q: How to plot lat/long points but exclude some based on another variable? I'm using python to plot a fish population in a certain area and my lat/long coordinates indicate every trawl while recording where the species is/isn't. I want to plot all of my coordinates where the species is by excluding the coordinates wh...
How to plot lat/long points but exclude some based on another variable?
I'm using python to plot a fish population in a certain area and my lat/long coordinates indicate every trawl while recording where the species is/isn't. I want to plot all of my coordinates where the species is by excluding the coordinates where the abundance of the species is zero. Any ideas? This is my script right ...
[ "This should solve your issue.\ndt = pd.read_csv(data)\n\ndt = dt[dt['Abundance']>0]\n\nfig = px.scatter_geo(dt,lat='Lat',lon='Lon', hover_name=\"Abundance\")\nfig.update_layout(title = 'World Map: plot fish and hover to see abundance', title_x=0.5)\nfig.show()\n\ndt['Abundance']>0\n\nfinds all entries where the ab...
[ 0 ]
[]
[]
[ "exclude_constraint", "mapping", "python" ]
stackoverflow_0074291303_exclude_constraint_mapping_python.txt
Q: How to sort panda dataframe based on numbers in column name I have a data file with column names like this (numbers in the name from 1 to 32): inlet_left_cell-10<stl-unit=m>-imprint) inlet_left_cell-11<stl-unit=m>-imprint) inlet_left_cell-12<stl-unit=m>-imprint) ------- inlet_left_cell-9<stl-unit=m>-imprint) dat...
How to sort panda dataframe based on numbers in column name
I have a data file with column names like this (numbers in the name from 1 to 32): inlet_left_cell-10<stl-unit=m>-imprint) inlet_left_cell-11<stl-unit=m>-imprint) inlet_left_cell-12<stl-unit=m>-imprint) ------- inlet_left_cell-9<stl-unit=m>-imprint) data data data data data data data data data data .... .....
[ "There many ways to do it...I'm just posting simply way.\n\nSimply extract column names & sort them using natsort.\n\nAssuming Dataframe name as df..\nfrom natsort import natsorted, ns\ndfl=list(df) #used to convert column names to list\n\ndfl=natsorted(dfl, alg=ns.IGNORECASE) # sort based on subtsring numbers\n\nd...
[ 2, 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074291073_dataframe_pandas_python.txt
Q: how to fix the error of converting numbers to letters in text files using python I have a code that when I enter a number in Codeheroback it was converted to a literal . How can i fix it: Here my code: import os,re codeheroback = str(input('Nhập Code Tướng:')) checkskinid = '''<int name="heroId" value="" refPara...
how to fix the error of converting numbers to letters in text files using python
I have a code that when I enter a number in Codeheroback it was converted to a literal . How can i fix it: Here my code: import os,re codeheroback = str(input('Nhập Code Tướng:')) checkskinid = '''<int name="heroId" value="" refParamName="" useRefParam="false"/>''' with open('back.xml', 'r+' ,encoding = 'utf-8') as ...
[ "Your problem is that you formatted in a number after a \\1 in the literal replacement string. re's substitution syntax unfortunately can't tell the difference between a \\1 followed by a number and \\123. Per the docs, emphasis added:\n\n\\number\nMatches the contents of the group of the same number. Groups are nu...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074291237_python_regex.txt