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:
Using Textract, how do you extract tables from a pdf file and output it into a csv file via .py script?
I want to use textract (via aws cli) to extract tables from a pdf file (located in an s3 location) and export it into a csv file. I have tried writing a .py script but am struggling to read from the file.
Any s... | Using Textract, how do you extract tables from a pdf file and output it into a csv file via .py script? | I want to use textract (via aws cli) to extract tables from a pdf file (located in an s3 location) and export it into a csv file. I have tried writing a .py script but am struggling to read from the file.
Any suggestions for writing the .py script is welcome.
This is my current script. I run into the error:
File "ext... | [
"There is a much simpler way using the Amazon Textractor Textractor library. pip install amazon-textract-textractor\nThis will create a csv per table in your pdf document. e.g output_p0_t0.csv\nfrom textractor import Textractor\n\ndef extract_tables(s3_file_path, output_directory, s3_output_path):\n extractor = ... | [
1
] | [] | [] | [
"amazon_textract",
"amazon_web_services",
"python",
"text_extraction"
] | stackoverflow_0064340059_amazon_textract_amazon_web_services_python_text_extraction.txt |
Q:
Linked List problem dummy.next different different as head
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: Lis... | Linked List problem dummy.next different different as head | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListN... | [
"The idea to use this dummy is good, but then you shouldn't assign anything else to it. In your loop you should use another name for traversing the list -- not dummy: this could be a new name like curr, or you could even use head for it:\n dummy = ListNode()\n dummy.next = head\n while head and... | [
2
] | [] | [] | [
"linked_list",
"python"
] | stackoverflow_0074214495_linked_list_python.txt |
Q:
Check that function return types match the def statements in PR test in python
I have a Github Action that runs unit tests on each Pull Request (PR).
It effectively runs pytest.
Seeing that we leverage the type hints introduced in PEP 484, I'd like a method like this to cause a PR check fail:
def return_an_int() -... | Check that function return types match the def statements in PR test in python | I have a Github Action that runs unit tests on each Pull Request (PR).
It effectively runs pytest.
Seeing that we leverage the type hints introduced in PEP 484, I'd like a method like this to cause a PR check fail:
def return_an_int() -> int:
return 'not an int'
Is there a simple way to run such a "compilation" test... | [
"This is the kind of type checking that mypy does, so you could include running mypy in your Action workflow.\nIf your module and its dependencies are already installed in your workflow, this step should do the trick:\n - name: Run mypy\n run: |\n # needed if mypy isn't already installed\n ... | [
4
] | [] | [] | [
"automated_tests",
"pull_request",
"pytest",
"python",
"types"
] | stackoverflow_0074214488_automated_tests_pull_request_pytest_python_types.txt |
Q:
Option menu widget in tkinter wont show beyond option number 1167
I have a long list of options for an option menu widget, but the menu always ends at option number 1167.
Here is the code:
from tkinter import *
root = Tk()
root.geometry( "200x200" )
options = [str(i) for i in range(2000)]
selected = Stri... | Option menu widget in tkinter wont show beyond option number 1167 | I have a long list of options for an option menu widget, but the menu always ends at option number 1167.
Here is the code:
from tkinter import *
root = Tk()
root.geometry( "200x200" )
options = [str(i) for i in range(2000)]
selected = StringVar()
selected.set( "1" )
drop = OptionMenu( root , selected , op... | [
"If anyone else gets themselves into this situation, I recommend the alternative I used: using a listbox instead. The code I wrote below isnt great, but it shows the basic idea.\nFor more info on the Listbox widget, visit: https://www.geeksforgeeks.org/python-tkinter-listbox-widget/ and https://www.geeksforgeeks.or... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074174172_python_tkinter.txt |
Q:
Combine 2 heatmaps in one chart
In my problem at hand, I want to combine 2 heatmaps in one chart. The following example creates a heatmap that captures the number of units sold with stores on the x-axis and books on the y-axis. Now, it is reasonable to assume that the units are sold through two different distribut... | Combine 2 heatmaps in one chart | In my problem at hand, I want to combine 2 heatmaps in one chart. The following example creates a heatmap that captures the number of units sold with stores on the x-axis and books on the y-axis. Now, it is reasonable to assume that the units are sold through two different distribution channels: stores (S) and online (... | [
"The expected output (with similar colorbars) can be very much achieved by creating a data frame in which alternate columns are data from channel S and A.\nThen the code you have written is already in a right condition to get the expected output with minor changes:\nCode:\nimport numpy as np\nimport matplotlib.pypl... | [
0
] | [] | [] | [
"heatmap",
"matplotlib",
"python"
] | stackoverflow_0074212782_heatmap_matplotlib_python.txt |
Q:
For loop to populate a PDF with FPDF
I have generated a report in python that looks similar to the one below that I've taken from this tutorial.
While this page is easy to set up if you manually enter the path to each image, like this:
pdf.add_page()
pdf.image("/Users/Foo/Graph1.png", 5, 20, WIDTH/2-10)... | For loop to populate a PDF with FPDF | I have generated a report in python that looks similar to the one below that I've taken from this tutorial.
While this page is easy to set up if you manually enter the path to each image, like this:
pdf.add_page()
pdf.image("/Users/Foo/Graph1.png", 5, 20, WIDTH/2-10)
pdf.image("/Users/Foo/Graph2.png", W... | [
"You could try something like:\ndef addtopage(function):\n png_count = 0\n start_y = 20\n img_ht = 90\n for f in os.listdir('path'):\n if f.endswith('png') in f:\n if png_count%2 == 0\n pdf.image(f, 5, start_y, WIDTH/2-10)\n else:\n pdf.image(f, WIDTH/2-10, start... | [
1
] | [] | [] | [
"anaconda",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074212332_anaconda_jupyter_notebook_pandas_python.txt |
Q:
Modifying array elements based on an absolute difference value
I have two arrays of the same length as shown below.
import numpy as np
y1 = [12.1, 6.2, 1.4, 0.8, 5.6, 6.8, 8.5]
y2 = [8.2, 5.6, 2.8, 1.4, 2.5, 4.2, 6.4]
y1_a = np.array(y1)
y2_a = np.array(y2)
print(y1_a)
print(y2_a)
for i in range(len(y2_a)):
y3... | Modifying array elements based on an absolute difference value | I have two arrays of the same length as shown below.
import numpy as np
y1 = [12.1, 6.2, 1.4, 0.8, 5.6, 6.8, 8.5]
y2 = [8.2, 5.6, 2.8, 1.4, 2.5, 4.2, 6.4]
y1_a = np.array(y1)
y2_a = np.array(y2)
print(y1_a)
print(y2_a)
for i in range(len(y2_a)):
y3_a[i] = abs(y2_a[i] - y2_a[i])
I am computing the absolute differen... | [
"First of all, let numpy do the lifting for you. You can calculate your absolute differences without a manual for loop:\nabs_diff = np.abs(y2_a - y1_a) # I assume your original code has a typo\n\nNow you can get all the values where the absolute difference is more than 2.0:\ny3_a = y1_a\ny3_a[abs_diff > 2.0] = y2_a... | [
1
] | [] | [] | [
"arrays",
"indexing",
"numpy",
"python"
] | stackoverflow_0074214445_arrays_indexing_numpy_python.txt |
Q:
How to obtain multiple substring from a long text using a string as the starting value
Overall I have one string and I am trying to create substrings based on a given word.So let's say the given word is apple and the text is about different kind of fruits.
Text:
"Fruits are tasty. Apples can be red. Bananas are ye... | How to obtain multiple substring from a long text using a string as the starting value | Overall I have one string and I am trying to create substrings based on a given word.So let's say the given word is apple and the text is about different kind of fruits.
Text:
"Fruits are tasty. Apples can be red. Bananas are yellow. Apples can also be yellow."
How would I go about getting the characters after the word... | [
"The regex library \"re\" works well for this and you can use re.finditer() to iterate over any matching groups found indicated by the pattern:\nimport re\nstr=\"Fruits are tasty. Apples can be red. Bananas are yellow. Apples can also be yellow.\"\npattern=\"apple\"\namt=10\n\nfor match in re.finditer(pattern,str,r... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074214396_python.txt |
Q:
Downloading images from wikipedia gives forbidden error due to User Agent policy
I am trying to scrape some actors images from Wikipedia using python and constantly get the following error HTTPError: 403 Client Error: Forbidden. Please comply with the User-Agent policy: https://meta.wikimedia.org/wiki/User-Agent_p... | Downloading images from wikipedia gives forbidden error due to User Agent policy | I am trying to scrape some actors images from Wikipedia using python and constantly get the following error HTTPError: 403 Client Error: Forbidden. Please comply with the User-Agent policy: https://meta.wikimedia.org/wiki/User-Agent_policy for url: https://upload.wikimedia.org/wikipedia/commons/0/0a/Christian_Bale-7837... | [
"It should be requests.get(url, headers=headers).\nThat said, don't just put in some random string you pulled from Google as the user agent. That's impolite and might get you banned if you generate significant traffic. Indicate who you are and what tool you are using, as asked in the user-agent policy. Something li... | [
1
] | [] | [] | [
"python",
"web_scraping",
"wikipedia"
] | stackoverflow_0074195067_python_web_scraping_wikipedia.txt |
Q:
select number from random set
when I generate a random set, I need to define each number in a different variable. I'm using random.sample() but the number are being repeated.
import random
#Generate 3 random numbers between 1 and 30
random_listOne = random.sample(range(1, 30), 3)
print(random_listOne)
valueOne = ... | select number from random set | when I generate a random set, I need to define each number in a different variable. I'm using random.sample() but the number are being repeated.
import random
#Generate 3 random numbers between 1 and 30
random_listOne = random.sample(range(1, 30), 3)
print(random_listOne)
valueOne = random.sample(random_listOne, 1)
va... | [
"because for the part where you are picking out the random generated numbers, so valueOne, valueTwo, etc, you are picking out the generated numbers randomly, meaning that valueOne may have the same number as valueTwo since both have an equal chance at selecting one of the three generated numbers by random.listOne.\... | [
0,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074214624_python_random.txt |
Q:
How do I append values to make a multi-dimentional list?
My code:
list=[["Uno","Dos"],[1,2],["Tres","Cuatro"],[3,4]]
print(list)
list[4][0].insert(A)
New_list=[[],[],[],[]]
A=list[0][0]+str(list[1][0])
B=(list[0][0]+str(list[1][0]))[::-1]
C=list[0][1]+str(list[1][1])
D=(list[0][1]+str(list[1][1]))[::-1]
E=list... | How do I append values to make a multi-dimentional list? | My code:
list=[["Uno","Dos"],[1,2],["Tres","Cuatro"],[3,4]]
print(list)
list[4][0].insert(A)
New_list=[[],[],[],[]]
A=list[0][0]+str(list[1][0])
B=(list[0][0]+str(list[1][0]))[::-1]
C=list[0][1]+str(list[1][1])
D=(list[0][1]+str(list[1][1]))[::-1]
E=list[2][0]+str(list[3][0])
F=(list[2][0]+str(list[3][0]))[::-1]
G=... | [
"append appends a value to your list inline. list[4][0] gives an error, because that value does not exist yet. With insert you can add entries to your list and specify the location as well where you want the entry to be insert, whereas append always attaches to the end of the list.\nExample:\nl = []\nl.append(\"a\"... | [
0,
0,
0,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074214453_list_python.txt |
Q:
Python: replacing all appearances of a class constructor in superclass from subclass
This is probably a stupid question. But I encountered this need when writing a tool that needs to slightly modify the API from an existing package. The minimal example is as such
class Foo:
def __init__(self):
print("f... | Python: replacing all appearances of a class constructor in superclass from subclass | This is probably a stupid question. But I encountered this need when writing a tool that needs to slightly modify the API from an existing package. The minimal example is as such
class Foo:
def __init__(self):
print("foo")
class Qux(Foo):
def __init__(self):
print("qux")
cl... | [
"What you need there is called \"monkey patching\" - an operation possible in dynamic languages such as Javascript, Python and Ruby, in which either a module level variable or an attribute of a class/instance is replaced by other at runtime.\nIt is popular with testing, as it allows one to replace functions and cla... | [
1
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0074214215_inheritance_oop_python.txt |
Q:
Child Class names in logger
I have the following code:
class LogMixin(object):
def __init__(self, log_name, log_level=logging.INFO):
self.project_name = self.__class__.__name__
self.log_level = log_level
self.log_name = log_name
self.log_file_path = (r"\\Logging\\{}_{}.log".form... | Child Class names in logger | I have the following code:
class LogMixin(object):
def __init__(self, log_name, log_level=logging.INFO):
self.project_name = self.__class__.__name__
self.log_level = log_level
self.log_name = log_name
self.log_file_path = (r"\\Logging\\{}_{}.log".format(self.log_name, datetime.dateti... | [
"Your implementation of classes is a bit troublesome. Avoid calling a separate _get_logger and log methods entirely\nclass LogMixin(object):\n\n def __init__(self, parent=None, log_name=\"\", log_level=logging.INFO):\n self.project_name = parent.__class__.__name__\n self.log_level = log_level\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074214063_python.txt |
Q:
Data loss while extracting the rows from large csv file
This is in continuation from my previous question. I have 2 files, file1.csv and a large csv called master_file.csv. They have several columns and have a common column name called EMP_Code.
File 1 example:
EMP_name
EMP_Code
EMP_dept
b
f367
abc
a
c264
xyz
... | Data loss while extracting the rows from large csv file | This is in continuation from my previous question. I have 2 files, file1.csv and a large csv called master_file.csv. They have several columns and have a common column name called EMP_Code.
File 1 example:
EMP_name
EMP_Code
EMP_dept
b
f367
abc
a
c264
xyz
c
d264
abc
master_file example:
EMP_name EMP_age ... | [
"You just have to pass chunksize=<SOME INTEGER> to pandas' .read_csv function (see documentation here)\nIf you pass a chunksize=2, you will read the file into dataframes of 2 rows. Or... more accurately, it will read 2 rows of the csv into a dataframe. You can then apply your filter to that 2-row dataframe and \"ac... | [
1,
1,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074212516_csv_python.txt |
Q:
Why does Python swap the top two elements of the stack for swapping two variables?
The following Python code:
a = 1
b = 2
a, b = b, a
compiles to the following Python bytecode:
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (a)
2 4 LOAD_CONST 1... | Why does Python swap the top two elements of the stack for swapping two variables? | The following Python code:
a = 1
b = 2
a, b = b, a
compiles to the following Python bytecode:
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (a)
2 4 LOAD_CONST 1 (2)
6 STORE_NAME 1 (b)
3 8 LOAD_NAME ... | [
"\nMy understanding is that, in order to swap a and b, you could just push a, then push b, then store the stacktop in a, then store the stacktop in b, achieving the variable swap.\n\nYou could, but that would read a first. a, b = b, a says to read b first.\nThat usually doesn't matter, but it can if you're executin... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074214687_python.txt |
Q:
Show all errors in json schema using json validate using python
I am writing a Python code to validate JSON schema but it is not showing all the errors in it , only the first one. Can anyone help to fix the code so that it displays all the errors.
Below is the code:
from __future__ import print_function
import sys... | Show all errors in json schema using json validate using python | I am writing a Python code to validate JSON schema but it is not showing all the errors in it , only the first one. Can anyone help to fix the code so that it displays all the errors.
Below is the code:
from __future__ import print_function
import sys
import json
import jsonschema
from jsonschema import validate
schem... | [
"To get all the validation errors in a single instance, use iter_errors() method of the validator class.\neg.:\nimport jsonschema\n\nschema = {\n \"type\" : \"object\",\n \"properties\" : {\n \"price\" : {\"type\" : \"number\"},\n \"name\" : {\"type\" : \"string\"},\n },\n}\ndata = { \"name\"... | [
13,
0,
0
] | [] | [] | [
"json",
"python",
"validation"
] | stackoverflow_0052196407_json_python_validation.txt |
Q:
How to update Python version in Terminal?
I've updated my version of Python to 3.11, but Terminal is printing different versions, depending on what command I enter.
Entering python3 --version prints Python 3.9.13.
Entering python --version prints Python 3.9.6.
When I go to the actual Python framework, I can see th... | How to update Python version in Terminal? | I've updated my version of Python to 3.11, but Terminal is printing different versions, depending on what command I enter.
Entering python3 --version prints Python 3.9.13.
Entering python --version prints Python 3.9.6.
When I go to the actual Python framework, I can see that 3.11 is installed and is the current version... | [
"A terminal in a unix-based OS (including Darwin / MacOS and Linux) will search for the command you have typed in several places, in order, and the first match found will stop the search from finding other possible commands with the same name.\nTo simplify the answer, I'll limit this to the bash shell as I don't us... | [
2,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074214615_python_python_3.x.txt |
Q:
How to print list with newline python?
I have a list like this.
[['Year', 'Salary', 'Yearly Income'],
[2, 2500, 30000],
[2, 3000.0, 36000.0],
[2, 3600.0, 43200.0],
[2, 4320.0, 51840.0],
[2, 5184.0, 62208.0],
[2, 6220.8, 74649.6]
]
I need print Like this
How can I do that in Python?
here is my code
wo... | How to print list with newline python? | I have a list like this.
[['Year', 'Salary', 'Yearly Income'],
[2, 2500, 30000],
[2, 3000.0, 36000.0],
[2, 3600.0, 43200.0],
[2, 4320.0, 51840.0],
[2, 5184.0, 62208.0],
[2, 6220.8, 74649.6]
]
I need print Like this
How can I do that in Python?
here is my code
work_experience = 0
year = 1
cnt =0
basic_sala... | [
"In the most simple version you can use string formatting to display your data:\nprint('{:<4} {:<6}\\t{:<13}'.format(*salary_list[0]))\nfor row in salary_list[1:]:\n print('{:<4} {:<6.2f}\\t{:<13.2f}'.format(*row))\n\n\nYear Salary Yearly Income\n2 2500.00 30000.00 \n2 3000.00 3600... | [
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074214606_python.txt |
Q:
Customized operation on 2 numpy arrays with standard scalar product structure
Is there any way to exploit the standard scalar product structure between two arrays in a customized way?
To make it more understandable, I would like to use this type of operation:
arr1 = array([a1,b1])
arr2 = array([a2,b2])
scalar_prod... | Customized operation on 2 numpy arrays with standard scalar product structure | Is there any way to exploit the standard scalar product structure between two arrays in a customized way?
To make it more understandable, I would like to use this type of operation:
arr1 = array([a1,b1])
arr2 = array([a2,b2])
scalar_product = arr1@arr2
-> where scalar_product is equal to: a1 * a2 + b1 * b2
But instead... | [
"The following is based on companion matrices and some clever linear algebra. I believe it works correctly, but I will leave it to you to find some examples to error check my method.\nimport numpy as np\n\nclass GF8(object):\n\n def __init__(self):\n poly_coeff = np.array([1,0,1,1,0,0,1,0],dtype = int)\n ... | [
0
] | [] | [] | [
"arrays",
"customization",
"numpy",
"product",
"python"
] | stackoverflow_0074212034_arrays_customization_numpy_product_python.txt |
Q:
INSERT or UPDATE ON DUPLICATE KEY with SQLAlchemy ORM
I'm looking for a function in MYSQLAlchemy's ORM to make a statement for all rows in dataset to load in DDBB at once with insert or update un duplicate key, but only found to execute row by row.
Actually I'm using the following code:
for orm_object in orm_mappe... | INSERT or UPDATE ON DUPLICATE KEY with SQLAlchemy ORM | I'm looking for a function in MYSQLAlchemy's ORM to make a statement for all rows in dataset to load in DDBB at once with insert or update un duplicate key, but only found to execute row by row.
Actually I'm using the following code:
for orm_object in orm_mapped_object:
session.merge(orm_object )
session.commit()
... | [
"You are probably looking for on_duplicate_key_update\n"
] | [
0
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0074208312_orm_python_sqlalchemy.txt |
Q:
ImportError: No module named tensorflow
Please help me with this error
I have installed the tensorflow module on my server and below is it's information
15IT60R19@cpusrv-gpu-109:~$ pip show tensorflow
Name: tensorflow
Version: 1.0.0
Summary: TensorFlow helps the tensors flow
Home-page: http://tensorflow.org/
Autho... | ImportError: No module named tensorflow | Please help me with this error
I have installed the tensorflow module on my server and below is it's information
15IT60R19@cpusrv-gpu-109:~$ pip show tensorflow
Name: tensorflow
Version: 1.0.0
Summary: TensorFlow helps the tensors flow
Home-page: http://tensorflow.org/
Author: Google Inc.
Author-email: opensource@googl... | [
"Try installing tensorflow again with the whatever version you want and with option --ignore-installed like:\npip install tensorflow==1.2.0 --ignore-installed\n\nI solved same issue using this command.\n",
"I had a more basic problem when I received this error.\nThe \"Validate your installation\" instructions say... | [
54,
34,
27,
26,
12,
10,
8,
6,
4,
3,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"installation",
"module",
"pip",
"python",
"tensorflow"
] | stackoverflow_0042244198_installation_module_pip_python_tensorflow.txt |
Q:
python time series missing y axis label 'observed'
I have the following dataset and try to plot the decomposition of the time series. The plot gives me Trend, Seasonal and Resid as Y labeling but the label for the first subplot 'observed' is missing. How can I add the label?
from statsmodels.tsa.seasonal import se... | python time series missing y axis label 'observed' | I have the following dataset and try to plot the decomposition of the time series. The plot gives me Trend, Seasonal and Resid as Y labeling but the label for the first subplot 'observed' is missing. How can I add the label?
from statsmodels.tsa.seasonal import seasonal_decompose
df_event_decompose.head()
... | [
"You can add the 'Observed' y-axis label manually after plotting the DecomposeResult object like so:\nfrom statsmodels.tsa.seasonal import seasonal_decompose\n\nsd_results = seasonal_decompose(data) \nfig = sd_results.plot()\n\nCheck the current y-axis labels:\nfig.axes\n\nwhich will return:\n[<AxesSubplot:>,\n <Ax... | [
0
] | [] | [] | [
"plot",
"python",
"time_series"
] | stackoverflow_0071696883_plot_python_time_series.txt |
Q:
Issue with aiohttp in Buildozer
I've ran into an issue trying to convert my Kivy app to an apk using Buildozer. The app performs as intended when ran through Python, and I have no issues getting Buildozer to produce an apk. I've gone down a rabbit hole of trial and error adding all of the needed modules to the .sp... | Issue with aiohttp in Buildozer | I've ran into an issue trying to convert my Kivy app to an apk using Buildozer. The app performs as intended when ran through Python, and I have no issues getting Buildozer to produce an apk. I've gone down a rabbit hole of trial and error adding all of the needed modules to the .spec file as it failed to run. Now, I a... | [
"It seems like an issue at import aiohttp as its' newer versions require newer versions of async-timeout that fails with the error (see the original comment by @csira).\nTo fix this issue I pinned the next versions in buildozer.spec:\nrequirements = python3, kivy, aiohttp==v3.7.4, aiosignal, frozenlist, async-timeo... | [
0
] | [] | [] | [
"buildozer",
"kivy",
"python"
] | stackoverflow_0071805923_buildozer_kivy_python.txt |
Q:
I am getting this error: requests.exceptions.ProxyError:
I am running this simple code:
import requests
x = requests.get('https://w3schools.com/python/demopage.htm')
print(x.text)
However, I am getting this error
requests.exceptions.ProxyError: HTTPSConnectionPool(host='w3schools.com', port=443): Max retries exc... | I am getting this error: requests.exceptions.ProxyError: | I am running this simple code:
import requests
x = requests.get('https://w3schools.com/python/demopage.htm')
print(x.text)
However, I am getting this error
requests.exceptions.ProxyError: HTTPSConnectionPool(host='w3schools.com', port=443): Max retries exceeded with url: /python/demopage.htm (Caused by ProxyError('Yo... | [
"It's wqorking fine without any issues.\nimport requests\nx = requests.get('https://w3schools.com/python/demopage.htm')\nprint(x.text)\n\nOutput:\n<html>\n<body>\n\n<h1>This is a Test Page</h1>\n\n</body>\n</html>\n\n",
"I actually had a proxy issue. So I just set up proxy dict for https and http and pass proxies... | [
1,
1
] | [] | [] | [
"get",
"python",
"python_requests"
] | stackoverflow_0074213976_get_python_python_requests.txt |
Q:
How to subset pandas df based on two columns?
I need to subset rows of df based on two columns (c1 and c2 columns) which have strings.
I need to be able to return rows where one value in c1 is associated with only 2 different values in c2. col4-6 are irrelevant for subsetting and just need to be returned.
Code to ... | How to subset pandas df based on two columns? | I need to subset rows of df based on two columns (c1 and c2 columns) which have strings.
I need to be able to return rows where one value in c1 is associated with only 2 different values in c2. col4-6 are irrelevant for subsetting and just need to be returned.
Code to recreate df
df = pd.DataFrame({"": [0,1,2,3,4,5,6,... | [
"here is one way to do it\n#using transform, return a boolean on unique values matching the count\n# and filter the dataframe\ndf[df.groupby('c1')['c2'].transform(lambda x: x.nunique()==2)]\n\nc1 c2 c3 col4 col5 col6\n2 2 dfg alpha 2 777 13 4\n3 3 dfg bravo 3 775 12 3\n4 ... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"subset"
] | stackoverflow_0074214838_dataframe_pandas_python_subset.txt |
Q:
how to upload local pdf files to google collab notebook?
I want to upload a local pdf into google collab and parse it with python.
How can I load the file so I could use with open?
A:
press on the file picture on the side bar (table of contents)
press on "upload session to storage" and notice it now appears on ... | how to upload local pdf files to google collab notebook? | I want to upload a local pdf into google collab and parse it with python.
How can I load the file so I could use with open?
| [
"\npress on the file picture on the side bar (table of contents)\n\n\npress on \"upload session to storage\" and notice it now appears on the list below. \n\nright click on the 3 dots on the right side of the name of the file. \n\nchoose \"copy path\".\n\nuse this path in your code just as you would locally.\n\n\... | [
0
] | [] | [] | [
"file",
"google_colaboratory",
"pdf_parsing",
"python"
] | stackoverflow_0074214905_file_google_colaboratory_pdf_parsing_python.txt |
Q:
Generate a random alphanumeric string as a primary key for a model
I would like a model to generate automatically a random alphanumeric string as its primary key when I create a new instance of it.
example:
from django.db import models
class MyTemporaryObject(models.Model):
id = AutoGenStringField(lenght=16, ... | Generate a random alphanumeric string as a primary key for a model | I would like a model to generate automatically a random alphanumeric string as its primary key when I create a new instance of it.
example:
from django.db import models
class MyTemporaryObject(models.Model):
id = AutoGenStringField(lenght=16, primary_key=True)
some_filed = ...
some_other_field = ...
in my... | [
"One of the simplest way to generate unique strings in python is to use uuid module. If you want to get alphanumeric output, you can simply use base64 encoding as well:\nimport uuid\nimport base64\nuuid = base64.b64encode(uuid.uuid4().bytes).replace('=', '')\n# sample value: 1Ctu77qhTaSSh5soJBJifg\n\nYou can then p... | [
15,
5,
3,
0
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0020392497_django_postgresql_python.txt |
Q:
How would I extract names separated by dots (.) and hyphens (-) in Python and just list them in a text file?
I have CSV containing multiple emails in multiple columns extracted from my email inbox.
emails are held within pointy brackets such as this:
<name-name.name@domain.com>, name.name@domain.com
emails are als... | How would I extract names separated by dots (.) and hyphens (-) in Python and just list them in a text file? | I have CSV containing multiple emails in multiple columns extracted from my email inbox.
emails are held within pointy brackets such as this:
<name-name.name@domain.com>, name.name@domain.com
emails are also listed inside text of emails I would like to pull out
I would like to extract each name fragment and just list t... | [
"Try this for a few lines in your file:\nimport re\nfile = ['<name-name.name@domain.com>, name.name@domain.com']\nres=[re.findall(r'([-\\w.]+)@',line) for line in file ]\nt = []\nfor ele in res:\n for match in ele:\n t.extend(re.split(r'[-.]',match))\n\n",
"Based on the example provided, her... | [
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074167216_python_regex.txt |
Q:
TypeError: function() argument 'code' must be code, not str
TypeError: function() argument 'code' must be code, not str
my main file
with open("city.txt","r") as f:
d2 = f.read()
d2=d2.strip()
if len(d2)!=0 or len(d2)!=1:
m=d2
else:
m="new york"
import asyncio
import python_weather
async def getweathe... | TypeError: function() argument 'code' must be code, not str | TypeError: function() argument 'code' must be code, not str
my main file
with open("city.txt","r") as f:
d2 = f.read()
d2=d2.strip()
if len(d2)!=0 or len(d2)!=1:
m=d2
else:
m="new york"
import asyncio
import python_weather
async def getweather():
client = python_weather.Client(format=python_weather.IMP... | [
"I believe the last line in your main file should be indented so that it is inside the function. This is based on the example code as found on the python-weather module page: https://pypi.org/project/python-weather/\nI am assuming that the variable m has been defined in your main file although it is not shown in y... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0072676144_python.txt |
Q:
Generate 2 random numbers in a loop that have a range of -5 and 5 and have to be displayed from smallest to biggest
My given instructions:
Write a program that continually generates 2 numbers between -5 and 5. After each number is generated, display each pair from smallest to biggest along with the sum of the pair... | Generate 2 random numbers in a loop that have a range of -5 and 5 and have to be displayed from smallest to biggest | My given instructions:
Write a program that continually generates 2 numbers between -5 and 5. After each number is generated, display each pair from smallest to biggest along with the sum of the pair.
The program stops when the program generates a pair that is the negative of the other (for example, -5 and 5 or -2 and ... | [
"I think my code below is self-explanatory. yet if you had any doubts or questions, I'm happy to explain\n# random is a python built-in library which has multiple functions regarding random events\nimport random\n\ntotal_sum = 0\n\n# a while loop with a final break statement is the closest idiomatic way for a do-wh... | [
0,
0
] | [
"import random\n\ntotal = 0\n\nwhile True:\n number1 = random.randint(-5,5)\n number2 = random.randint(-5,5)\n\n total += number1 + number2\n\n if number1 > number2:\n print(f\"{number2} {number1} total: {total}\")\n elif number1 < number2:\n print(f\"{number1} {number2} total: {total}\... | [
-1
] | [
"loops",
"python",
"ranged_loops"
] | stackoverflow_0074214776_loops_python_ranged_loops.txt |
Q:
Is intel_extension_for_pytorch compatible with anaconda?
I have an intel gpu which is not cuda compatible, so I'm spending a lot of time training small-ish nets on my cpu. I found that there is a package called intel_extension_for_pytorch that is available to run on pytorch. When trying to install it in my Anaco... | Is intel_extension_for_pytorch compatible with anaconda? | I have an intel gpu which is not cuda compatible, so I'm spending a lot of time training small-ish nets on my cpu. I found that there is a package called intel_extension_for_pytorch that is available to run on pytorch. When trying to install it in my Anaconda environment though, I receive the error:
Collecting packag... | [
"https://www.anaconda.com/blog/using-pip-in-a-conda-environment\nsometimes there is no conda.. its possible to use both, though pip doesnt do versioning as well as conda.\n"
] | [
0
] | [] | [] | [
"intel",
"machine_learning",
"neural_network",
"python",
"pytorch"
] | stackoverflow_0074210551_intel_machine_learning_neural_network_python_pytorch.txt |
Q:
Insert data from buckets to tables of Cloud SQL for SQL Server instance using local python
I am trying to insert data (txt files) from buckets to Cloud SQL for SQL Server instance using my local python.
I can connect to the buckets but I have trouble connecting to the SQL Server instance and make a insert data fro... | Insert data from buckets to tables of Cloud SQL for SQL Server instance using local python | I am trying to insert data (txt files) from buckets to Cloud SQL for SQL Server instance using my local python.
I can connect to the buckets but I have trouble connecting to the SQL Server instance and make a insert data from the txt files
import os, sys
from google.cloud import storage
os.environ['GOOGLE_APPLICATION_... | [
"You can use the Cloud SQL Python connector :\nGithub Cloud SQL Python connector\nPyPi Cloud SQL Python connector\nAccording the documentation, the Cloud SQL Python Connector is a package to be used alongside a database driver. Currently supported drivers are:\npymysql (MySQL)\npg8000 (PostgreSQL)\nasyncpg (Postgre... | [
3
] | [] | [] | [
"google_cloud_platform",
"google_cloud_sql",
"python",
"sql_server"
] | stackoverflow_0074212808_google_cloud_platform_google_cloud_sql_python_sql_server.txt |
Q:
Having trouble with a function that has to split a string into roman numbers weights
i wrote this code:
admitted_List = [1, 5, 10, 50, 100, 500, 1000]
tempString = ""
finalList = []
for i in range(len(xkcd)-1):
if int(xkcd[i] + xkcd[i+1]) in admitted_List:
tempString += xkcd[i]
continue
els... | Having trouble with a function that has to split a string into roman numbers weights | i wrote this code:
admitted_List = [1, 5, 10, 50, 100, 500, 1000]
tempString = ""
finalList = []
for i in range(len(xkcd)-1):
if int(xkcd[i] + xkcd[i+1]) in admitted_List:
tempString += xkcd[i]
continue
else:
tempString += xkcd[i]
finalList.append(int(tempString))
tempStr... | [
"Set the list of numbers from higher to lower value\nThe idea for this snippet of code is to list the decimal numbers corresponding to roman numbers from bigger value to lower value (see the new definition of variable admitted_List).\nYour code become the following:\ndef func(xkcd): \n admitted_List = [\"1000... | [
1,
1
] | [] | [] | [
"list",
"python",
"python_3.x",
"roman_numerals",
"string"
] | stackoverflow_0074214700_list_python_python_3.x_roman_numerals_string.txt |
Q:
Dataflow streaming job processes the same element many times at the same time
Short description:
Dataflow is processing the same input element many times, even at the same time in parallel (so this is not fail-retry build-in mechanism of dataflow, because previous process didn't fail).
Long description:
Pipeline g... | Dataflow streaming job processes the same element many times at the same time | Short description:
Dataflow is processing the same input element many times, even at the same time in parallel (so this is not fail-retry build-in mechanism of dataflow, because previous process didn't fail).
Long description:
Pipeline gets pubsub message in which path to GCS file is stored.
In next step (DoFn class) t... | [
"When a file is added on Cloud storage and fire an automatic notification to Pub Sub, multiple notifications can be sent :\n- OBJECT_FINALIZE Sent when a new object (or a new generation of an existing object) is successfully created in the bucket. This includes copying or rewriting an existing object. A failed up... | [
1,
1
] | [] | [] | [
"apache_beam",
"google_cloud_dataflow",
"python"
] | stackoverflow_0074179315_apache_beam_google_cloud_dataflow_python.txt |
Q:
Efficiently merge GeoDataFrames if Polygon from one contains Point from second
i have two GeoDataFrames
gdf_point:
Unnamed: 0 latitude longitude geometry
0 0 50.410203 7.236583 POINT (7.23658 50.41020)
1 1 51.303545 7.263082 POINT (7.26308 51.30354)
2 ... | Efficiently merge GeoDataFrames if Polygon from one contains Point from second | i have two GeoDataFrames
gdf_point:
Unnamed: 0 latitude longitude geometry
0 0 50.410203 7.236583 POINT (7.23658 50.41020)
1 1 51.303545 7.263082 POINT (7.26308 51.30354)
2 2 50.114965 8.672785 POINT (8.67278 50.11496)
and gdf_poly:
... | [
"To merge two dataframes on their geometries (not on column or index values), use one of geopandas's spatial joins. They have a whole section of the docs about it - it's great - give it a read!\nThere are two workhorse spatial join functions in geopandas:\n\nGeoDataFrame.sjoin joins two dataframes based on a binary... | [
0
] | [] | [] | [
"geopandas",
"pandas",
"python"
] | stackoverflow_0074211441_geopandas_pandas_python.txt |
Q:
How to print line number of element if it equals specific format given in one XML searched in another XML
Example of my XML1 consists of format of Equal element :
<Operator>
<Equal>
<Data>OPERATING_MODE</Data>
<Data>2</Data>
</Equal>
<Equal>
<Integer>Remote_Request</Integer>
... | How to print line number of element if it equals specific format given in one XML searched in another XML | Example of my XML1 consists of format of Equal element :
<Operator>
<Equal>
<Data>OPERATING_MODE</Data>
<Data>2</Data>
</Equal>
<Equal>
<Integer>Remote_Request</Integer>
<Data>2</Data>
</Equal>
<Equal>
<Integer>Real_area</Integer>
<Integer>2</Integer>
... | [
"The xpath on the for-loop can be changed to find Data elements with a Label child AND an Equal child with 2 children\n//System1//Data[Label and .//Equal//*[2]]\nfor service in doc.xpath('//System1//Data[Label and .//Equal//*[2]]'):\n value = service.xpath('.//Equal//*[2]')\n if value[0].text in values:\n ... | [
0
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0074214568_lxml_python_xpath.txt |
Q:
How to drop multilevel and rename in pandas dataframe
I have the following dataframe with multiple indeces
balance account_age token_trading_activity
last mean first last mean
address
A 8401.072266 7108.331543... | How to drop multilevel and rename in pandas dataframe | I have the following dataframe with multiple indeces
balance account_age token_trading_activity
last mean first last mean
address
A 8401.072266 7108.331543 4.554461e+03 22 2.654430e+06
B 12.3920... | [
"here is one way to do it\n# iterate over the multi-level columns names\n# using list comprehension, concatenate them\n\ndf.columns=[col[0]+\" \"+col[1] for col in df.columns]\n\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074214933_dataframe_pandas_python.txt |
Q:
How do I make imports work for file that need to be called from different folders?
This is my folder structure
├── folder1
│ ├── component.py
│ └── utils
│ └── utils.py
└── rootComponent.py
component.py makes use of utils. So I import it with
import utils
but if I try to import component.py from rootCo... | How do I make imports work for file that need to be called from different folders? | This is my folder structure
├── folder1
│ ├── component.py
│ └── utils
│ └── utils.py
└── rootComponent.py
component.py makes use of utils. So I import it with
import utils
but if I try to import component.py from rootComponent.py
import folder1.component
I get ModuleNotFoundError: No module named 'utils'
... | [
"an ad-hoc and dirty solution can be done with a try-except block:\n# in component.py\ntry:\n import utils\nexcept:\n import folder1.utils\n\nanother solution is to modify the sys.path. python searches paths listed here for import requests after it searched the current folder and python's standard library. he... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074214958_python_python_3.x.txt |
Q:
Minimum amount of numbers to change inside of n*n matrix to make it symmetrical about multiple lines at once
There is a n*n matrix made of numbers 0 - 9. For example:
6 0 0 8 9 6 1
5 1 6 8 1 1 0
4 2 1 3 7 1 5
8 8 6 6 2 5 2
7 9 4 6 9 6 4
1 4 7 8 5 3 8
9 4 8 3 9 2 9
I need to find the minimum amount of number... | Minimum amount of numbers to change inside of n*n matrix to make it symmetrical about multiple lines at once | There is a n*n matrix made of numbers 0 - 9. For example:
6 0 0 8 9 6 1
5 1 6 8 1 1 0
4 2 1 3 7 1 5
8 8 6 6 2 5 2
7 9 4 6 9 6 4
1 4 7 8 5 3 8
9 4 8 3 9 2 9
I need to find the minimum amount of numbers to change (inside the matrix) to make it symmetrical about multiple lines (/, \, -, |) at once.
I made four func... | [
"You can try this:\nimport numpy as np\nimport scipy\n\na = np.array([[6, 0, 0, 8, 9, 6, 1],\n [5, 1, 6, 8, 1, 1, 0],\n [4, 2, 1, 3, 7, 1, 5],\n [8, 8, 6, 6, 2, 5, 2],\n [7, 9, 4, 6, 9, 6, 4],\n [1, 4, 7, 8, 5, 3, 8],\n [9, 4, 8, 3, 9, 2,... | [
2
] | [] | [] | [
"list",
"matrix",
"python",
"symmetry"
] | stackoverflow_0074214343_list_matrix_python_symmetry.txt |
Q:
Threading NNTP, how? (Newbie here)
I can't wrap my head around how I could possibly rewrite my code to be multi-threaded.
The code I'm writing is made to automatically archive every single article in a list of newsgroups that exist, but I wanna be able to utilize my newsgroup plan and make it up to 20 threads. I'v... | Threading NNTP, how? (Newbie here) | I can't wrap my head around how I could possibly rewrite my code to be multi-threaded.
The code I'm writing is made to automatically archive every single article in a list of newsgroups that exist, but I wanna be able to utilize my newsgroup plan and make it up to 20 threads. I've never coded threading before and my at... | [
"I can't test it with XSUseNet.\nI wouldn't use global variables because when processes work at the same time then they may get the same values from these variables.\nYou should rather send values as parameters to functions.\nSomething like this:\ndef download_nntp_file(g_tuple):\n # ... code which uses `g_tuple... | [
2
] | [] | [] | [
"multithreading",
"nntp",
"python"
] | stackoverflow_0074200828_multithreading_nntp_python.txt |
Q:
How to show full number in plotly log scale
I want to add this:
I.e. the multiplier f (for femto in this case) to every tick, not only the powers of 10, as is the case already for linear scale. Is it possible to change this behavior?
I would prefer an answer that fixes this automatically by changing the behavior ... | How to show full number in plotly log scale | I want to add this:
I.e. the multiplier f (for femto in this case) to every tick, not only the powers of 10, as is the case already for linear scale. Is it possible to change this behavior?
I would prefer an answer that fixes this automatically by changing the behavior of Plotly, don't want to modify every tick manual... | [
"You're trying to modify both the minor and major ticks. Right now nothing's built into Plotly's API to modify the minor tick formatting. However, I found a creative workaround.\nYou didn't share any programming code. I don't know if you're using a notebook or Plotly express, go, or Plotly as a backend. I don't kno... | [
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074203643_plotly_python.txt |
Q:
dynamically add attributes to class in python
I need to dynamically add attributes to a class in python
download_folder = mail_box.Folders('Inbox').Folders[subfolder].Folders[subfolder]....etc
is it somehow possible to add a certain number of subfolders - '.Folders[subfolder]' dynamically with a loop or some sort... | dynamically add attributes to class in python | I need to dynamically add attributes to a class in python
download_folder = mail_box.Folders('Inbox').Folders[subfolder].Folders[subfolder]....etc
is it somehow possible to add a certain number of subfolders - '.Folders[subfolder]' dynamically with a loop or some sort of lambda function?
Thanks!
| [
"I am not sure if I understand your question. I can give a short example if it works for you.\nclass folder:\n def __init__(self):\n self.subfolder=[]\n\nYou can create a new folder object by:\nnewfolder=folder()\n\nThen you can add a new subfolder for newfolder by:\nnewsubfolder=folder()\nnewfolder.subfo... | [
0
] | [] | [] | [
"attributes",
"python"
] | stackoverflow_0074214813_attributes_python.txt |
Q:
How do you sort input in Python?
beginning coder here. I was trying to sort words and numbers, and it mostly work. However, when I provided input to sort, it doesn't seem to work.
I tried inserting the input as a variable and it broke the numbers down into single digits, which I did not want to do. I tried convert... | How do you sort input in Python? | beginning coder here. I was trying to sort words and numbers, and it mostly work. However, when I provided input to sort, it doesn't seem to work.
I tried inserting the input as a variable and it broke the numbers down into single digits, which I did not want to do. I tried converting the input into a float and integer... | [
"If your input is a String, you can convert it to int and add to a list.\nThen you can sort the list:\nlist = []\nx = input(\"write:\")\nx = x.replace(\" \",\"\")\ny = x.split(\",\")\nfor i in y:\n if i.isnumeric():\n i = int(i)\n list.append(i)\nlist.sort()\nprint(list)\n\n"
] | [
-2
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074214976_python_sorting.txt |
Q:
pydrake: How do I identify slow Python LeafSystem's (to possibly rewrite in C++)?
I am prototyping a simple Drake simulation. I have some simple Python LeafSystems that implement controllers, and find that without these systems, my simulation can run at realtime; however, with these systems, my simulation runs muc... | pydrake: How do I identify slow Python LeafSystem's (to possibly rewrite in C++)? | I am prototyping a simple Drake simulation. I have some simple Python LeafSystems that implement controllers, and find that without these systems, my simulation can run at realtime; however, with these systems, my simulation runs much slower than realtime.
I don't think it's the math, but instead just the overhead of P... | [
"I'm not sure if this is best answer, but I found this post:\nhttps://stackoverflow.com/a/61253170/7829525\npy-spy seems like an excellent tool for seeing relative performance information for Python code that involves CPython API extensions.\nFrom my naive usage mentioned here: \nhttps://github.com/benfred/py-spy/i... | [
1,
0
] | [] | [] | [
"drake",
"profiling",
"python"
] | stackoverflow_0074201118_drake_profiling_python.txt |
Q:
How to efficiently run multiple Pytorch Processes / Models at once ? Traceback: The paging file is too small for this operation to complete
Background
I have a very small network which I want to test with different random seeds.
The network barely uses 1% of my GPUs compute power so i could in theory run 50 proces... | How to efficiently run multiple Pytorch Processes / Models at once ? Traceback: The paging file is too small for this operation to complete | Background
I have a very small network which I want to test with different random seeds.
The network barely uses 1% of my GPUs compute power so i could in theory run 50 processes at once to try many different seeds at once.
Problem
Unfortunately i can't even import pytorch in multiple processes. When the nr of processe... | [
"I've looked a bit into this tonight. I don't have a solution (edit: I have a mitigation, see the edit at end), but I have a bit more information.\nIt seems the issue is caused by NVidia fatbins (.nv_fatb) being loaded into memory. Several DLLs, such as cusolver64_xx.dll, torcha_cuda_cu.dll, and a few others, have ... | [
23,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"python",
"python_multiprocessing",
"pytorch"
] | stackoverflow_0064837376_python_python_multiprocessing_pytorch.txt |
Q:
Standard deviation of dataframe?
Since dataframe.std() is deprecated, we should use groupby now: https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.std.html
However, for finding a simple standard deviation of this
dataframe['number'].std(),
the groupby function seems to be an unnecessarily l... | Standard deviation of dataframe? | Since dataframe.std() is deprecated, we should use groupby now: https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.std.html
However, for finding a simple standard deviation of this
dataframe['number'].std(),
the groupby function seems to be an unnecessarily long command to me. "dataframe" has a c... | [
"I think there is a misunderstanding of the docs.\nWhat pandas is deprecating is specifically the level parameter in favor of its groupby counterpart (the link you shared). Nowhere it says pandas.Series.std is deprecated as a whole:\n\nlevel: int or level name, default None\nIf the axis is a MultiIndex (hierarchica... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074215072_dataframe_pandas_python.txt |
Q:
Metadata error when installing "pyqt6-tools"
I'm using Python 3.11. I'm trying to install pyqt6-tools using pip install pyqt6-tools command but the following error is occurred during installation:
C:\Users\Alex>pip install pyqt6-tools Collecting pyqt6-tools Using
cached pyqt6_tools-6.1.0.3.2-py3-none-any.whl (2... | Metadata error when installing "pyqt6-tools" | I'm using Python 3.11. I'm trying to install pyqt6-tools using pip install pyqt6-tools command but the following error is occurred during installation:
C:\Users\Alex>pip install pyqt6-tools Collecting pyqt6-tools Using
cached pyqt6_tools-6.1.0.3.2-py3-none-any.whl (29 kB) Collecting click
Using cached click-8.1.3-py... | [
"It looks like this is might be a sort of bug, but really more that there isn't an installer yet for your version of python and OS.\nYou can either try installing an older version of Python, some version of 3.10 would probably do. Or you can try one of the workarounds detailed in the bug report that people have cla... | [
1
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0074212597_pyqt_python.txt |
Q:
List reverse in particular range
I wanted to recursively reverse elements in the list for range i to j.
def revlist(l, i, j):
if not l: # this will be true if l == []
return l
return l[-1:] + revlist(l[:-1]) # recursive case
For example list [1, 2, 3, 4, 5, 6, 7, 8, 9] for i = 2 and j = 5 will be ... | List reverse in particular range | I wanted to recursively reverse elements in the list for range i to j.
def revlist(l, i, j):
if not l: # this will be true if l == []
return l
return l[-1:] + revlist(l[:-1]) # recursive case
For example list [1, 2, 3, 4, 5, 6, 7, 8, 9] for i = 2 and j = 5 will be [1, 5, 4, 3, 2, 6, 7, 8, 9].
How to do... | [
"If you insist on a recursive implementation (which is inefficient, and rather pointless in this use case, as well as limiting the size of the list that can be reversed):\ndef rev_sublist(xs, i, j):\n def rec_rev(ys):\n if not ys:\n return ys\n else:\n return [ys[-1]] + rec_re... | [
2,
0
] | [] | [] | [
"list",
"python",
"recursion",
"reverse"
] | stackoverflow_0074214972_list_python_recursion_reverse.txt |
Q:
For Loop to Write Multiple Dataframes to Separate Excel Sheets
I've been trying to figure out where my code is going wrong but I can't seem to figure out the error. The goal of this code snippet is pretty simple. I read in my CSV into a data frame and create a list of the unique subfunctions in the Sub Function1 c... | For Loop to Write Multiple Dataframes to Separate Excel Sheets | I've been trying to figure out where my code is going wrong but I can't seem to figure out the error. The goal of this code snippet is pretty simple. I read in my CSV into a data frame and create a list of the unique subfunctions in the Sub Function1 column. My goal is to create an excel workbook with separate workshee... | [
"you need to add writer.save() at the end of your codes so that it will close the Excel writer and output the Excel file\n"
] | [
1
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074215005_excel_pandas_python.txt |
Q:
Jupyter notebook in VS Code - No color for the python code in ipynb-file. What am i doing wrong?
Code of .ipynb file:
Python is detected:
The code has color in jupyter notebook:
I tried setting up a jupyter notebook in vs code in an anaconda environment. I have tried - Python: Select interpreter and selected my... | Jupyter notebook in VS Code - No color for the python code in ipynb-file. What am i doing wrong? | Code of .ipynb file:
Python is detected:
The code has color in jupyter notebook:
I tried setting up a jupyter notebook in vs code in an anaconda environment. I have tried - Python: Select interpreter and selected my anaconda environment. Made sure python is in the environment: python --version: Python 3.8.8. Tried ... | [
"Jupyter extension detects your code as CVE instead of Python so Python syntax highlighting is not applied successfully.\nRefer to Jupyter in vscode can't execute syntax highlighting, the Dependency Analytics extension should be the reason. Remove or Disable it then reload window, the question should go away.\n",
... | [
11,
0,
0
] | [] | [] | [
"color_scheme",
"jupyter_notebook",
"python",
"visual_studio_code"
] | stackoverflow_0069802585_color_scheme_jupyter_notebook_python_visual_studio_code.txt |
Q:
Finding the next available date from a Dataframe for group by
I have a data frame that contains 1 minutes OHLC stock data(length = 22879). It has times that are greater than 16:00 or less than 9:30. I am trying to find the extended hours max high and min low for each individual extended hour session. Since the mar... | Finding the next available date from a Dataframe for group by | I have a data frame that contains 1 minutes OHLC stock data(length = 22879). It has times that are greater than 16:00 or less than 9:30. I am trying to find the extended hours max high and min low for each individual extended hour session. Since the market closes at 4 and opens up at 9:30 I have this to filter the time... | [
"\nMy question. Is there away to search the dataframe for the next\navailable date after it knows the current date\n\nQuestion: what should be the next date for the last date in your DF?\nIn below solution, its NaN at the moment\n# create a df by finding the unique dates\ndf2=pd.DataFrame(np.unique(df['date']), col... | [
0
] | [] | [] | [
"dataframe",
"date",
"group_by",
"pandas",
"python"
] | stackoverflow_0074215027_dataframe_date_group_by_pandas_python.txt |
Q:
My Flask-Admin ModelView's __init__ has no application context—when does it normally get one?
I have a working sample Flask-Admin application on GitHub which queries a view (itself based on MySQL's information_schema.TABLES) in order to dynamically update a ModelView's column_labels and column_descriptions propert... | My Flask-Admin ModelView's __init__ has no application context—when does it normally get one? | I have a working sample Flask-Admin application on GitHub which queries a view (itself based on MySQL's information_schema.TABLES) in order to dynamically update a ModelView's column_labels and column_descriptions properties. There's also a small template modification to add tooltips to the header row containing the co... | [
"I would override the render method of ModelView and set your column_descriptions there. Obviously you could setup some kind of caching mechanism to reduce the number of database queries.\nSomething like (completely untested) - note use of self.session in querying:\n# views.py\nfrom flask_admin.contrib.sqla import ... | [
0,
0
] | [] | [] | [
"flask",
"flask_admin",
"flask_sqlalchemy",
"python",
"sqlalchemy"
] | stackoverflow_0050459142_flask_flask_admin_flask_sqlalchemy_python_sqlalchemy.txt |
Q:
Getting two graphs using matplotlib animation instead of one
I am trying to plot world population map using geopandas and matplotlib. I also use matplotlib animation to make graph animated for each year.
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
f... | Getting two graphs using matplotlib animation instead of one | I am trying to plot world population map using geopandas and matplotlib. I also use matplotlib animation to make graph animated for each year.
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
fig,ax=plt.subplots(1,1,figsize=(15,5))
def animation_bar(year):
... | [
"You can use plt.close() anywhere in between plt.subplots and HTML(animator.to_jshtml()).\nFor example:\nimport matplotlib.pyplot as plt\nimport matplotlib.animation\nfrom IPython.display import HTML\n\nfig, ax = plt.subplots()\nl = ax.plot([0, 2], [0, 3])[0]\nt = [0, 1, 2]\nx = [2, 0, 3]\nanimate = lambda n: l.set... | [
0
] | [] | [] | [
"geopandas",
"matplotlib",
"matplotlib_animation",
"pandas",
"python"
] | stackoverflow_0074196620_geopandas_matplotlib_matplotlib_animation_pandas_python.txt |
Q:
represent list of dicts as a string
I have many lists of dictionaries with keys: origin/destination that I want to represent in a simpler and shorter way.
I was trying with some for loops and creating lists with the letters, but it has not worked for me.
Any idea how I could do this representation of the values?
... | represent list of dicts as a string | I have many lists of dictionaries with keys: origin/destination that I want to represent in a simpler and shorter way.
I was trying with some for loops and creating lists with the letters, but it has not worked for me.
Any idea how I could do this representation of the values?
| [
"I interpreted 3 answers from this:\nIntroduction\nAll work regardless of list length\nI believe the use of this is to have a dictionary without repeat values? (answer 3) but you use the term list a lot so it might be for readability to use? (answer 2). An individual dict for each? (Answer 1)\nIs list 3 meant to be... | [
0,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074214710_list_python_string.txt |
Q:
Why don't Python stream methods raise an Exception on a deleted file?
I've been playing around a bit with file-based Streams in Python and have noticed that several methods (e.g. write, close, writable) do not raise Exceptions when an underlying file for the stream has been deleted (e.g. per a call to os.remove().... | Why don't Python stream methods raise an Exception on a deleted file? | I've been playing around a bit with file-based Streams in Python and have noticed that several methods (e.g. write, close, writable) do not raise Exceptions when an underlying file for the stream has been deleted (e.g. per a call to os.remove().
Having reviewed the standard library docs here - there isn't any content r... | [
"reading/writing to files is not handled by python, it is handled by the operating system, python just puts the data in a buffer, and the operating system is responsible for writing it to the disk. (by calling a kernel mode function)\nwhat the operating system does when it writes to a file that doesn't exist is up ... | [
0
] | [] | [] | [
"file",
"python",
"stream"
] | stackoverflow_0074215306_file_python_stream.txt |
Q:
Unban a user in a specific discord server (python)
I'm working on a discord bot that mutes/unmutes/unbans users based on my servers specific requirements.
I want my discord bot to continue working exactly as it did before it crashed if/when it ever crashes. To do this I have saved all the information I need (user... | Unban a user in a specific discord server (python) | I'm working on a discord bot that mutes/unmutes/unbans users based on my servers specific requirements.
I want my discord bot to continue working exactly as it did before it crashed if/when it ever crashes. To do this I have saved all the information I need (user ID, guild ID) to a file.
What I need help with is, how ... | [
"It doesn't matter where the command is run from, assuming you're using message based commands in discord.py, you'll still have access to context.\nYou'll have to fetch the user in a different way though...\nmember = discord.Object(id=123)\ntry:\n await ctx.guild.unban(member)\nexcept discord.NotFound:\n awai... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_3.x"
] | stackoverflow_0074214609_discord_discord.py_python_python_3.x.txt |
Q:
How to find dataframe inside another dataframe (order is important)?
I have 2 dataframes A and B. I need to check if A has all the values in B (the order is important) and if yes I need the position.
A:
index X Y
0 0 0
1 1 0
2 1 1
3 0 1
4 0 0
5 1... | How to find dataframe inside another dataframe (order is important)? | I have 2 dataframes A and B. I need to check if A has all the values in B (the order is important) and if yes I need the position.
A:
index X Y
0 0 0
1 1 0
2 1 1
3 0 1
4 0 0
5 1 1
6 2 2
7 2 1
8 2 2
B:
index X ... | [
"Ok, I have one really fast version.\nInspired from this answer which deals with the same question but with 1D arrays.\ndef findIndex(A,B):\n a=A.values # ndarray of data in A\n b=B.values # same for B\n af=a.flatten() # same ndarray, but flatten\n bf=b.flatten() # same for B\n # This create a rollin... | [
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074214907_pandas_python.txt |
Q:
Same word but different unicode characters
I built a question answering application in terms of restaurants in Vietnam using Python on Windows. To write Vietnamese characters I need to use Unicode.
First, I clone data from TripAdvisor website which used HTML charset=utf-8 and build my Mongo database. A city named ... | Same word but different unicode characters | I built a question answering application in terms of restaurants in Vietnam using Python on Windows. To write Vietnamese characters I need to use Unicode.
First, I clone data from TripAdvisor website which used HTML charset=utf-8 and build my Mongo database. A city named "đà nẵng" in TripAdvisor has a code:
>>> print... | [
"The problem you encounter is, that unicode allows multiple ways to compose the same symbol. The Python module unicodedata provides a function normalize that allows you to convert unicode representations to a fixed form (e.g. NFC)\nfrom unicodedata import normalize\n\nS1 = b'\\xc4\\x83\\xcc\\x83'.decode('UTF-8')\n... | [
5,
2
] | [] | [] | [
"mongodb",
"python",
"unicode"
] | stackoverflow_0041975601_mongodb_python_unicode.txt |
Q:
Delete column in python-pptx table
Hi I have seen How To Delete A Specific Table Row In PowerPoint Using Python-PPTX on deleting rows in python-pptx table which is more than helpful, however I realised that deleting columns is not as straightforward as this, was wondering if there's a way to do it?
A:
Yes but ag... | Delete column in python-pptx table | Hi I have seen How To Delete A Specific Table Row In PowerPoint Using Python-PPTX on deleting rows in python-pptx table which is more than helpful, however I realised that deleting columns is not as straightforward as this, was wondering if there's a way to do it?
| [
"Yes but again through editing the XML\nimport pptx\nfrom pptx import *\n\ndef remove(table,column):\n col_idx = table._tbl.tblGrid.index(column._gridCol)\n\n for tr in table._tbl.tr_lst:\n tr.remove(tr.tc_lst[col_idx])\n table._tbl.tblGrid.remove(column._gridCol)\n\n\n\n# Establish read path\nin_fi... | [
0
] | [] | [] | [
"python",
"python_pptx"
] | stackoverflow_0074205760_python_python_pptx.txt |
Q:
How to apply function in DataFrame.query in pandas
I want to apply round function while using dataframe.query
import pandas as pd
df = pd.DataFrame([(1.2,2.3,12),(2.7,2.3,13),(1.9,5.3,14), (1.2,4.6,15)], columns=['val1', 'val2','val3'])
Data frame looks as follows:
val1 val2 val3
0 1.2 2.3 12
1 2.7 ... | How to apply function in DataFrame.query in pandas | I want to apply round function while using dataframe.query
import pandas as pd
df = pd.DataFrame([(1.2,2.3,12),(2.7,2.3,13),(1.9,5.3,14), (1.2,4.6,15)], columns=['val1', 'val2','val3'])
Data frame looks as follows:
val1 val2 val3
0 1.2 2.3 12
1 2.7 2.3 13
2 1.9 5.3 14
3 1.2 4.6 15
I wa... | [
"Your query seems fine, but you can try this too:\ndf[df.val1.round() > 2]\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074215441_pandas_python.txt |
Q:
How do I assign a string to a list of which the number that the user inputs?
How do I take 2 numbers from input where the first number indicates how many lists there should be and the second indicates how many strings there will be and then assigning that string to the number of that list? For example if I have an... | How do I assign a string to a list of which the number that the user inputs? | How do I take 2 numbers from input where the first number indicates how many lists there should be and the second indicates how many strings there will be and then assigning that string to the number of that list? For example if I have an input of:
3 3 # first 3 indicates how many lists and the second 3 indicates how m... | [
"This should produce the result you want\nnum_lists, num_strings = [int(x) for x in input().split()]\nmy_lists = [[] for x in range(num_lists)]\n\nfor x in range(num_strings):\n index, string = input().split()\n my_lists[int(index) - 1].append(string)\n\nprint(my_lists)\n\n# 3 3\n# 1 Dog\n# 2 Cat\n# 3 Tiger\n... | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074215229_python_python_3.x.txt |
Q:
Dropdown menu button doesn't update the plotly timeline plot
I am trying to build a dropdown menu for plotly timeline plot. Here is my code:
import pandas as pd
import plotly.express as px
def main():
d = {
'T_ID': ['T1', 'T2', 'T3', 'T1'],
'TYPE': ['Type1', 'Type2', 'Type3', 'Type2'],
'SYS_START_... | Dropdown menu button doesn't update the plotly timeline plot | I am trying to build a dropdown menu for plotly timeline plot. Here is my code:
import pandas as pd
import plotly.express as px
def main():
d = {
'T_ID': ['T1', 'T2', 'T3', 'T1'],
'TYPE': ['Type1', 'Type2', 'Type3', 'Type2'],
'SYS_START_TIME': ['2021-06-20 06:05', '2021-06-23 15:13', '2021-06-27 13:01'... | [
"I think the issue is that the args x_start and x_end that you're passing to your buttons aren't going to be recognized by plotly. If you look at fig.data, you'll see that under the hood, px.timeline creates go.Bar traces for each T_ID using the arguments \"base\" and \"x\" to draw the horizontal bars, so you would... | [
0,
0
] | [] | [] | [
"drop_down_menu",
"plotly",
"python",
"timeline"
] | stackoverflow_0074188951_drop_down_menu_plotly_python_timeline.txt |
Q:
Can't access s3 file from chalice local test server
Im trying to change S3 file's metadata from python, and test with chalice server locally (need the chalice for other things). When running (without chalice server):
# change file metadata in s3:
s3 = boto3.resource('s3')
s3_object = s3.Object(bucket, key)
s3_obje... | Can't access s3 file from chalice local test server | Im trying to change S3 file's metadata from python, and test with chalice server locally (need the chalice for other things). When running (without chalice server):
# change file metadata in s3:
s3 = boto3.resource('s3')
s3_object = s3.Object(bucket, key)
s3_object.metadata.update({'metadata-key': 'something'})
s3_obje... | [
"\nAn error occurred (404) when calling the HeadObject operation: Not Found\n\nIf the object exists, this error usually means the role you are using to make the request doesn't have the required permissions.\nYour local tests with Python work because they are using your default AWS profile. But that key is not pass... | [
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"chalice",
"python"
] | stackoverflow_0074213350_amazon_s3_amazon_web_services_chalice_python.txt |
Q:
Python - call multiple methods in a single call
how can i call multiple methods of an object at the same time in python. in php I can do this:
class Client{
public ac1(){ ... }
public ac2(){ ... }
}
$client = new client();
$client->ac1()->ac2(); <-- I want to do it here
how would you do it in python?
A... | Python - call multiple methods in a single call | how can i call multiple methods of an object at the same time in python. in php I can do this:
class Client{
public ac1(){ ... }
public ac2(){ ... }
}
$client = new client();
$client->ac1()->ac2(); <-- I want to do it here
how would you do it in python?
| [
"The example you gave of PHP code does not run the methods at the same time - it just combines the 2 calls in a single line of code. This pattern is called a fluent interface.\nYou can do the same in Python as long as a method you're calling returns the instance of the object it was called on.\nI.e.:\nclass Client:... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0074215524_python.txt |
Q:
want to scrap image urls from json data
i,m trying to scrap image urls of each product only jpg extension also with the name available in "alt" from json structure like (also mentioned below) "attributes" > "media_map" > ("b" , "c" , "d" , e which available) > "src" and then "medium" , "lg" , "xl" , "xxl"
... | want to scrap image urls from json data | i,m trying to scrap image urls of each product only jpg extension also with the name available in "alt" from json structure like (also mentioned below) "attributes" > "media_map" > ("b" , "c" , "d" , e which available) > "src" and then "medium" , "lg" , "xl" , "xxl"
"a218": {
"label": "Sha... | [
"Instead of\nlink = data['product']['response']['product']['data']['attributes']['media_map']\n\nhave\nmediaMap = data['product']['response']['product']['data']['attributes']['media_map']\n\nThen you can extract you want from mediaMap\nIf you want the alts:\nmediaAlts = [m['alt'] for m in mediaMap.values() if 'alt'... | [
0
] | [] | [] | [
"arrays",
"beautifulsoup",
"python",
"scrape",
"web_scraping"
] | stackoverflow_0074214571_arrays_beautifulsoup_python_scrape_web_scraping.txt |
Q:
How Can I avoid the Trailing whitespace and produce the desired 8 x 8 grid in the code below using Python?, my code is below as well
for i in range(n):
for j in range(n):
z = i * n + j
if z < 10:
print(f" {z}", end = " ")
else:
print(f"{z}" , end = " ")
print... | How Can I avoid the Trailing whitespace and produce the desired 8 x 8 grid in the code below using Python?, my code is below as well | for i in range(n):
for j in range(n):
z = i * n + j
if z < 10:
print(f" {z}", end = " ")
else:
print(f"{z}" , end = " ")
print()
I have tried the end= " " method but I keep getting the whitespace error, I am a beginner thus I am unable to implement other methods ... | [
"This approach creates the full matrix as a string s first and then only prints once in the end:\ns = ''\nfor i in range(n):\n for j in range(n):\n z = i * n + j\n s += ' '\n if z < 10:\n s += ' '\n s += str(z)\n s += '\\n'\nprint(s)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074215528_python.txt |
Q:
Python + Image Processing: Efficiently Assign Pixel Values to Nearest Predefined Value
I implemented an algorithm that uses opencv kmeans to quantize the unique brightness values present in a greyscale image. Quantizing the unique values helped avoid biases towards image backgrounds which are typically all the sam... | Python + Image Processing: Efficiently Assign Pixel Values to Nearest Predefined Value | I implemented an algorithm that uses opencv kmeans to quantize the unique brightness values present in a greyscale image. Quantizing the unique values helped avoid biases towards image backgrounds which are typically all the same value.
However, I struggled to find a way to utilize this data to quantize a given input i... | [
"As your image is grayscale (presumably 8 bits), a lookup-table will be an efficient solution. It suffices to map all 256 gray-levels to the nearest center once for all, then use this as a conversion table. Even a 16 bits range (65536 entries) would be significantly accelerated.\n",
"I recently thought of a much ... | [
1,
0
] | [] | [] | [
"image_processing",
"k_means",
"opencv",
"performance",
"python"
] | stackoverflow_0074184049_image_processing_k_means_opencv_performance_python.txt |
Q:
I am trying to update the score that has been blitted but it doesnt change
class Score:
def __init__(self):
self.Colour = (230, 230, 230)
self.x = 25
self.y = 0
self.Shape = pygame.Rect((self.x, self.y), (200, 100))
self.Team1Score = 0
self.Team2Score = 0
... | I am trying to update the score that has been blitted but it doesnt change | class Score:
def __init__(self):
self.Colour = (230, 230, 230)
self.x = 25
self.y = 0
self.Shape = pygame.Rect((self.x, self.y), (200, 100))
self.Team1Score = 0
self.Team2Score = 0
self.Title = f"{self.Team1Score} - {self.Team2Score}"
self.text_type ... | [
"After changing Team1Score or Team2Score you have to create again\nself.Title = f\"{self.Team1Score} - {self.Team2Score}\"\n\nto get new string\n\nif p1.Colour == (255, 0, 0):\n self.Team1Score += 1\nelse:\n self.Team2Score += 1\n\nself.Title = f\"{self.Team1Score} - {self.Team2Score}\"\n\nself.text_type ... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074215185_pygame_python.txt |
Q:
New line in List
Lets say I have a list called l1:
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
And I want to print it as
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
How would I do that in python on 3.9
I tried to us a \n, but that has not worked for me.
A:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list[:5])
print(list[5:])
ou... | New line in List | Lets say I have a list called l1:
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
And I want to print it as
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
How would I do that in python on 3.9
I tried to us a \n, but that has not worked for me.
| [
"list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(list[:5])\nprint(list[5:])\n\noutputs:\n[1, 2, 3, 4, 5]\n[6, 7, 8, 9, 10]\n\nif you want them to be printed on the same line then you can use:\nprint(list[:5],list[5:])\n\nwhich will return:\n[1, 2, 3, 4, 5] [6, 7, 8, 9, 10]\n\n",
"Slicing would probably work for you... | [
0,
0
] | [] | [] | [
"list",
"newline",
"python"
] | stackoverflow_0074215549_list_newline_python.txt |
Q:
Compare values with previous values and count the change : Pandas Groupby
I have a panadas dataframe shown below :
masterid price
1001 12
1001 12
1001 11
1001 14
1002 15
1003 10
1003 10
1003 10
1004 16
1004 17
I want to count the times when ... | Compare values with previous values and count the change : Pandas Groupby | I have a panadas dataframe shown below :
masterid price
1001 12
1001 12
1001 11
1001 14
1002 15
1003 10
1003 10
1003 10
1004 16
1004 17
I want to count the times when the price changes for a particular master id
Example : For masterid 1001 the pr... | [
"\n#calculate the price difference using diff\n# take absolute value and compare with zero\n# go another group by and take the count\n\ndf.assign(price=\n df.groupby('masterid')['price']\n .diff()\n .abs()>0)\n.groupby(['masterid'])['price']\n.sum()\n.reset_index()\n\n\nmasterid price\... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074215396_pandas_python.txt |
Q:
Why is defaultdict creating an array for my values?
I'm creating a defaultdict from an array of arrays:
>>> array = [['Aaron','1','2'],['Ben','3','4']]
>>> d = defaultdict(list)
>>> for i in array:
... d[i[0]].append({"num1":i[1],"num2":i[2]})
My expected outcome is:
>>> d
defaultdict(<type 'list'>, {'Aaron':... | Why is defaultdict creating an array for my values? | I'm creating a defaultdict from an array of arrays:
>>> array = [['Aaron','1','2'],['Ben','3','4']]
>>> d = defaultdict(list)
>>> for i in array:
... d[i[0]].append({"num1":i[1],"num2":i[2]})
My expected outcome is:
>>> d
defaultdict(<type 'list'>, {'Aaron': {'num1': '1', 'num2': '2'},
'Ben': {'num1': '3', 'num2'... | [
"When you call this:\nd = defaultdict(list)\n\nIt means that if you attempt to access d['someKey'] and it does not exist, d['someKey'] is initialized by calling list() with no arguments. So you end up with an empty list, which you then append your dictionary to. You probably want this instead:\nd = defaultdict(di... | [
16,
8
] | [
"Do\nfrom collections import defaultdict\nd = defaultdict(list)\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0009928360_python.txt |
Q:
Update Python dictionary while looping
I was trying to iterate over a list of values, craft a dictionary to save each value in a structured way, and then append the dictionary to a new list of results, but I found an unexpected behavior.
Below is an example:
values_list = [1,2,3]
# Basic dict
result_dict = {
... | Update Python dictionary while looping | I was trying to iterate over a list of values, craft a dictionary to save each value in a structured way, and then append the dictionary to a new list of results, but I found an unexpected behavior.
Below is an example:
values_list = [1,2,3]
# Basic dict
result_dict = {
'my_value': ''
}
# Iterate, craft a dicti... | [
"As explained in the comment, you're appending the same dictionary in each iteration because update() modifies the result_dict rather than returning a copy. So, the only change you need to do is to append a copy of the crafted dictionary. For example:\nvalues_list = [1,2,3]\n\n# Basic dict\nresult_dict = {\n 'my... | [
1,
0
] | [] | [] | [
"dictionary",
"loops",
"python"
] | stackoverflow_0074199082_dictionary_loops_python.txt |
Q:
I want to make sure the user 's input is in the same order as the list. If it is not, it should print Try again
solution = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
enter number >1
enter number >1
enter number >2
enter number >3
enter number >5
enter number >8
enter number >3
Try again
What I tried
guess = int(input("E... | I want to make sure the user 's input is in the same order as the list. If it is not, it should print Try again | solution = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
enter number >1
enter number >1
enter number >2
enter number >3
enter number >5
enter number >8
enter number >3
Try again
What I tried
guess = int(input("Enter the next Fibonacci number >"))
solution = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
while guess not in solution or gu... | [
"You can the following a try, where it makes you keep trying until you say the last number in the solution:\nsolution = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n\ni = 0\nwhile i < len(solution):\n guess = int(input(\"Enter the next Fibonacci number >\"))\n # Use if condition to compare\n if guess != solution[i]... | [
2,
0,
0
] | [] | [] | [
"if_statement",
"list",
"python"
] | stackoverflow_0074215595_if_statement_list_python.txt |
Q:
So Im getting some of the code to work, just my call to the function for getting the average of the test scores isnt working i dont know what to pass
def determine_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif ... | So Im getting some of the code to work, just my call to the function for getting the average of the test scores isnt working i dont know what to pass | def determine_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
def calc_average(test1, test2, test3, test4, test5):
avg = sum((test1, test2, test3, te... | [
"You should call the method, just like the other function that you are calling.\nline 26 of your code:\n# ...\nprint('Average of the Test Scores')\navg_score = calc_average(test1, test2, test3, test4, test5)\nprint(avg_score)\n# ...\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074215659_python.txt |
Q:
github actions ffmpeg gem cannot find ffprobe
so, we have been using a gem called streamio-ffmpeg, and it has been working well. We have been using github actions to to integration and E2E testing for our front end. We also had to add python for another dependency we are using. now, when we run the E2E suite on gi... | github actions ffmpeg gem cannot find ffprobe | so, we have been using a gem called streamio-ffmpeg, and it has been working well. We have been using github actions to to integration and E2E testing for our front end. We also had to add python for another dependency we are using. now, when we run the E2E suite on github actions, streamio-ffmpeg cannot find the ffpro... | [
"Here is how I use FedericoCarboni/setup-ffmpeg:\n steps:\n ...\n - name: Set up FFmpeg\n uses: FedericoCarboni/setup-ffmpeg@v2\n with:\n token: ${{ secrets.GITHUB_TOKEN }}\n\nThen, my package ffmpegio picks up both ffmpeg & ffprobe w/out any problem from the system path. Maybe yo... | [
0
] | [] | [] | [
"ffmpeg",
"github_actions",
"python",
"shell"
] | stackoverflow_0074215521_ffmpeg_github_actions_python_shell.txt |
Q:
How to speed up importing multiple csv files, do some cleaning of the data and then blend them together in Python?
I have multiple csv files on which I have to remove 2 rows because they are only NaNs. I want to load the first one, perform the cleaning and then load the second one do the cleaning and concatenate w... | How to speed up importing multiple csv files, do some cleaning of the data and then blend them together in Python? | I have multiple csv files on which I have to remove 2 rows because they are only NaNs. I want to load the first one, perform the cleaning and then load the second one do the cleaning and concatenate with the first one and so on.
This is the code:
df_result = None
for file in tqdm(files):
df = pd.read_csv(file)
... | [
"Another way could be by appending the df's to the list and then concatenating after the for loop like this because you are currently doing the concatenation on each iteration(I guess that may slow up your script).\ndf_result = []\nfor file in tqdm(files):\n df = pd.read_csv(file, index_col=None, header=0)\n ... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074215506_pandas_python.txt |
Q:
How can I download a .txt file from a string and save it to the user's desktop in Python?
I have a HTML text field in Python. (I read the HTML code in Python, the HTML code is a text field) When the user enters a string in the text field and clicks the submit button, I want the application to automatically downloa... | How can I download a .txt file from a string and save it to the user's desktop in Python? | I have a HTML text field in Python. (I read the HTML code in Python, the HTML code is a text field) When the user enters a string in the text field and clicks the submit button, I want the application to automatically download a .txt file from the string and save it to the user's desktop in Python.
My code:
<form actio... | [
"For this particular application, it would be more suitable to do the download in the browser using javascript only. Because you are not trying to modify the text using data stored on your server, your server backend application (Python), does not need to know that the user is downloading the file. This is good bec... | [
1
] | [] | [] | [
"download",
"python",
"string"
] | stackoverflow_0074202199_download_python_string.txt |
Q:
Finding a combination of characters and digits in a string python
I have a list of lists, and I'm attempting to loop through and check to see if the strings in a specific index in each of the inner lists contain a combination of "XY" and then 4 numbers immediately following. The "XY" could be in various locations ... | Finding a combination of characters and digits in a string python | I have a list of lists, and I'm attempting to loop through and check to see if the strings in a specific index in each of the inner lists contain a combination of "XY" and then 4 numbers immediately following. The "XY" could be in various locations of the string, so I'm struggling with the syntax beyond just using "XY"... | [
"You can use Python's regex module re with this pattern that matches XY and then four digits anywhere in the string.\nimport re\npattern = r'XY\\d{4}'\n\nmy_list = [['XY0'],['XY1234','AB1234'],['XY1234','ABC123XY5678DEF6789']]\n\nelem_to_check = 1\nfor row in my_list:\n if len(row) > elem_to_check: \n for... | [
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074215493_python_string.txt |
Q:
No module recognised after creating new virtualenv
So, i have python 3.11 installed, i wanted to run a code with flask module, and it was running using original python, but not in vscode, so i followed a suggestion from stack exchange and used command python -m venv env.
This created a new folder called env, and a... | No module recognised after creating new virtualenv | So, i have python 3.11 installed, i wanted to run a code with flask module, and it was running using original python, but not in vscode, so i followed a suggestion from stack exchange and used command python -m venv env.
This created a new folder called env, and after that i got a prompt that new virtual environment ha... | [
"Once a venv is created, you must activate it like so: C:\\User\\venv_folder\\Scripts\\ activate\nIf this doesn't work try using C:\\User\\venv_folder\\Scripts\\ activate.ps1 or activate.bat\nYou'll know if it works once you have the (venv_name) before your command line in the terminal\n",
"\npython -m venv env\n... | [
1,
0
] | [] | [] | [
"modulenotfounderror",
"python",
"virtualenv",
"visual_studio_code"
] | stackoverflow_0074089006_modulenotfounderror_python_virtualenv_visual_studio_code.txt |
Q:
Why is my if statement not executing when I start my code?
I'm a beginner programmer just starting out and learning and I'm wondering why my code finishes after the first line. If anyone can let me know what is wrong with it, would be greatly appreciated.
I wanted it to print my if statements properly but I'm not ... | Why is my if statement not executing when I start my code? | I'm a beginner programmer just starting out and learning and I'm wondering why my code finishes after the first line. If anyone can let me know what is wrong with it, would be greatly appreciated.
I wanted it to print my if statements properly but I'm not sure what's going on.
x = 10
try:
(input("Type in a number:... | [
"You will never get a ValueError in this program from this line input(\"Type in a number:\")\nCorrected code:\nx = 10\n\ntry:\n x = input(\"Type in a number:\")\n print('Correct!')\n\nexcept ValueError:\n if x > 10:\n print('X is bigger than the number given')\n if x < 10:\n print('X is sm... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074215318_python.txt |
Q:
Get a DataFrame with calculated value from 2 lists
I have the following 2 lists:
A=list(range(2018, 2023))
B=list(range(1,13))
Corresponding to A -> (2018,2019,2020,2021,2022) and
B -> (1,2,3,4,5,6,7,8,9,10,11,12).
I need to get the following DataFrame:
ColumnA
201801
201802
201803
201804... | Get a DataFrame with calculated value from 2 lists | I have the following 2 lists:
A=list(range(2018, 2023))
B=list(range(1,13))
Corresponding to A -> (2018,2019,2020,2021,2022) and
B -> (1,2,3,4,5,6,7,8,9,10,11,12).
I need to get the following DataFrame:
ColumnA
201801
201802
201803
201804
201805
201806
201807
201808
201809
... | [
"cross join ?:\ndf1 = pd.DataFrame(A, columns=['Year'])\ndf2= pd.DataFrame(B, columns=['Month'])\n\nres = df1.merge(df2, how='cross')\n\n# and if you want to concat them :\nres['Column1'] = res['Year'].astype(str)+ res['Month'].astype(str).str.zfill(2)\n\noutput:\n> \n Year Month Column1\n0 2018 1 20180... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074215764_pandas_python.txt |
Q:
How to apply formatting rules from PyCharm in VSCode?
As I understand, PyCharm uses his own set of formatting rules.
https://www.jetbrains.com/help/pycharm/configuring-code-style.html#editorconfig
Is there any faster way to apply same rules to the VSCode and PyCharm?
Solution could be either import formatting rule... | How to apply formatting rules from PyCharm in VSCode? | As I understand, PyCharm uses his own set of formatting rules.
https://www.jetbrains.com/help/pycharm/configuring-code-style.html#editorconfig
Is there any faster way to apply same rules to the VSCode and PyCharm?
Solution could be either import formatting rules from PyCharm to VSCode OR apply same formatting rules in ... | [
"The settings in vscode are stored in the settings.json file. You can also select from the gears in the lower left corner:\n\nWith the example you mentioned, I can query format in the search box and then customize the formatting tool:\n\nYou can also add the following codes into the settings.json file:\n\"python.fo... | [
1
] | [] | [] | [
"formatting",
"pycharm",
"python",
"visual_studio_code"
] | stackoverflow_0074206131_formatting_pycharm_python_visual_studio_code.txt |
Q:
How to eliminate "blank" rows that show up after importing an Excel file using pd.read_excel()
I read in an Excel file from an external source:
import pandas as pd
df = pd.read_excel('https://www.sharkattackfile.net/spreadsheets/GSAF5.xls')
When I call df.tail(), I see that there are 25,841 rows in this dataframe... | How to eliminate "blank" rows that show up after importing an Excel file using pd.read_excel() | I read in an Excel file from an external source:
import pandas as pd
df = pd.read_excel('https://www.sharkattackfile.net/spreadsheets/GSAF5.xls')
When I call df.tail(), I see that there are 25,841 rows in this dataframe.
Also, notably, I see that there is a value of 'xx' in the Case Number column. This is not valid ... | [
"You could use pandas DataFrame's replace function, then do dropna to drop every np.nan values.\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html\nDataFrame.replace('', np.nan)\nDataFrame.replace('xx', np.nan)\nData... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074215837_pandas_python.txt |
Q:
Is there a built in way, using pandas, to find the amount of values below a threshold for bins?
Sorry if the title is confusing I am new to pandas and tried to be as concise as possible. Basically I have a dataframe I'm reading in and for each of the attributes in the data frame I need to quantize them to nearest ... | Is there a built in way, using pandas, to find the amount of values below a threshold for bins? | Sorry if the title is confusing I am new to pandas and tried to be as concise as possible. Basically I have a dataframe I'm reading in and for each of the attributes in the data frame I need to quantize them to nearest 2 value by rounding. My approach is to turn them into bins with the values (-1.01, 1.00], (1.00, 3.00... | [
"I might be wrong but I think you're looking for cumulative sum at each bin:\nimport pandas as pd\n# sample you provided\ndf = pd.DataFrame({'age': [1.9, 2.0, 2.4, 5.9, 6.0, 6.4]})\n# some bins to show how it works\npd.cut(df['age'], bins=[0, 2, 4, 6, 8], right=False).value_counts(sort=False).cumsum()\n\nOutput:\n[... | [
0
] | [] | [] | [
"bins",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074215440_bins_dataframe_pandas_python.txt |
Q:
JSON agrouped by one field
I'm trying to transform an dataframe to json but one column must agrouped some others, like that:
| name | order | age | color | rank |
| robert | car | 25 | red | 5 |
| helena | car | 45 | yellow | 4 |
| cleito | car | 35 | green | 4.5 |
but the json woul... | JSON agrouped by one field | I'm trying to transform an dataframe to json but one column must agrouped some others, like that:
| name | order | age | color | rank |
| robert | car | 25 | red | 5 |
| helena | car | 45 | yellow | 4 |
| cleito | car | 35 | green | 4.5 |
but the json would be like that to insert into Mo... | [
"You can use to_dict to combine multiple columns.\ndf['details'] = df[['color', 'rank']].to_dict(orient='records')\ndf = df.drop(['color', 'rank'], axis=1)\n\n# df.to_json(orient='records') or df.to_dict(orient='records')\n\n(I didn't put details in an array though. I was not sure if you want an array of 1 object.)... | [
2
] | [] | [] | [
"group_by",
"json",
"pandas",
"pymongo",
"python"
] | stackoverflow_0074215723_group_by_json_pandas_pymongo_python.txt |
Q:
Have GitPython stage itself
I am new to GitPython and I am trying to have a python program stage itself to a new git repository (my-new-repo).
My main.py is as follows:
import git
repo = git.Repo.init('my-new-repo')
# List all branches
for branch in repo.branches:
print(branch)
# Provide a list of the files... | Have GitPython stage itself | I am new to GitPython and I am trying to have a python program stage itself to a new git repository (my-new-repo).
My main.py is as follows:
import git
repo = git.Repo.init('my-new-repo')
# List all branches
for branch in repo.branches:
print(branch)
# Provide a list of the files to stage
repo.index.add(['main.... | [
"GitPython's repo.index.add function stages files from the directory of the repo. git.Repo.init('my-new-repo') creates a new repo in the (possibly new) directory my-new-repo. If main.py is not in the repo directory, then GitPython won't be able to see it.\nTo fix this, you can copy main.py into the repo's directory... | [
1
] | [] | [] | [
"git",
"gitpython",
"python"
] | stackoverflow_0074215818_git_gitpython_python.txt |
Q:
Error: Unauthorized: Your client does not have permission to the requested URL while sending gRPC request to service hosted on Cloud Run
I would like to deploy my grpc service to Cloud Run and send authenticated requests to it via Python3. I have followed various Documents regarding setting establishing authentica... | Error: Unauthorized: Your client does not have permission to the requested URL while sending gRPC request to service hosted on Cloud Run | I would like to deploy my grpc service to Cloud Run and send authenticated requests to it via Python3. I have followed various Documents regarding setting establishing authentication to Google Cloud Run Services and have been recieving grpc._channel._InactiveRpcError errors:
my client code is as follows:
#server_info='... | [
"It's confusing and it's poorly-documented.\nThe issue is that you need an ID token including an audience (claim) of the Cloud Run service's address. The credentials that you're getting from google.auth.credentials.Credentials provide an access token.\nSee this grpc_client.py and the associated README and note that... | [
0
] | [] | [] | [
"authentication",
"google_cloud_run",
"grpc",
"grpc_python",
"python"
] | stackoverflow_0074214143_authentication_google_cloud_run_grpc_grpc_python_python.txt |
Q:
Reading individual rows from a file and using values in another script
I have a file (x.txt) with a single column containing a hundred values.
228.71
245.58
253.71
482.72
616.73
756.74
834.72
858.62
934.61
944.60
....
I want to input each of these values to an existing script I have such that my command o... | Reading individual rows from a file and using values in another script | I have a file (x.txt) with a single column containing a hundred values.
228.71
245.58
253.71
482.72
616.73
756.74
834.72
858.62
934.61
944.60
....
I want to input each of these values to an existing script I have such that my command on the terminal is:
script_name 228.71 245.58 253.71........... and so on.
I... | [
"You could read the text file line by line into a list, stripping any newlines on the way. The subprocess.call call takes a list of the command to run plus any arguments. So create a new list with the values just read and the name of the command.\nimport sys\nimport subprocess\n\nvalues = [line.strip() for line in ... | [
0,
0,
0,
0
] | [] | [] | [
"bash",
"python",
"shell"
] | stackoverflow_0074214846_bash_python_shell.txt |
Q:
How can I prevent Django view from being called repeatedly despite of long execution time?
I have a Django view which runs a sub process and returns a JsonResponse back to the user:
def process_images(request, id):
log.debug("Processing images view...")
start = perf_counter()
result = subprocess.run(["... | How can I prevent Django view from being called repeatedly despite of long execution time? | I have a Django view which runs a sub process and returns a JsonResponse back to the user:
def process_images(request, id):
log.debug("Processing images view...")
start = perf_counter()
result = subprocess.run(["ssh", "<REMOTE SERVER>", "bash", "process_images.sh"],
capture_output = True,
te... | [
"While I don't understand the source for this error, I was able to avoid it by using subprocess.Popen rather than subprocess.run, so that it could run it in the background and immediately return the view (avoiding the long execution time):\ndef process_images(request, id):\n result = subprocess.Popen([\"ssh\", \... | [
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0074201326_django_django_views_python.txt |
Q:
How to close a pop up html element in Chrome using Selenium with Python
I am trying to build a web scraper to search through the online Disney store and send me an alert any time a new product is listed or a price is changed. Things had been going well, but recently Disney added a new pop-up window to their online... | How to close a pop up html element in Chrome using Selenium with Python | I am trying to build a web scraper to search through the online Disney store and send me an alert any time a new product is listed or a price is changed. Things had been going well, but recently Disney added a new pop-up window to their online store that is interfering with my script.
This new pop-up window must be cl... | [
"I resolved this issue by specifying that selenium needs to launch the browser in desktop format, rather than using a mobile format. The popup window does not appear in the desktop version of the site, removing the source of the problem.\noptions = Options()\noptions.add_argument(\"user-agent=91.0.4472.114\")\nPATH... | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074133320_python_selenium_web_scraping.txt |
Q:
Access to layer weights from a tf.keras model
I am trying to replicate a tensorflow subclassed model, but I'm having problems accessing to the weights of a layer included in the model. Here's a summarized definition of the model:
class model():
def __init__(self, dims, size):
self._dims = dims
se... | Access to layer weights from a tf.keras model | I am trying to replicate a tensorflow subclassed model, but I'm having problems accessing to the weights of a layer included in the model. Here's a summarized definition of the model:
class model():
def __init__(self, dims, size):
self._dims = dims
self.size = size
self.autoencoder= None
... | [
"A (not very elegant) way to solve it is calling the custom layer in the __init__ method. By doing this, the layer is created as a model attribute making its weights accesible.\n def __init__(self, dims, size):\n self.dims = dims\n self.size = size\n\n self.autoencoder = None\n self.encoder = None\n ... | [
0
] | [] | [] | [
"python",
"subclassing",
"tensorflow2.0",
"tf.keras"
] | stackoverflow_0074167977_python_subclassing_tensorflow2.0_tf.keras.txt |
Q:
Plotly choropleth can't read State iso codes
I want to visualize the number of crimes by state using plotly express.
This is the code :
import plotly.express as px
fig = px.choropleth(grouped, locations="Code",
color="Incident",
hover_name="Code",
anima... | Plotly choropleth can't read State iso codes | I want to visualize the number of crimes by state using plotly express.
This is the code :
import plotly.express as px
fig = px.choropleth(grouped, locations="Code",
color="Incident",
hover_name="Code",
animation_frame='Year',
scope='usa'... | [
"The reason for the lack of color coding is that the United States is not specified in the location mode. please find attached a graph with locationmode='USA-states' added. You can find an example in the references. The data was created for your data.\ndf.head()\nYear Code State incident\n0 1980 AL Al... | [
0
] | [] | [] | [
"choropleth",
"plotly",
"python"
] | stackoverflow_0074212931_choropleth_plotly_python.txt |
Q:
How to set a pandas PeriodIndex with yearly frequency?
I am able to create quarterly and monthly PeriodIndex like so:
idx = pd.PeriodIndex(year=[2000, 2001], quarter=[1,2], freq="Q") # quarterly
idx = pd.PeriodIndex(year=[2000, 2001], month=[1,2], freq="M") # monthly
I would expect to be able to create a yearly ... | How to set a pandas PeriodIndex with yearly frequency? | I am able to create quarterly and monthly PeriodIndex like so:
idx = pd.PeriodIndex(year=[2000, 2001], quarter=[1,2], freq="Q") # quarterly
idx = pd.PeriodIndex(year=[2000, 2001], month=[1,2], freq="M") # monthly
I would expect to be able to create a yearly PeriodIndex like so:
idx = pd.PeriodIndex(year=[2000, 2001],... | [
"month and year are both required \"fields\" due to the current implementation (through pandas 1.5.1 at least). Most other field values will be configured with a default value, however, neither month or year will be defined if a value is not provided. Therefore, in this case, month will remain None which causes the... | [
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"period",
"python"
] | stackoverflow_0074215857_dataframe_pandas_period_python.txt |
Q:
How to formulate and solve optimization problem with pulp in python
Inputs:
2 lists of variables, list_1 and list_2.
function that takes an element from each of lists and return some value >=0:
foo(el_list1, el_list2)
we could assume that we have a matrix of the shape (len(list_1), len(list_2)) that has values >=... | How to formulate and solve optimization problem with pulp in python | Inputs:
2 lists of variables, list_1 and list_2.
function that takes an element from each of lists and return some value >=0:
foo(el_list1, el_list2)
we could assume that we have a matrix of the shape (len(list_1), len(list_2)) that has values >=0.
Task:
Find pairs of elements of list_1, list_2 that give maximum sum ... | [
"from pulp import *\n\nmodel = pulp.LpProblem(\"_problem\", LpMaximize)\n\nA = [[0.0, 1.5, 2.4, 0.8],\n [3.1, 0.5, 0.0, 0.0],\n [0.0, 1.3, 2.5, 1.0]\n]\n \n# Creates a list of all the supply nodes\nlist1 = [\"I0\", \"I1\", \"I2\"]\n\n# Creates a list of all demand nodes\nlist2 = [\"J0\",\"J1\", \"J2\", \"J3\... | [
0
] | [] | [] | [
"pulp",
"python"
] | stackoverflow_0073569886_pulp_python.txt |
Q:
Python version 3.10.6 cannot run jupyter notebook on Visual studio code
I was using my conda environment, which has 3.10.6 python version, but when i try to run the jupyter notebook cell on Visual studio code, its produce this error
Failed to start the Kernel.
NameError: name 'f' is not defined.
View Jupyter log... | Python version 3.10.6 cannot run jupyter notebook on Visual studio code | I was using my conda environment, which has 3.10.6 python version, but when i try to run the jupyter notebook cell on Visual studio code, its produce this error
Failed to start the Kernel.
NameError: name 'f' is not defined.
View Jupyter log for further details.
This problem only happen with 3.10.6 version,however o... | [
"Check the kernel specifications by using the following command in your cmd:\njupyter kernelspec list\n\nIt will show you the available kernels.\nFor me, I can get :\nC:\\Users\\Admin>jupyter kernelspec list\nAvailable kernels:\n python3 c:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\share\\jupy... | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"visual_studio_code"
] | stackoverflow_0074213289_jupyter_notebook_python_visual_studio_code.txt |
Q:
Tell whether people arrived close or not
Write a function that takes two arguments to determine length of interval used to determine if arrivals are close or not. Should return true is close and false if not
Idk I can’t figure it out.
| Tell whether people arrived close or not | Write a function that takes two arguments to determine length of interval used to determine if arrivals are close or not. Should return true is close and false if not
Idk I can’t figure it out.
| [] | [] | [
"I don’t have enough reputation to comment, so this has to be an answer, I’m sorry, you’re going to have to explain your issue in more detail in order to get help.\n",
"Provide more specific details:\n\nAre the arguments integers?\nWhat does \"close\" mean?\nWhat do you mean by \"length of interval\"?\n\n"
] | [
-1,
-1
] | [
"computer_science",
"function",
"intervals",
"python",
"statistics"
] | stackoverflow_0074216060_computer_science_function_intervals_python_statistics.txt |
Q:
Pandas- How to deal with sub columns & merge them with rows?
Let's take a small subset of my dataframe
What I want
I keep messing this up & I have to make a time series of a much bigger dataset. Thanks!
A:
You can play around with stack and unstack to manipulate the shape of your dataframe.
Given this:
columns... | Pandas- How to deal with sub columns & merge them with rows? | Let's take a small subset of my dataframe
What I want
I keep messing this up & I have to make a time series of a much bigger dataset. Thanks!
| [
"You can play around with stack and unstack to manipulate the shape of your dataframe.\nGiven this:\ncolumns = pd.MultiIndex.from_product(\n [[\"12/20/2021\"], [\"National Rate\", \"National Rate Cap\"]]\n)\n\ndf = pd.DataFrame(\n [[0.06, 0.82], [0.03, 0.82]],\n index=[\"Savings\", \"Interest Checking\"],\... | [
0
] | [] | [] | [
"pandas",
"python",
"time_series"
] | stackoverflow_0074212558_pandas_python_time_series.txt |
Q:
Firebase-Admin with AWS Lambda Python
I am currently writing a Python server to deploy on AWS Lambda. I want to use the firebase-admin package to send notifications with FCM and read data from cloud firestore. however when I try deploying my function to AWS Lambda with the .zip file archives, I get this error on e... | Firebase-Admin with AWS Lambda Python | I am currently writing a Python server to deploy on AWS Lambda. I want to use the firebase-admin package to send notifications with FCM and read data from cloud firestore. however when I try deploying my function to AWS Lambda with the .zip file archives, I get this error on execution:
[ERROR] Runtime.ImportModuleError... | [
"The problem is that the firebase-admin package uses some libraries that are compiled differently on different OSes, so you need to create a docker image and install everything there, zip it up and upload it as a layer. Here is an example docker file:\nFROM amazonlinux:2.0.20210126.0\n\nRUN yum -y groupinstall \"De... | [
4,
2,
0,
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"firebase",
"firebase_admin",
"python"
] | stackoverflow_0066291208_amazon_web_services_aws_lambda_firebase_firebase_admin_python.txt |
Q:
__eq__() called multiple times instead of once in nested data structure
Once or twice a year, I run into the following issue: I have some type on which comparison operations might be expensive (e.g. the values are to big to keep in memory and need to be loaded form disk or equality is hard to compute because a sin... | __eq__() called multiple times instead of once in nested data structure | Once or twice a year, I run into the following issue: I have some type on which comparison operations might be expensive (e.g. the values are to big to keep in memory and need to be loaded form disk or equality is hard to compute because a single value may have many representations, think chemical formulas). This type ... | [
"From the way your question is posed I'm assuming:\n\nyou would prefer not to overwrite list.__eq__ if possible. (I also would not want to, this is a pretty dangerous idea).\nYou are okay with overwriting the dunder (__) methods of X if needed. (As far as I can tell it is needed).\n\nAs you kind of hinted at, becau... | [
0
] | [] | [] | [
"comparison",
"data_structures",
"python"
] | stackoverflow_0067010095_comparison_data_structures_python.txt |
Q:
Python code that finds total pay monthly. Phrased very weirdly
Write a function that calculates a total amount of money a worker has made when given the initial salary (per month) and months worked. Every year the worker is at the job, their salary increases by $100 per month.
Please try to keep the level of code ... | Python code that finds total pay monthly. Phrased very weirdly | Write a function that calculates a total amount of money a worker has made when given the initial salary (per month) and months worked. Every year the worker is at the job, their salary increases by $100 per month.
Please try to keep the level of code relatively low. And I know that the phrasing is pretty weird but I b... | [
"You can simplify this using the formula for the sum of triangle numbers.\ndef calculate_pay(initial_salary, months_worked):\n base_line, tips = initial_salary * months_worked, 0\n if (after_first := months_worked - 12) > 0:\n tips = 100 * (after_first * (after_first+1) * (after_first+2) // 6)\n ret... | [
0
] | [] | [] | [
"math",
"python",
"python_3.x"
] | stackoverflow_0074216073_math_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.