content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to use pip for pyenv?
I have installed pyenv in my Mac to manage different python versions.
Before, I have the system default python 2.7 which is located in /Library/Frameworks/Python.framework/Versions/2.7/
and I also have python3 which is located in /usr/local/bin/python3
Now, I installed the pyenv and pytho... | How to use pip for pyenv? | I have installed pyenv in my Mac to manage different python versions.
Before, I have the system default python 2.7 which is located in /Library/Frameworks/Python.framework/Versions/2.7/
and I also have python3 which is located in /usr/local/bin/python3
Now, I installed the pyenv and python 2.7.14 which is located in /U... | [
"When using pyenv, you should be able to set your 'local' version in the directory you are working in, and then pip will rely on this version.\nSo in your case:\npyenv local 2.7.14\npip install package-name\n\nSee more on pyenv commands here: https://github.com/pyenv/pyenv/blob/master/COMMANDS.md\nBut I do think th... | [
15,
6,
1
] | [] | [] | [
"pip",
"pyenv",
"python"
] | stackoverflow_0052060867_pip_pyenv_python.txt |
Q:
Vectorizing "balance sheet"-like data
The problem is the following: how to vectorize situations where a value on the next line of a dataframe depends on a previous one? I want to avoid the for loop.
The row logic I need for the desired column is, given an "open balance" different from 0 or NaN in row[0]:
(1) row_t... | Vectorizing "balance sheet"-like data | The problem is the following: how to vectorize situations where a value on the next line of a dataframe depends on a previous one? I want to avoid the for loop.
The row logic I need for the desired column is, given an "open balance" different from 0 or NaN in row[0]:
(1) row_t.open_balance = row_t-1.close_balance
(2) r... | [
"First, had to create reproducible example so I can try to answer this question. Remember to do this next time you ask a question.\nHere I simulate additions and subtractions.\nimport pandas as pd\nimport numpy as np\n\nadditions = np.random.randint(0, 100, 10)\nsubtractions = np.random.randint(0, 50, 10)\nnet_chan... | [
0
] | [] | [] | [
"pandas",
"python",
"refactoring",
"vectorization"
] | stackoverflow_0074415100_pandas_python_refactoring_vectorization.txt |
Q:
Why do I get error message in python that len is missing when I use the built in len function?
I am currently working on a python project - windows application / software that has GUI where you can put patient information and so on and all that is going to a local mysql database / table. all that works but my IDE ... | Why do I get error message in python that len is missing when I use the built in len function? | I am currently working on a python project - windows application / software that has GUI where you can put patient information and so on and all that is going to a local mysql database / table. all that works but my IDE VS code gives 4 error messages and one of the errors is related to "len()" function. I will provide ... | [
"The \"errors\" you are seeing are type checking issues, not real Python errors that are occurring when you run your code. They're warnings that there might be real errors in the code, but you should be able to run it regardless and the code may work fine. Whether there's a real issue may depend on the data the cod... | [
0
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0074415368_debugging_python.txt |
Q:
python - how to identify and remove rows unique values from a subset of duplicate rows?
I have a dataframe with rows that are almost duplicates, except for the value on one column.
event = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3]
subj = [1, 1, 2, 2, 3, 3, 4, 4, 5, 6]
age = [22, 22, 56, 56, 32, 32, 48, 48, 19, 43]
sex = ['F'... | python - how to identify and remove rows unique values from a subset of duplicate rows? | I have a dataframe with rows that are almost duplicates, except for the value on one column.
event = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3]
subj = [1, 1, 2, 2, 3, 3, 4, 4, 5, 6]
age = [22, 22, 56, 56, 32, 32, 48, 48, 19, 43]
sex = ['F', 'F','M',' M', 'M', 'M',' F',' F', 'F', 'M']
fruit = ['apple', 'orange', 'apple', 'orange', ... | [
"this should work:\ndf['check'] = (\n df.groupby([\"event\"])\n .apply(lambda x: x['fruit'].shift(1)==x['fruit'].shift(-1))\n .reset_index(drop=True)\n)\ndf=df[df['check']==False].drop(['check'],axis=1)\n\nprint(df)\n'''\n event subj age sex fruit\n0 1 1 22 F apple\n3 1 2 56... | [
0
] | [] | [] | [
"dataframe",
"duplicates",
"pandas",
"python"
] | stackoverflow_0074415309_dataframe_duplicates_pandas_python.txt |
Q:
Why is nested function not changing the variable of main function
def findAllPaths(vertices, Alist, source, dest):
result = []
path = []
visited = []
def find_path(Alist, source, dest, path, visited):
path.append(source)
visited.append(source)
if source == dest:
... | Why is nested function not changing the variable of main function | def findAllPaths(vertices, Alist, source, dest):
result = []
path = []
visited = []
def find_path(Alist, source, dest, path, visited):
path.append(source)
visited.append(source)
if source == dest:
result.append(path)
else:
for i in Alist[source]:... | [
"I have changed your code a little bit, but the main problem is that you need to use copy when saving path, because if you don't that all other changes of path also change when path is in result, cause it is the same object actually.\ndef findAllPaths(vertices, Alist, source, dest):\n result = []\n path = []\... | [
0
] | [] | [] | [
"depth_first_search",
"graph",
"python",
"recursion"
] | stackoverflow_0074415587_depth_first_search_graph_python_recursion.txt |
Q:
Python Substring Regex Extraction
I have the following types of strings:
FWI20010112
DC20030405 etc...
I need to extract segments of the strings into separate variables like this (example):
name: FWI
year: 2001
month: 01
day: 12
So, the name segment of the string can vary between 2 or 3 characters, and the followi... | Python Substring Regex Extraction | I have the following types of strings:
FWI20010112
DC20030405 etc...
I need to extract segments of the strings into separate variables like this (example):
name: FWI
year: 2001
month: 01
day: 12
So, the name segment of the string can vary between 2 or 3 characters, and the following digits always follow the same format... | [
"import re\n\nstrings_list = ['FWI20010112','DC20030405']\nprint(re.sub(r'(\\w*)(\\d{4})(\\d{2})(\\d{2})',r'name: \\1, year: \\2, month: \\3, day: \\4','\\n'.join(strings_list)))\n\nOutput:\nname: FWI, year: 2001, month: 01, day: 12\nname: DC, year: 2003, month: 04, day: 05\n\n"
] | [
2
] | [] | [] | [
"date",
"extract",
"python",
"substring"
] | stackoverflow_0074415681_date_extract_python_substring.txt |
Q:
How to query TRC20 transaction records in Python?
def test3(address):
url = 'https://apilist.tronscan.org/api/transfer?'
payload = {
"sort": 'timestamp',
'count':True,
'limit':20,
'start':0,
'token':'_',
'address':address
}
res = requests.get(url, params=payload)
obj = json.loads(... | How to query TRC20 transaction records in Python? | def test3(address):
url = 'https://apilist.tronscan.org/api/transfer?'
payload = {
"sort": 'timestamp',
'count':True,
'limit':20,
'start':0,
'token':'_',
'address':address
}
res = requests.get(url, params=payload)
obj = json.loads(res.text)
print(res)
test3('TQAuZ2YsGgPRPNpHXxoJZLHs... | [
"It's supposed to help\ndef test3(address):\n url = f'https://api.trongrid.io/v1/accounts/{address}/transactions/trc20?'\n payload = {\n \"sort\": 'blockNumber',\n 'limit':10,\n }\n res = requests.get(url,params=payload)\n obj = json.loads(res.text)\n return obj\n\n"
] | [
0
] | [] | [] | [
"python",
"tron"
] | stackoverflow_0072051445_python_tron.txt |
Q:
Python Generator Memory Usage
I recently came across this great stackoverflow post explaining the concept of yield What does the "yield" keyword do in Python?.
As such I did some exploring myself and found that the size of a generator, although substantially smaller than that of an iterable (list in this case) tha... | Python Generator Memory Usage | I recently came across this great stackoverflow post explaining the concept of yield What does the "yield" keyword do in Python?.
As such I did some exploring myself and found that the size of a generator, although substantially smaller than that of an iterable (list in this case) that the generator still holds a very ... | [
"a with a list comprehension is building and holding the entire object in memory.\nb is a generator and it doesn't build nor hold the entire object in memory. Instead, it keeps state and runs up to yield every time you call next().\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074409630_python.txt |
Q:
Python decorator? - can someone please explain this?
Apologies this is a very broad question.
The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protected - I am wondering what this does and how it does it? It appears to be checking that a valid us... | Python decorator? - can someone please explain this? | Apologies this is a very broad question.
The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protected - I am wondering what this does and how it does it? It appears to be checking that a valid user is logged in prior to executing the do_upload_ajax func... | [
"Take a good look at this enormous answer/novel. It's one of the best explanations I've come across.\nThe shortest explanation that I can give is that decorators wrap your function in another function that returns a function.\nThis code, for example:\n@decorate\ndef foo(a):\n print a\n\nwould be equivalent to this... | [
46,
17,
8,
6,
2,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"python_decorators"
] | stackoverflow_0012046883_python_python_3.x_python_decorators.txt |
Q:
Pandas groupby two columns and expand the third
I have a Pandas dataframe with the following structure:
A B C
a b 1
a b 2
a b 3
c d 7
c d 8
c d 5
c d 6
c d 3
e b 4
e b 3
e b ... | Pandas groupby two columns and expand the third | I have a Pandas dataframe with the following structure:
A B C
a b 1
a b 2
a b 3
c d 7
c d 8
c d 5
c d 6
c d 3
e b 4
e b 3
e b 2
e b 1
And I will like to transform ... | [
"Use GroupBy.cumcount and pandas.Series.add with 1, to start naming the new columns from 1 onwards, then pass this to DataFrame.pivot, and add DataFrame.add_prefix to rename the columns (C1, C2, C3, etc...). Finally use DataFrame.rename_axis to remove the indexes original name ('g') and transform the MultiIndex int... | [
12,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074401537_pandas_python.txt |
Q:
Issues installing mypy in VS Code
I'm trying to install the mypy linter in Visual Studio Code version 1.53 on MacOS. I've never used a linter before, so I'm not sure what to expect, though I know it should be highlighting type errors and the such. I'm trying to get mypy working in the context of a Django app.
I fo... | Issues installing mypy in VS Code | I'm trying to install the mypy linter in Visual Studio Code version 1.53 on MacOS. I've never used a linter before, so I'm not sure what to expect, though I know it should be highlighting type errors and the such. I'm trying to get mypy working in the context of a Django app.
I followed these steps and restarted VS Cod... | [
"In VS Code, \"mypy\" is one of the python code analysis tools, we usually install and use it as follows:\n\nInstall it. (pip install mypy)\nCheck the installation: (pip show mypy)\n\n\nSelect \"mypy\": (F1, Python: Select Linter, mypy)\n\n\nRun \"mypy\": (F1, Python: Run Linting)\n\n\n\nIts effect:\n\nReference: L... | [
10,
1,
0,
0
] | [] | [] | [
"linter",
"python",
"visual_studio_code"
] | stackoverflow_0066319787_linter_python_visual_studio_code.txt |
Q:
How would I ensure that only authorised users are able to access this class based view
I have a risk entry view that only project managers are able to access and no other user group how would I ensure that only this user group is able to access this view?
Risk page class-based view
@method_decorator(decorators, na... | How would I ensure that only authorised users are able to access this class based view | I have a risk entry view that only project managers are able to access and no other user group how would I ensure that only this user group is able to access this view?
Risk page class-based view
@method_decorator(decorators, name='dispatch')
class Risk_entry_page(View):
template_name = 'risk/riskEntry.html'
... | [
"If you want to give access to Authorized user only then you can introduce Permission in your project, so that user with certain permission can be accesible to your Risk_entry_page class\nhttps://django-permission.readthedocs.io/en/latest/\nIf You want only login user can access, you Risk_entry_page class then use ... | [
0,
0
] | [] | [] | [
"authorization",
"django",
"python"
] | stackoverflow_0074415265_authorization_django_python.txt |
Q:
Python: Use a dictionary to output the mode of a text file
I have a text file with an unknown amount of numbers included. My program reads in the values and calculates the minimum value, the maximum value, the range and the median. The last thing that I have to do is find the mode of the set.
I have a sorted list... | Python: Use a dictionary to output the mode of a text file | I have a text file with an unknown amount of numbers included. My program reads in the values and calculates the minimum value, the maximum value, the range and the median. The last thing that I have to do is find the mode of the set.
I have a sorted list that I am iterating through with a loop in order to place all o... | [
"Create a function compute_mode with a argument which takes in a list(in this case num_count). The function finds mode and stores them in a temp_list which is then printed out\nAppend all the mode values to a list like this:\ntemp_list.append(num)\n\nThen print the list like this:\nprint(\"Mode: \" ,temp_list)\n\nF... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0051249479_dictionary_list_python.txt |
Q:
Pandas resample: How to get resampled values from inexact timestamps
I have a dataframe with data that I obtained from a device, so that timestamp is not at exact seconds.
Like below:
hr ... | Pandas resample: How to get resampled values from inexact timestamps | I have a dataframe with data that I obtained from a device, so that timestamp is not at exact seconds.
Like below:
hr
timestamp ... | [
"You first need to chose a method to resample, then interpolate the gaps:\ndf_resamp = df.resample('250ms').mean().interpolate('cubic')\nprint(df_resamp.head(30))\n\nOutput:\n hr\ntimestamp \n2022-11-02 20:23:20.750 72.000000\n2022-11-02 20:23:21.000 71.73869... | [
0
] | [] | [] | [
"pandas",
"python",
"resample"
] | stackoverflow_0074415860_pandas_python_resample.txt |
Q:
Error when using pandas assign function when returned value is alist
I am wondering why pandas assign function cannot handle returned lists.
For example
df = pd.DataFrame({
"id" : [1,2,3,4,5],
"val" : [10,20,30,30,40]
})
def squareMe(x):
return x**2
df = df.assign(val2 = lambda x: squareMe(x.val))
... | Error when using pandas assign function when returned value is alist | I am wondering why pandas assign function cannot handle returned lists.
For example
df = pd.DataFrame({
"id" : [1,2,3,4,5],
"val" : [10,20,30,30,40]
})
def squareMe(x):
return x**2
df = df.assign(val2 = lambda x: squareMe(x.val))
# Out > Works fine : Returns a DataFrame with squared values
But if we r... | [
"Since you reference x.val in the call to squareMe, that function is passed a list (you can easily verify this by adding a debug statement to print type(x) inside the function).\nThus, x ** 2 returns a Series (since the expression is vectorized) and the assignment works correctly.\nBut when you return [x ** 2] you'... | [
1,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0069478364_pandas_python.txt |
Q:
Upload Photos Selenium
I need to upload images using selenium.
I'm trying to use the input (attached image) with the sendkeys command, but with no success.
foto = driver.find_element(By.XPATH, "//input[@accept='image/*,image/heif,image/heic']")
sleep(5)
foto.click()
sleep(5)
foto.s... | Upload Photos Selenium | I need to upload images using selenium.
I'm trying to use the input (attached image) with the sendkeys command, but with no success.
foto = driver.find_element(By.XPATH, "//input[@accept='image/*,image/heif,image/heic']")
sleep(5)
foto.click()
sleep(5)
foto.send_keys("C:\image11.jpg")
| [
"Uploading file with Selenium is done by sending the uploaded file to a special element. This is not an element you are clicking as a user via GUI to upload elements. The element actually receiving uploaded files normally matching this XPath:\n//input[@type='file']\nAgain, this element is not visible to a user.\nTr... | [
1
] | [] | [] | [
"file_upload",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074415167_file_upload_python_selenium_selenium_webdriver.txt |
Q:
Django redirect /D/ to /d/
I'm looking for a way to redirect any url that start with /D/ to the same URL with lowercased /d/.
/D/<anything_including_url_params>
to
/d/<anything_including_url_params>
I literally only want to redirect urls that start with /D/ - not /DABC/ etc...
The suffix can also be empty, eg. /D/... | Django redirect /D/ to /d/ | I'm looking for a way to redirect any url that start with /D/ to the same URL with lowercased /d/.
/D/<anything_including_url_params>
to
/d/<anything_including_url_params>
I literally only want to redirect urls that start with /D/ - not /DABC/ etc...
The suffix can also be empty, eg. /D/ > /d/
Is there a way to do that... | [
"You can make a view that directs with:\n# some_app/urls.py\n\nfrom django.views.generic import RedirectView\n\n# …\n\nurlpatterns = [\n path('d/', include(…)),\n path(\n 'D/<path:path>',\n RedirectView.as_view(\n url='/d/%(path)s', query_string=True, permanent=True\n ),\n )... | [
2,
0
] | [] | [] | [
"django",
"django_urls",
"django_views",
"python"
] | stackoverflow_0074408735_django_django_urls_django_views_python.txt |
Q:
How to make 80 folders using Python
I want to make 79 folder in my drive and want folder name is a number 1 to 79.
this is my code.
I used Google colab
import os
for i in range(1,80):
folder = "/content/drive/My Drive/project/Dataset"
os.makedirs(folder[i])
Please Help.
My code can be change if you have any t... | How to make 80 folders using Python | I want to make 79 folder in my drive and want folder name is a number 1 to 79.
this is my code.
I used Google colab
import os
for i in range(1,80):
folder = "/content/drive/My Drive/project/Dataset"
os.makedirs(folder[i])
Please Help.
My code can be change if you have any thought.
| [
"Use:\nimport os\n\nfolder = \"/content/drive/My Drive/project/Dataset\"\nfor i in range(1,80):\n os.mkdir(os.path.join(folder,str(i)))\n\n"
] | [
1
] | [] | [] | [
"for_loop",
"google_colaboratory",
"python"
] | stackoverflow_0074415844_for_loop_google_colaboratory_python.txt |
Q:
how could I remove the characters from this string
I am trying to remove any numbers from a set of string and returning just the characters.
def standardize_names(employee_name):
employee_name.strip()
print(employee_name)
for x in employee_name:
if x.isnumeric():
employee_name.repla... | how could I remove the characters from this string | I am trying to remove any numbers from a set of string and returning just the characters.
def standardize_names(employee_name):
employee_name.strip()
print(employee_name)
for x in employee_name:
if x.isnumeric():
employee_name.replace(x, '')
print(employee_name)
... | [
"I am writing this cold, without testing but I think you should be able to do the following:\ndef standardize_names(employee_name):\n employee_name = employee_name.strip()\n print(employee_name)\n name = ''\n for x in employee_name:\n if not x.isnumeric():\n name += x\n print(name)\... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074415870_python.txt |
Q:
Can not rashape a numpy array
I have the following code, which should decrease the width of an image passed as a numpy array by one. Array seam has the column-indices of the pixels to be deleted from corresponding row. To do the deletion, I flatten the matrix, delete the pixels using their coordinates with np.dele... | Can not rashape a numpy array | I have the following code, which should decrease the width of an image passed as a numpy array by one. Array seam has the column-indices of the pixels to be deleted from corresponding row. To do the deletion, I flatten the matrix, delete the pixels using their coordinates with np.delete (which works for one dimentional... | [
"I think there are two mistakes in the code:\n(1) to calculate your indices in the flattened array you should multiply x by the column width W, not by y (why?):\nindices = x * W + y\n\n(2) to remove a subarray (color pixel in your case) you should indicate the axis to apply the removal to (otherwise you only remove... | [
0
] | [] | [] | [
"image_processing",
"numpy",
"numpy_ndarray",
"python",
"reshape"
] | stackoverflow_0072511503_image_processing_numpy_numpy_ndarray_python_reshape.txt |
Q:
How to get data from a biography of an instagram profile with BeautifulSoup
I'm using the book "Web Scraping with Python by Ryan Mitchell" as a reference.
I'm trying to create a crawler that only grabs the bio content of an Instagram profile with the BeautifulSoup module in Python 3.10.
I made this script based on... | How to get data from a biography of an instagram profile with BeautifulSoup | I'm using the book "Web Scraping with Python by Ryan Mitchell" as a reference.
I'm trying to create a crawler that only grabs the bio content of an Instagram profile with the BeautifulSoup module in Python 3.10.
I made this script based on the examples given in the book:
from urllib.request import urlopen
from bs4 impo... | [
"if you are looking for a div with bs on that particular site, it is found like this:\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nuserpage = 'https://instagram.com/tarantinoxx'\n\nuserpage = urlopen(\"https://instagram.com/{}/\".format(\"tarantinoxx\"))\nbs = BeautifulSoup(userpage, 'html.... | [
0
] | [] | [] | [
"beautifulsoup",
"instagram",
"python"
] | stackoverflow_0074415657_beautifulsoup_instagram_python.txt |
Q:
MATLAB vs. Python Binary File Read
I have a MATLAB application that reads a .bin file and parses through the data. I am trying to convert this script from MATLAB to Python but am seeing discrepancies in the values being read.
The read function utilized in the MATLAB script is:
fname = 'file.bin';
f=fopen(fname);
d... | MATLAB vs. Python Binary File Read | I have a MATLAB application that reads a .bin file and parses through the data. I am trying to convert this script from MATLAB to Python but am seeing discrepancies in the values being read.
The read function utilized in the MATLAB script is:
fname = 'file.bin';
f=fopen(fname);
data = fread(f, 100);
fclose(f);
The Pyt... | [
"An exact translation of the MATLAB code, using NumPy, would be:\ndata = np.frombuffer(f.read(100), dtype=np.uint8).astype(np.float64)\n\n",
"python automatically transforms single bytes into unsigned integers, as done by matlab, so you just need to do the following.\nfname = 'file.bin'\nwith open(fname, mode='rb... | [
1,
0
] | [] | [] | [
"binaryfiles",
"matlab",
"python",
"readfile"
] | stackoverflow_0074415661_binaryfiles_matlab_python_readfile.txt |
Q:
Readable values in on axis with Matplotlib
I am working with Matplotlib and trying to plot a combo box with bars and lines. Below you can see my data:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from matplotlib.ticker import FormatStrFormatter
# Data
... | Readable values in on axis with Matplotlib | I am working with Matplotlib and trying to plot a combo box with bars and lines. Below you can see my data:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from matplotlib.ticker import FormatStrFormatter
# Data
data = {
'Year': ['2010','2011','2012',... | [
"The instantiation of the third Axes object with ax_3 = ax_2.twinx() can be circumvented by using just one extra y-axis on the right and plotting ChangeRate_1 and ChangeRate_2 on that axis keeping the (right) y-axis label as ChangeRate and then assigning correct labels to the lines.\n\nCode:\nfig, ax_1 = plt.subplo... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074415794_matplotlib_python.txt |
Q:
Two Sum Leetcode - Getting [0,0] on multiple lists input
I'm a beginner and trying to solve the two sum leetcode (easy problem).
I know my code is kind of basic but it works when I try it in another workspace(codecademy) and it also works if the leet code input is only 1 list.
However, when leetcode applies 2-3 li... | Two Sum Leetcode - Getting [0,0] on multiple lists input | I'm a beginner and trying to solve the two sum leetcode (easy problem).
I know my code is kind of basic but it works when I try it in another workspace(codecademy) and it also works if the leet code input is only 1 list.
However, when leetcode applies 2-3 lists(testcases on the site), the 2nd and 3rd list returns [0,0]... | [
"class Solution {\npublic int[] twoSum(int[] nums, int target) {\n int first=-1,second=-1;\n boolean flag=false;\n\n for(int i=0; i<nums.length; i++)\n {\n for(int j=0; j<nums.length; j++)\n {\n if(i!=j)\n {\n if(nums[i]+nums[j]==target)\n ... | [
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0073906989_list_python.txt |
Q:
copy variable by value not reference
quite new to python and struggling to achieve a value copy of a variable. have an algorithm that calls recursively another one but not getting the desired values since i think im instead using reference when assigning one variable to another in the following code:
def search(pr... | copy variable by value not reference | quite new to python and struggling to achieve a value copy of a variable. have an algorithm that calls recursively another one but not getting the desired values since i think im instead using reference when assigning one variable to another in the following code:
def search(problem, strategy, depthl, depthi, pruning):... | [
"Generally, if you have concerns with references and copying data, the copy module is going to give you the fine-grained copy control you're looking for. \ncopy.copy is guaranteed to do a \"shallow copy\", where a list will contain references to the old data, but will be a new list (or other container).\ncopy.deepc... | [
5,
0
] | [] | [] | [
"copy",
"python",
"reference",
"variables"
] | stackoverflow_0053214361_copy_python_reference_variables.txt |
Q:
Creating function points(self) from class Cards
I created a class called Cards and I need to create a function called points(self) which returns that card and its associated points. For example the I have three lists I created,
Card_rank = ["2", "3", "4", "5", "6", "Q", "J", "K", "7", "A"]
Cardsuit = ["H", "C", "... | Creating function points(self) from class Cards | I created a class called Cards and I need to create a function called points(self) which returns that card and its associated points. For example the I have three lists I created,
Card_rank = ["2", "3", "4", "5", "6", "Q", "J", "K", "7", "A"]
Cardsuit = ["H", "C", "S", "D"]
points2 = ["0", "2", "3", "4", "10", "11"]
... | [
"It appears that you are trying to define and build a deck of cards with each card having a rank. With that in mind, you might want to utilize the \"index\" function to determine the associated point value with a specific card. Following is an example of what that might look like.\nclass Deck:\n \n def __in... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074415634_python.txt |
Q:
Pandas doens't show scatter matrix
I don't see a scatter matrix if I run the following code in Visual Studio Code:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(1000, 4), columns=\['A','B','C','D'\])
pd.plotting.scatter_matrix(df, alpha=0.2)
There is also no error message in the command... | Pandas doens't show scatter matrix | I don't see a scatter matrix if I run the following code in Visual Studio Code:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(1000, 4), columns=\['A','B','C','D'\])
pd.plotting.scatter_matrix(df, alpha=0.2)
There is also no error message in the command line.
| [
"you want scatter matrix in question title but you use plot in code. Will you try this?\nimport numpy as np\nimport pandas as pd\nfrom pandas.plotting import scatter_matrix\n\ndf = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])\nscatter_matrix(df, alpha=0.2)\n\nif you still don't see scatter matr... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074415984_pandas_python.txt |
Q:
Pandas Float64 nans are not recognized
Pandas does not recognize NaNs which were computed as a result of an arithmetic operation between non-NaN Float64 and NaN float64.
Example below:
import pandas as pd
import numpy as np
print(f'{pd.__version__=}')
# pd.__version__='1.5.1'
print(f'{np.__version__=}')
# np.__ve... | Pandas Float64 nans are not recognized | Pandas does not recognize NaNs which were computed as a result of an arithmetic operation between non-NaN Float64 and NaN float64.
Example below:
import pandas as pd
import numpy as np
print(f'{pd.__version__=}')
# pd.__version__='1.5.1'
print(f'{np.__version__=}')
# np.__version__='1.23.4'
df = pd.DataFrame({'NonNa... | [
"Works fine for me, if the dtypes are all \"float64\" and not the title case \"Float64\" in df.astype(...)\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074414354_pandas_python.txt |
Q:
How to write a function that finds the mode of a list and saves it as dictionary?
I need help writing a function findMode(aList) that accepts a list of items as a parameter, and proceeds to find the mode. However, your Python solution must use a dictionary to keep track of the items and their counts as the meth... | How to write a function that finds the mode of a list and saves it as dictionary? | I need help writing a function findMode(aList) that accepts a list of items as a parameter, and proceeds to find the mode. However, your Python solution must use a dictionary to keep track of the items and their counts as the method of finding the mode (not parallel lists).
Here is the code that i have already tried... | [
"This should do the trick:\nfrom collections import Counter\n\ndef findMode(aList):\n counter = Counter(aList)\n max_count = max(counter.values())\n return [item for item, count in counter.items() if count == max_count]\n\n",
"def findMode(aList):\n dic_freq = {}\n for element in aList:\n if element... | [
4,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0055996523_dictionary_python.txt |
Q:
Openpyxl or Pandas, which is better at reading data from a excel file and returning corresponding values
Hello Stack OF Community,
*
Basically my goal is to extract values from an excel file, after reading through data from another column.*
**
Thickness** of parcel, with values for example - [0.12, 0.12, 0.13, 0.... | Openpyxl or Pandas, which is better at reading data from a excel file and returning corresponding values | Hello Stack OF Community,
*
Basically my goal is to extract values from an excel file, after reading through data from another column.*
**
Thickness** of parcel, with values for example - [0.12, 0.12, 0.13, 0.14, 0.14, 0.15] (Heading: Thickness (mm))
Weight of parcel, with values for example - [4.000, 3.500, 2.500, 4.... | [
"pandas is using openpyxl depending on the file extension under the hood in pandas.DataFrame.read_excel or pandas.DataFrame.to_excel anyways.\nYou can probably go with pandas as you just need the one method. The performance difference (if there even is one) shouldn't affect you in any way.\nhttps://pandas.pydata.or... | [
1,
0
] | [] | [] | [
"data_analysis",
"excel",
"openpyxl",
"pandas",
"python"
] | stackoverflow_0074415578_data_analysis_excel_openpyxl_pandas_python.txt |
Q:
Invalid extension for engine problem, iterating through directories and files
I have a code, which is working properly if I manually insert strings for path, directory and file name, here is the code:
path = r"test//ab3b//ab3b_all_anal.xlsx"
directory = "test"
file1 = "test//ab3b//ab3b80.csv"
df1 = all_calc_80(fi... | Invalid extension for engine problem, iterating through directories and files | I have a code, which is working properly if I manually insert strings for path, directory and file name, here is the code:
path = r"test//ab3b//ab3b_all_anal.xlsx"
directory = "test"
file1 = "test//ab3b//ab3b80.csv"
df1 = all_calc_80(file1, directory)
file2 = "test//ab3b//ab3b80m.csv"
df2 = all_calc_80m(file2, direct... | [
"If someone will still search for this answer, I had found a solution.\nMain discovery was regarding how to append path and file name to the list.\nIt is done with os.path.join(dirpath, filename), if you use os.walk.\nHere is the working code:\nseznam80 = []\nseznam80m = []\nseznam120 = []\nseznam120m = []\nseznam1... | [
0
] | [] | [] | [
"automation",
"excel",
"operating_system",
"python",
"xlsxwriter"
] | stackoverflow_0074322944_automation_excel_operating_system_python_xlsxwriter.txt |
Q:
How to send multiple commands to FTP server with python 'socket'?
I'm trying to print file catalogue from FTP server. I have two sockets: first to send commands to the server, second to get requested data. To parse data, I want to send LIST command multiple times, but I don't know how to do this properly. Here is ... | How to send multiple commands to FTP server with python 'socket'? | I'm trying to print file catalogue from FTP server. I have two sockets: first to send commands to the server, second to get requested data. To parse data, I want to send LIST command multiple times, but I don't know how to do this properly. Here is my code:
import socket
HOST = '[IP address]'
USERNAME = '[login]'
PASS... | [
"\nI think I can just recreate the connection every time I want to send another command, but there must be a better solution.\n\nFTP has a control connection for all commands and a data connection for each command transferring data. So the control connection (sock_1 in your code) will be kept open, the data connect... | [
2
] | [] | [] | [
"ftp",
"ftp_client",
"python",
"sockets"
] | stackoverflow_0074415707_ftp_ftp_client_python_sockets.txt |
Q:
Error! blahfile is not UTF-8 encoded. Saving disabled
So, I'm trying to write a gzip file, actually from the net, but to simplify I wrote some very basic test.
import gzip
LINES = [b'I am a test line' for _ in range(100_000)]
f = gzip.open('./test.text.gz', 'wb')
for line in LINES:
f.write(line)
f.close()
It ... | Error! blahfile is not UTF-8 encoded. Saving disabled | So, I'm trying to write a gzip file, actually from the net, but to simplify I wrote some very basic test.
import gzip
LINES = [b'I am a test line' for _ in range(100_000)]
f = gzip.open('./test.text.gz', 'wb')
for line in LINES:
f.write(line)
f.close()
It runs great, and I can see in Jupyter that it has created th... | [
"The very simple answer to this is none of the above. This is a very misleading error message, especially when the code you've written was designed to save a binary file with a weird extension.\nWhat this actually means is ...\n I HAVE NO IDEA HOW TO DISPLAY THIS DATA ! - Yours Jupyter\n\nSo, go to your File Exp... | [
43,
0
] | [] | [] | [
"binary_data",
"gzip",
"jupyter",
"jupyter_notebook",
"python"
] | stackoverflow_0061114350_binary_data_gzip_jupyter_jupyter_notebook_python.txt |
Q:
Python equivalent for gcloud auth print-identity-token command
The gcloud auth print-identity-token command prints an identity token for the specified account.
$(gcloud auth print-identity-token \
--audiences=https://example.com \
--impersonate-service-account my-sa@my-project.iam.gserviceaccount.c... | Python equivalent for gcloud auth print-identity-token command | The gcloud auth print-identity-token command prints an identity token for the specified account.
$(gcloud auth print-identity-token \
--audiences=https://example.com \
--impersonate-service-account my-sa@my-project.iam.gserviceaccount.com \
--include-email)
How do I do the same using Python?
| [
"Here a code sample (not so easy and well documented)\nimport google.auth.transport.requests\nfrom google.auth.impersonated_credentials import IDTokenCredentials\nSCOPES = ['https://www.googleapis.com/auth/cloud-platform']\n\nrequest = google.auth.transport.requests.Request()\n\naudience = 'my_audience'\n\ncreds, _... | [
1
] | [] | [] | [
"gcloud",
"google_cloud_platform",
"python"
] | stackoverflow_0074411491_gcloud_google_cloud_platform_python.txt |
Q:
Picking out a specific column in a table
My goal is to import a table of astrophysical data that I have saved to my computer (obtained from matching 2 other tables in TOPCAT, if you know it), and extract certain relevant columns. I hope to then do further manipulations on these columns. I am a complete beginner in... | Picking out a specific column in a table | My goal is to import a table of astrophysical data that I have saved to my computer (obtained from matching 2 other tables in TOPCAT, if you know it), and extract certain relevant columns. I hope to then do further manipulations on these columns. I am a complete beginner in python, so I apologise for basic errors. I've... | [
"Maybie you can try dataset.iloc[:,0] . With iloc you can extract the column or line you want by index(not only). [:,0] for all the lines of 1st column.\n",
"The file is incorrectly named.\nI expect that you are reading a csv file or an xlsx or txt file. So the (windows) path would look similar to this:\nimport p... | [
0,
0
] | [] | [] | [
"astronomy",
"python"
] | stackoverflow_0074415916_astronomy_python.txt |
Q:
Selenium stopped working. Error received: Message: element click intercepted: Element is not clickable at point
My python script to browse a website in headless mode using selenium was working fine for a long time but it stopped working suddenly. 'Submit' button on [this][1] page was clickable easily but not anymo... | Selenium stopped working. Error received: Message: element click intercepted: Element is not clickable at point | My python script to browse a website in headless mode using selenium was working fine for a long time but it stopped working suddenly. 'Submit' button on [this][1] page was clickable easily but not anymore.
This is part of my code which is not working anymore:
def result(update: Update, context: CallbackContext):
... | [
"You have to wait for the elements to be clickable.\nFirst of all this related to the submit button you are clicking, but I'd add this check also before selecting the Result since I see when the page is opened spinner is appeared until the page is loaded.\nSo, I'd change your code to be as following:\nfrom selenium... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver",
"webdriverwait"
] | stackoverflow_0074414690_python_selenium_selenium_chromedriver_selenium_webdriver_webdriverwait.txt |
Q:
Getting different results in training a tensorflow model using keras classes and strings for compilation
Hi I am trying to train a tensorflow convolutional model on a small portion of the kaggle dogs-vs-cats dataset.
I am building the model in the following way:
from tensorflow import keras
from tensorflow.keras i... | Getting different results in training a tensorflow model using keras classes and strings for compilation | Hi I am trying to train a tensorflow convolutional model on a small portion of the kaggle dogs-vs-cats dataset.
I am building the model in the following way:
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.utils import image_dataset_from_directory
import pathlib
new_base_dir = pa... | [
"It is because the string \"accuracy\" is converted to tf.keras.metrics.BinaryAccuracy() (which turns a float into 0-1 automatically with 0.5 as the threshold) under the hood. In your first case, you are using tf.keras.metrics.Accuracy() which requires exact match while your model only outputs a float number probab... | [
1
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074415813_conv_neural_network_deep_learning_keras_python_tensorflow.txt |
Q:
Execute a function on first startup only
How to - let a function run only on the first startup?
I have tried creating a value-adding mechanism (adding 1 to a variable after startup) but I failed.
result = _winreg.QueryValueEx(key, "MachineGuid")
ID = str(result)
licence_path = 'C:\\Program Files\\Common Files\\Sy... | Execute a function on first startup only | How to - let a function run only on the first startup?
I have tried creating a value-adding mechanism (adding 1 to a variable after startup) but I failed.
result = _winreg.QueryValueEx(key, "MachineGuid")
ID = str(result)
licence_path = 'C:\\Program Files\\Common Files\\System\\read.txt'
oon = 0
def first_time_open_... | [
"There is a way that can solve this problem. On each run of the code, in order to understand that a function is run before or not, is to save the flag to a file such as pickle or a database. The code below shows a simple example such that the function only runs one time. This kind of problems can be solved by savin... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0074415737_python.txt |
Q:
Return all possible placements of buildings in a city grid using backtracking
I have two inputs
An NxM city grid where empty spaces represent vacant lots, and X's represent filled lots
e.g
X XXX
X X
XXXX
XX X
This is in the format List[List[str]]
And an integer that represents the number of buildings require... | Return all possible placements of buildings in a city grid using backtracking | I have two inputs
An NxM city grid where empty spaces represent vacant lots, and X's represent filled lots
e.g
X XXX
X X
XXXX
XX X
This is in the format List[List[str]]
And an integer that represents the number of buildings required.
Return a list of all possible placements, i.e. List[List[List[str]]]
for example... | [
"find_permutations doesn't take in required_building_count where it's defined.\ndef find_permutations(initial_city_map, current_city_map, building_code, possible_combinations):\n\nought to be\ndef find_permutations(initial_city_map, current_city_map, building_code, required_building_count, possible_combinations):\n... | [
0,
0
] | [] | [] | [
"algorithm",
"backtracking",
"dynamic_programming",
"python"
] | stackoverflow_0074415918_algorithm_backtracking_dynamic_programming_python.txt |
Q:
How to create a function which tells how far Turtle has travelled in Python?
import math
import turtle
import random
# Starting Code
def moveTurtle():
for count in range(10):
choice = move.randint(1,2)
if (choice==1):
turtle.forward(move.randint(3, 30))
elif(choice==2):
turtle.right(move.rand... | How to create a function which tells how far Turtle has travelled in Python? | import math
import turtle
import random
# Starting Code
def moveTurtle():
for count in range(10):
choice = move.randint(1,2)
if (choice==1):
turtle.forward(move.randint(3, 30))
elif(choice==2):
turtle.right(move.randint(1,234))
def testTurtle():
turtle.forward(100)
turtle.left(90)
turtle.forwa... | [
"To find distance you will need to add a new variable with distance. As I know, turtle doesn't count distance, because turtle can move in circle, or in air, and you may need different types of moving path length.\nTo count, simply add the same length you move. Try this :\nimport math\nimport turtle\nimport random\n... | [
0
] | [] | [] | [
"function",
"math",
"python",
"python_turtle",
"random"
] | stackoverflow_0074416028_function_math_python_python_turtle_random.txt |
Q:
Matplot SavFig Returns Blank Image
I am trying to download some plots as images and these are being downloaded as blank images. The direct download works but the download through the drive shows blank images.
ANY HELP WOULD BE HIGHLY APPRECIATED PLEASE.
If I try to directly download the image, it is as expected, h... | Matplot SavFig Returns Blank Image | I am trying to download some plots as images and these are being downloaded as blank images. The direct download works but the download through the drive shows blank images.
ANY HELP WOULD BE HIGHLY APPRECIATED PLEASE.
If I try to directly download the image, it is as expected, however, if I try through collab, it down... | [
"This issue has been fixed.\nbelow lines of code should be replaced with the ones that I shared in the next code block\nplt.savefig(\"eee.png\") \ndrive.mount('/content/gdrive')\n!touch \"/content/gdrive/MyDrive/eee.png\"\nfrom google.colab import files\nfiles.download('/content/sample_data/eee.png')\n\ncorrect lin... | [
1,
0
] | [] | [] | [
"graph",
"matplotlib",
"plot",
"python",
"savefig"
] | stackoverflow_0074402097_graph_matplotlib_plot_python_savefig.txt |
Q:
How to replace an integer in Python without using int()
I'm learning Python from Brian Heinold's A Practical Introduction to Python Programming where exercise 24 in chapter 6 reads:
In calculus, the derivative of x4 is 4x3. The derivative of x5 is 5x4. The derivative of x6 is 6x5. This pattern continues. Write a ... | How to replace an integer in Python without using int() | I'm learning Python from Brian Heinold's A Practical Introduction to Python Programming where exercise 24 in chapter 6 reads:
In calculus, the derivative of x4 is 4x3. The derivative of x5 is 5x4. The derivative of x6 is 6x5. This pattern continues. Write a program that asks the user for input like x^3 or x^25 and pri... | [
"Ok i'll explain what I meant in the comments. If these are strings, not numbers, what is the pattern? Replace the last digit with the digit just before it in the digit sequence, e.g. turn a final \"5\" into a \"4\". Unless it's a zero, in which case do that to the digit before and add a \"9\". Like this:\ndigits =... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074415932_python.txt |
Q:
How can I add list to another list? PANDAS df.loc
I'm Newbie to Pandas.
My df is a CSV with accounting information, I have variables with a list of accounts inside them, and I want to add them to another variable first and then use df.loc
df = pd.read_csv('2021BALANCE.csv')
menor = (df['account_1'] < 10000) # j... | How can I add list to another list? PANDAS df.loc | I'm Newbie to Pandas.
My df is a CSV with accounting information, I have variables with a list of accounts inside them, and I want to add them to another variable first and then use df.loc
df = pd.read_csv('2021BALANCE.csv')
menor = (df['account_1'] < 10000) # just filtering
#LIST OF ACCOUNTS inside variables
... | [
"If you're trying to \"merge\" the lists into a single flat list, you need to use the spread operator (https://how.wtf/spread-operator-in-python.html) to \"unpack\" the lists you're trying to insert into the new one. Otherwise you're nesting the lists, causing the .loc to throw the error.\nTry using this in the dec... | [
0
] | [] | [] | [
"data_science",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074415739_data_science_dataframe_numpy_pandas_python.txt |
Q:
Cannot scrap the contents of a table. I get some sort of call to a database instead. How to get the contents that I can see with Python BeautifulSoup?
When using BeautifulSoup to scrap a table from https://egov.uscis.gov/processing-times/historic-pt, instead of getting the values that can bee seen in the content o... | Cannot scrap the contents of a table. I get some sort of call to a database instead. How to get the contents that I can see with Python BeautifulSoup? | When using BeautifulSoup to scrap a table from https://egov.uscis.gov/processing-times/historic-pt, instead of getting the values that can bee seen in the content of the table, I get what seems to be a call from some sort of database:
table = webpage.select("table.records")
table
df = pd.read_html(str(table), na_values... | [
"The data is loaded from different URL so beautifulsoup doesn't see it, try:\nimport requests\nimport pandas as pd\n\nurl = \"https://egov.uscis.gov/processing-times/historical-forms-data\"\n\ndf = pd.DataFrame(requests.get(url, verify=False).json())\nprint(df)\n\nPrints:\n FORM_NUMBER FORM_NAME FORM_NAME_ES ... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074415783_beautifulsoup_python_web_scraping.txt |
Q:
Why this Object Oriented Programming code is not working in Python?
class Bike:
def __init__(self, speed):
self.speed = speed
def speed(self):
if (self.speed) > 120:
print("You are driving fast.")
else:
print("You are diving safely.")
bike1 = Bike(32)
bike1... | Why this Object Oriented Programming code is not working in Python? | class Bike:
def __init__(self, speed):
self.speed = speed
def speed(self):
if (self.speed) > 120:
print("You are driving fast.")
else:
print("You are diving safely.")
bike1 = Bike(32)
bike1.speed()
It is showing:
Traceback (most recent call last):
File "C:\U... | [
"Attributes of an object are stored in its __dict__ namespace(if it has one). This is True for both the class and the instance itself. Your class Bike has a method called speed which is basically a callable attribute(a long with other attributes that is not important for us now). Your instance bike1 has only one in... | [
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0074415791_oop_python.txt |
Q:
Access Apache Beam metrics values during pipeline run in python?
I'm using the direct runner of Apache Beam Python SDK to execute a simple pipeline similar to the word count example. Since I'm processing a large file, I want to display metrics during the execution. I know how to report the metrics, but I can't fin... | Access Apache Beam metrics values during pipeline run in python? | I'm using the direct runner of Apache Beam Python SDK to execute a simple pipeline similar to the word count example. Since I'm processing a large file, I want to display metrics during the execution. I know how to report the metrics, but I can't find any way to access the metrics during the run.
I found the metrics() ... | [
"The direct runner is generally used for testing, development, and small jobs, and Pipeline.run() was made blocking for simplicity. On other runners Pipeline.run() is asynchronous and the result can be used to monitor the pipeline progress during execution.\nYou could try running a local version of an OSS runner li... | [
3,
2,
1
] | [] | [] | [
"apache_beam",
"python"
] | stackoverflow_0068803591_apache_beam_python.txt |
Q:
How access odd index elements and even index elements and merge them vertically
I've started learning numpy since yesterday.
my AIM is
Extract odd index elements from numpy array & even index elements from numpy and merge side by side vertically.
Let's say I have the array
mat = np.array([[1, 1, 0, 0, 0],
... | How access odd index elements and even index elements and merge them vertically | I've started learning numpy since yesterday.
my AIM is
Extract odd index elements from numpy array & even index elements from numpy and merge side by side vertically.
Let's say I have the array
mat = np.array([[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0... | [
"Looks like you want:\nmat[np.r_[1:mat.shape[0]:2,:mat.shape[0]:2]].T\n\nOutput:\narray([[0, 0, 1, 1, 1],\n [1, 0, 1, 0, 0],\n [0, 0, 0, 0, 1],\n [0, 0, 0, 1, 0],\n [1, 0, 0, 1, 1]])\n\nIntermediate:\nnp.r_[1:mat.shape[0]:2,:mat.shape[0]:2]\n\noutput: array([1, 3, 0, 2, 4])\n",
"While the ... | [
2,
2,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074415658_numpy_python.txt |
Q:
"save() got an unexpected keyword argument 'commit'" error in functional view
I got this error in my functional view:
save() got an unexpected keyword argument 'commit'
I'm try to save one object in database. 'debtors' is Many to Many field in models.py.
forms.py
class ExpenseForm(forms.ModelForm):
class Meta:... | "save() got an unexpected keyword argument 'commit'" error in functional view | I got this error in my functional view:
save() got an unexpected keyword argument 'commit'
I'm try to save one object in database. 'debtors' is Many to Many field in models.py.
forms.py
class ExpenseForm(forms.ModelForm):
class Meta:
model = Expense
fields = ('amount', 'text', 'debtors', 'date', 'ti... | [
"Your form is not an ExpenseForm, it is a model object Expense, hence commit=False makes no sense, and neither does .save_m2m():\nfrom django.contrib.auth.decorators import login_required\n\n\n@login_required\ndef expenseformview(request, pk):\n if request.method == 'POST':\n form = ExpenseForm(request.PO... | [
3
] | [] | [] | [
"django",
"python",
"save",
"view"
] | stackoverflow_0074416186_django_python_save_view.txt |
Q:
Assign a Series with its index to a multiIndex dataframe with loc
With a dataframe of an index level of 2, either empty or filled with something:
import pandas as pd
midx = pd.MultiIndex(levels=[[],[]],
codes=[[],[]],
names=[u'var_name', u'modalities']
... | Assign a Series with its index to a multiIndex dataframe with loc | With a dataframe of an index level of 2, either empty or filled with something:
import pandas as pd
midx = pd.MultiIndex(levels=[[],[]],
codes=[[],[]],
names=[u'var_name', u'modalities']
)
df = pd.DataFrame(index=midx)
df.loc[("foo","bar"),"A"] = 3
df
###... | [
"I did not find the method with loc.\nMy current solution is to use the concat method, which feels a bit unnatural to me (The first answer with a solution will get the checkmark).\nSolution with concat\nimport pandas as pd\nmidx = pd.MultiIndex(levels=[[],[]],\n codes=[[],[]],\n ... | [
0
] | [] | [] | [
"dataframe",
"multi_index",
"pandas",
"python"
] | stackoverflow_0074413783_dataframe_multi_index_pandas_python.txt |
Q:
Import CSV with every row containing the column headers
I'm dealing with a csv that repeats its headers name within each rows:
player: John Doe ; level: 45 ; last_login: 7854414174 ; coins: 7600
player: Anckx Uj ; level: 471 ; last_login: 7854418847 ; coins: 684111
I'd like to know how I can only select the value... | Import CSV with every row containing the column headers | I'm dealing with a csv that repeats its headers name within each rows:
player: John Doe ; level: 45 ; last_login: 7854414174 ; coins: 7600
player: Anckx Uj ; level: 471 ; last_login: 7854418847 ; coins: 684111
I'd like to know how I can only select the values when importing it using pandas so that the output looks lik... | [
"One solution might be to can clean the rows after the loading:\ndf = df.apply(lambda x: x.str.replace(r\"^[^:]+:\", \"\").str.strip())\nprint(df)\n\nPrints:\n player level last_login coins\n0 John Doe 45 7854414174 7600\n1 Anckx Uj 471 7854418847 684111\n\n\nAnd probably convert the level/coins... | [
0,
0,
0
] | [] | [] | [
"csv",
"pandas",
"python",
"txt"
] | stackoverflow_0074413770_csv_pandas_python_txt.txt |
Q:
Dependency injection with FastAPI problem
I am getting an error when using dependency_overrides
https://fastapi.tiangolo.com/advanced/testing-dependencies/
I have sample project (in attachment) with the following structure:
service.py
from pydantic import BaseModel
class Service(BaseModel):
key: int
name: ... | Dependency injection with FastAPI problem | I am getting an error when using dependency_overrides
https://fastapi.tiangolo.com/advanced/testing-dependencies/
I have sample project (in attachment) with the following structure:
service.py
from pydantic import BaseModel
class Service(BaseModel):
key: int
name: str
handler.py
from service import Service
cl... | [
"Please replace the content of your unit_tests/test.py:\nfrom fastapi.testclient import TestClient\nfrom handler import ServiceHandler\nimport factory\nfrom service import Service\nimport pytest\nfrom main import app\nimport asyncio\nfrom unittest.mock import AsyncMock\n \n\n\n@pytest.fixture(scope=\"session\", ... | [
0
] | [] | [] | [
"dependency_injection",
"fastapi",
"pydantic",
"python",
"python_3.x"
] | stackoverflow_0064551295_dependency_injection_fastapi_pydantic_python_python_3.x.txt |
Q:
How to get the index of a repeating element in list?
I wanted to make a Japanese transliteration program.
I won't explain the details, but some characters in pairs have different values than if they were separated, so I made a loop that gets two characters (current and next)
b = "きゃきゃ"
b = list(b)
name = ""
for ... | How to get the index of a repeating element in list? | I wanted to make a Japanese transliteration program.
I won't explain the details, but some characters in pairs have different values than if they were separated, so I made a loop that gets two characters (current and next)
b = "きゃきゃ"
b = list(b)
name = ""
for i in b:
if b.index(i) + 1 <= len(b) - 1:
if i ... | [
"if you are looking for the indices of 'き':\nb = \"きゃきゃ\"\nb = list(b)\nindices = [i for i, x in enumerate(b) if x == \"き\"]\nprint(indices)\n[0, 2]\n\n",
"Rather than looking ahead a character, it may be easier to store a reference to the previous character, and replacing the previous transliteration if you foun... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074415710_list_python.txt |
Q:
How to find a US zip code in a string using regular expression?
Fill in the code to check if the text passed includes a possible U.S. zip code, formatted as follows: exactly 5 digits, and sometimes, but not always, followed by a dash with 4 more digits. The zip code needs to be preceded by at least one space, and ... | How to find a US zip code in a string using regular expression? | Fill in the code to check if the text passed includes a possible U.S. zip code, formatted as follows: exactly 5 digits, and sometimes, but not always, followed by a dash with 4 more digits. The zip code needs to be preceded by at least one space, and cannot be at the start of the text.
Couldn't produce the required out... | [
"You could use\n(?!\\A)\\b\\d{5}(?:-\\d{4})?\\b\n\nFull code:\nimport re\n\ndef check_zip_code (text):\n m = re.search(r'(?!\\A)\\b\\d{5}(?:-\\d{4})?\\b', text)\n return True if m else False\n\nprint(check_zip_code(\"The zip codes for New York are 10001 thru 11104.\")) # True\nprint(check_zip_code(\"90210 is ... | [
2,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0062157006_python_regex.txt |
Q:
Error in the PyCharm Python terminal, indicates the sign
After updating PyCharm, an error started popping up in the terminal:
PS C:\Users\kant\Desktop\Шаблон TelegramBot> python main.py
Сбой выполнения программы python.exe: Системе не удается найти указанный путьстрока:1 знак:1
+ python main.py
+ ~~~~~~~~~~~~~~.
с... | Error in the PyCharm Python terminal, indicates the sign | After updating PyCharm, an error started popping up in the terminal:
PS C:\Users\kant\Desktop\Шаблон TelegramBot> python main.py
Сбой выполнения программы python.exe: Системе не удается найти указанный путьстрока:1 знак:1
+ python main.py
+ ~~~~~~~~~~~~~~.
строка:1 знак:1
+ python main.py
+ ~~~~~~~~~~~~~~
+ Categor... | [
"Шt looks like the problem was in python 3.11 after reinstalling everything is fine\n"
] | [
0
] | [] | [] | [
"pycharm",
"python",
"telegram"
] | stackoverflow_0074416037_pycharm_python_telegram.txt |
Q:
How to fix an attribute error when clearing an entry box
While I was writing my code I stumbled over this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1482, in __call__
return self.func(*args)
File "C:\Users\Bryan\Desktop\Python ov... | How to fix an attribute error when clearing an entry box | While I was writing my code I stumbled over this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1482, in __call__
return self.func(*args)
File "C:\Users\Bryan\Desktop\Python overhoorprogramma.py", line 18, in verify
oentry.delete(0,EN... | [
"The grid method of every Tkinter widget works in-place (it always returns None). \nIn other words, every line like this:\nolabel = ttk.Label(gui,text=Fransevertaling,font=(\"Times\", 18), background=\"white\").grid(row=0, column=0,padx=5, pady=5, sticky=\"W\")\n\nshould be written like this:\nolabel = ttk.Label(g... | [
2,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0022284378_python_tkinter.txt |
Q:
python issue adds a new label
take a look at this code
well it happens to just add another label for no reason
import tkinter
from tkinter import *
clicks = 1
def click_count():
global clicks
# making the label that shows how many idk you have
label = Label(frame, text="you have " + str(clicks), fon... | python issue adds a new label | take a look at this code
well it happens to just add another label for no reason
import tkinter
from tkinter import *
clicks = 1
def click_count():
global clicks
# making the label that shows how many idk you have
label = Label(frame, text="you have " + str(clicks), font=(('Courrier'), 32))
label.pac... | [
"It does not add a Label for no reason. It adds the label because that's what your function tells it to do. Each time you click the button, the function is executed that creates and packs a new Label.\nWhat you should do is create the label at the onset and link it to a variable. Then, you can change the value of t... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074415624_python_tkinter.txt |
Q:
Data file processing - Python
I have been assigned a task, and I cannot seem to figure out how I should proceed with it. It seemed relatively easy, but I must be doing something wrong, I would love it if someone could give me guidance. The code I have so far is:
infile = open("dataset.txt", "r")
outfile = open("em... | Data file processing - Python | I have been assigned a task, and I cannot seem to figure out how I should proceed with it. It seemed relatively easy, but I must be doing something wrong, I would love it if someone could give me guidance. The code I have so far is:
infile = open("dataset.txt", "r")
outfile = open("emails.txt", "w")
def main():
line... | [
"\nYou defined a function but you didn't call it.\nstr.find method doesn't accept two strings. Its signature is str.find(sub[, start[, end]]). take a look at the documentation\n\nAs you've already done, you should iterate through the lines in the dataset.txt file. Then grab email addresses. Based on your data you c... | [
1,
0
] | [] | [] | [
"iteration",
"loops",
"python",
"text_processing"
] | stackoverflow_0074416248_iteration_loops_python_text_processing.txt |
Q:
How do I make the space between subplots smaller?
I have this subplot-
fig = make_subplots(rows = 4, cols = 1)
fig.append_trace(go.Scatter(
x=[3, 4, 5],
y=[1000, 1100, 1200],
), row=1, col=1)
fig.append_trace(go.Scatter(
x=[2, 3, 4],
y=[100, 110, 120],
), row=2, col=1)
fig.append_trace(go.Scatter(
... | How do I make the space between subplots smaller? | I have this subplot-
fig = make_subplots(rows = 4, cols = 1)
fig.append_trace(go.Scatter(
x=[3, 4, 5],
y=[1000, 1100, 1200],
), row=1, col=1)
fig.append_trace(go.Scatter(
x=[2, 3, 4],
y=[100, 110, 120],
), row=2, col=1)
fig.append_trace(go.Scatter(
x=[0, 1, 2],
y=[10, 11, 12]
), row=3, col=1)
fi... | [
"When you increase the height to 3200 in the css is totally equivalent to fig['layout'].update(margin=dict(l=0,r=0,b=0,t=0), height=3200). Therefore, it is a Plotly problem rather than a Dash problem. You can solve it by adjusting the vertical space as follows:\nfig = make_subplots(rows = 4, cols = 1, vertical_spac... | [
1
] | [] | [] | [
"css",
"plotly",
"plotly_dash",
"plotly_python",
"python"
] | stackoverflow_0074415841_css_plotly_plotly_dash_plotly_python_python.txt |
Q:
While loop, how do I condition for when input equals nothing?
Create a program that will keep track of items for a shopping list. The program should keep asking for new items until nothing is entered (no input followed by enter key). The program should then display the full shopping list
How do I write the conditi... | While loop, how do I condition for when input equals nothing? | Create a program that will keep track of items for a shopping list. The program should keep asking for new items until nothing is entered (no input followed by enter key). The program should then display the full shopping list
How do I write the condition so it works?
The code I'm writing looks like this:
x = []
i = 0... | [
"Find len of user input & check with if accordingly\nx = []\n \nwhile 1:\n ask= input('what u want?')\n if len(ask)>0:\n x.append(ask)\n\n else:\n print(\"Good bye\")\n break\n \nprint(x)\n\noutput #\nwhat u want?rice\nwhat u want?sugar\nwhat u want?\nGood bye\n['rice', 'sugar']\n\nC... | [
1,
1
] | [] | [] | [
"conditional_statements",
"python",
"while_loop"
] | stackoverflow_0074416350_conditional_statements_python_while_loop.txt |
Q:
how to truncate an array of uint8 rather than overflow, when adding a value?
I would like to implement a tool to adjust the brightness of a RGB image, which is simply a (N, M, 3)-shaped numpy array of dtype uint8.
The algorithm is really simple, I'm just adding an integer in range [-255, 255] to all pixels of my i... | how to truncate an array of uint8 rather than overflow, when adding a value? | I would like to implement a tool to adjust the brightness of a RGB image, which is simply a (N, M, 3)-shaped numpy array of dtype uint8.
The algorithm is really simple, I'm just adding an integer in range [-255, 255] to all pixels of my images.
Unfortunately, I also need to truncate the resulting pixel value to stay in... | [
"A bit late but I've used a convenient non-linear function (arctan) instead of clipping the overflow values:\nfrom PIL import Image\nimport numpy as np\n\nfactor = 3\nc = 512 / np.pi # a constant to be used along with arctan\n\nadjusted_image = np.arctan(data/c * factor) * c\nImage.fromarray(adjusted_image.astype(... | [
1
] | [] | [] | [
"image_processing",
"integer_overflow",
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0056026014_image_processing_integer_overflow_numpy_numpy_ndarray_python.txt |
Q:
How to save a pandas DataFrame table as a png
I constructed a pandas dataframe of results. This data frame acts as a table. There are MultiIndexed columns and each row represents a name, ie index=['name1','name2',...] when creating the DataFrame. I would like to display this table and save it as a png (or any grap... | How to save a pandas DataFrame table as a png | I constructed a pandas dataframe of results. This data frame acts as a table. There are MultiIndexed columns and each row represents a name, ie index=['name1','name2',...] when creating the DataFrame. I would like to display this table and save it as a png (or any graphic format really). At the moment, the closest I ca... | [
"Pandas allows you to plot tables using matplotlib (details here).\nUsually this plots the table directly onto a plot (with axes and everything) which is not what you want. However, these can be removed first:\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom pandas.table.plotting import table # EDIT: se... | [
100,
71,
37,
23,
11,
8,
8,
4,
3,
3,
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0035634238_pandas_python.txt |
Q:
InternalError: Failed copying input tensor from CPU:0 to GPU:0 in order to run _EagerConst: Dst tensor is not initialized
I am running a code for Tensorflow cross validation training with 10 folds. The code works in a for loop where I have to run the model.fit each time of the loop. When I run it for the first fol... | InternalError: Failed copying input tensor from CPU:0 to GPU:0 in order to run _EagerConst: Dst tensor is not initialized | I am running a code for Tensorflow cross validation training with 10 folds. The code works in a for loop where I have to run the model.fit each time of the loop. When I run it for the first fold it works well and then GPU memory becomes full.
Here is my for loop:
acc_per_fold = []
loss_per_fold = []
for train, test in ... | [
"I faced this problem long time ago, Even after reducing the batch size didn’t work. My GPU was rtx 3060 12 GB RAM and it worked on Google Collab Pro\nHowever, there is one solution for this problem that may work. You can use the gc library which cleans the GPU after each iteration\nimport gc\n\nYou can put this st... | [
0
] | [] | [] | [
"deep_learning",
"python",
"tensorflow"
] | stackoverflow_0073912958_deep_learning_python_tensorflow.txt |
Q:
how do I make a function where i have three str values and based on the third str it prints the letters of str1 and str2?
If I have a function:
def chars(str1: str, str2: str, str3: str) -> str:
What should I put inside this so that it returns a new string where the character at index i is
str1[i] if str3[i] is 0... | how do I make a function where i have three str values and based on the third str it prints the letters of str1 and str2? | If I have a function:
def chars(str1: str, str2: str, str3: str) -> str:
What should I put inside this so that it returns a new string where the character at index i is
str1[i] if str3[i] is 0 and str2[i] if str3[i] is 1.
for example, if I had:
chars('dog', 'cat', '001')
it would output:
dot #since the first 0 is d f... | [
"The code can be fixed by adding a variable\ndef chars(str1: str, str2: str, str3: str) -> str:\n final = \"\" # I added a variable with name final\n for i in range(len(str3)):\n if str3[i] == '0':\n final += str1[i]\n else:\n final += str2[i]\n return final\n \nprint... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074416341_python_python_3.x.txt |
Q:
If list in a column of Pandas DataFrame
I am trying to verify if the elements of a list are contained in a DataFrame (DF) in Pandas.
This is the code that I've so far:
import pandas as pd
from pathlib import Path
data = pd.read_excel(r'/home/darteagam/diploma/bert/files/codon_positions.xlsx')
df = pd.DataFrame(da... | If list in a column of Pandas DataFrame | I am trying to verify if the elements of a list are contained in a DataFrame (DF) in Pandas.
This is the code that I've so far:
import pandas as pd
from pathlib import Path
data = pd.read_excel(r'/home/darteagam/diploma/bert/files/codon_positions.xlsx')
df = pd.DataFrame(data,columns=['position','codon','aminoacid'])
... | [
"First of all, currently your \"output\" that you've presented seems to be a sequence of prints to standard out. It would be ideal to have a list like ['ATC','AAC','ACC','TTT','GTC','CTC'].\nConcretely, I suspect the following change to your second loop would produce such a list.\n # <first for loop>...\n #\n... | [
1
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074414902_dataframe_list_pandas_python.txt |
Q:
How to open a frame without a button
I am creating a GUI using Python and Tkinter, with user authentication and registration and a homepage frames.
The submit function will verify the credentials in the database, authenticate the user, then should automatically transfer them to the homepage frame.
How can I switch... | How to open a frame without a button | I am creating a GUI using Python and Tkinter, with user authentication and registration and a homepage frames.
The submit function will verify the credentials in the database, authenticate the user, then should automatically transfer them to the homepage frame.
How can I switch frames without using button but rather wi... | [
"It is difficult to give you an answer because your code is not complete. You also provide parts of code (like for example the connection to a database) that are not relevant with your GUI.\nSo we have to do a lot of guesswork to give you an useful answer. That does not help you get an appropriate answer. But let's... | [
0
] | [] | [] | [
"frames",
"python",
"tkinter"
] | stackoverflow_0074249473_frames_python_tkinter.txt |
Q:
Getting what I thought was a good result but is not sufficient
I am working on a word cloud problem. I thought that my result covered the requirements as it produces a word cloud without the uninteresting words or punctuation, but apparently not. I cannot figure out what I am missing.
The script needs to process t... | Getting what I thought was a good result but is not sufficient | I am working on a word cloud problem. I thought that my result covered the requirements as it produces a word cloud without the uninteresting words or punctuation, but apparently not. I cannot figure out what I am missing.
The script needs to process the text, remove punctuation, ignore cases and words that do not cont... | [
" So here is some different approach!\npunctuations and uninteresting_words are given separately off course for to students understand easily. Since, both of them are same str type simply concatenating them saves us work. Doing such reduces iteration to just one time only and script gets lot simpler and clean.\ndef... | [
0
] | [
"As written, I don't think your code runs. words is a list, and .replace is not a valid list method.\n\nTo simply get the counts, see this code\nFor punctuation refer - Best way to strip punctuation from a string\nFor counting, use a Counter\nimport string\nfrom collections import Counter\n\nuninteresting_words = ... | [
-1
] | [
"dictionary",
"list",
"python"
] | stackoverflow_0069095682_dictionary_list_python.txt |
Q:
Re-assigning Sets in Pyomo Models
Hello I am new to Pyomo and modelling technique.
I was curious to know whether it is possible to reassign sets in the case when we continuously want to re-solve a model. For example:
model = pyo.ConcreteModel()
model.m = pyo.Set(initialize=get_numbers())
In the example, get_numbe... | Re-assigning Sets in Pyomo Models | Hello I am new to Pyomo and modelling technique.
I was curious to know whether it is possible to reassign sets in the case when we continuously want to re-solve a model. For example:
model = pyo.ConcreteModel()
model.m = pyo.Set(initialize=get_numbers())
In the example, get_numbers() feeds a different set every time I... | [
"Well, \"dynamically\" could mean a few different things here. Anytime you reassign the model variable to a new model, you make a new model, so there are several ways to do that. Here are a few. Both of these produce 3 independent models using the differing input values for the set S. Both methods produce the s... | [
0
] | [] | [] | [
"pyomo",
"python"
] | stackoverflow_0074379347_pyomo_python.txt |
Q:
Using the Kramers-Kronig (Hilbert) transform in Python via scipy or sympy
I am trying to use the Kramers-Kronig algorithm to transform the real and imaginary contributions to the anomalous scattering factor from a diffraction anomalous fine structure (DAFS) experiment.
I have fit a smooth curve to my experimental ... | Using the Kramers-Kronig (Hilbert) transform in Python via scipy or sympy | I am trying to use the Kramers-Kronig algorithm to transform the real and imaginary contributions to the anomalous scattering factor from a diffraction anomalous fine structure (DAFS) experiment.
I have fit a smooth curve to my experimental data using the lmfit package, and the following function:
`def intensity(en, ph... | [
"Yeah, this is maybe a little off-point for Stackoverflow, but for resonant X-ray scattering (including DAFS) in particular and other cases in optics where one might need to do a KK transform for a signal that might be a small change (your chi - a perturbation) from a larger signal, one can use a Differential KK tr... | [
0
] | [] | [] | [
"lmfit",
"numerical_integration",
"python",
"scipy",
"sympy"
] | stackoverflow_0074395360_lmfit_numerical_integration_python_scipy_sympy.txt |
Q:
'float' object is not subscriptable - not sure why
I have the following code. I am trying to select the 4th (index) item from a list at a given index location of the dataframe 'df'.
trialoutcomes = []
for j in range(0,len(df.columns)):
for i in range(5,len(df)):
trialoutcome = df.loc[i,j]
tria... | 'float' object is not subscriptable - not sure why | I have the following code. I am trying to select the 4th (index) item from a list at a given index location of the dataframe 'df'.
trialoutcomes = []
for j in range(0,len(df.columns)):
for i in range(5,len(df)):
trialoutcome = df.loc[i,j]
trialoutcomes.append(trialoutcome[4])
However, I keep getti... | [
"i think your data contain nans:\na=['trial', '2:7|2:8|4:1|4:2|8:3|8:4|', '4:7', '4:7', 'fullMiss', '5.828', '11', '37', '66']\n\nprint(a[4]) #fullMiss\n\na=np.nan\nprint(a[4]) #TypeError: 'float' object is not subscriptable\n\nyou can drop nans or you can add a control in loop:\nfor j in range(0,len(df.columns)):\... | [
1,
0
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074416265_dataframe_jupyter_notebook_pandas_python.txt |
Q:
How to return counting of first N natural numbers using while loop
I need to return the count of first N natural numbers using a while loop.
My code is:
def count_until(seconds):
cnt=seconds
while(cnt):
cnt-=1
return str(cnt)
print(count_until(10))
It is returning 9
but I want the result ... | How to return counting of first N natural numbers using while loop | I need to return the count of first N natural numbers using a while loop.
My code is:
def count_until(seconds):
cnt=seconds
while(cnt):
cnt-=1
return str(cnt)
print(count_until(10))
It is returning 9
but I want the result to be like this: 9 8 7 6 5 4 3 2 1
My other similar code with a print st... | [
"Don't return the count instead append it to string and output it\ndef count_until(seconds):\n cnt=seconds\n out = \"\"\n while(cnt-1):\n cnt-=1\n out+=\" \" + str(cnt)\n return out\n\nprint(count_until(10))\n\n",
"Does this solve the problem ?\ndef count_until(seconds):\n s=\"\"\n ... | [
1,
0,
0
] | [] | [] | [
"python",
"return",
"while_loop"
] | stackoverflow_0074416496_python_return_while_loop.txt |
Q:
"Business is not iterable" error returning data on same HTML page as form
I can get data from the form into database and pass that to the view where it queries Yelp and puts it into a JSON file, then particular fields from the JSON file are saved to database. But I can't display the database data.
I get the search... | "Business is not iterable" error returning data on same HTML page as form | I can get data from the form into database and pass that to the view where it queries Yelp and puts it into a JSON file, then particular fields from the JSON file are saved to database. But I can't display the database data.
I get the search success message when I should be returning the data to the page. I found my di... | [
"Problem\nI think the bottom line is that your first instinct that the page yelp.html was being overwritten was correct. Your yelping returns render(request, 'app/yelp.html'), which has no data in it, because no context has been given to it. Now this view function first calls yelp_main(request), which also return... | [
1
] | [] | [] | [
"django",
"python",
"sqlite"
] | stackoverflow_0074404979_django_python_sqlite.txt |
Q:
Turning on debug output for python 3 urllib
In python 2, it was possible to get debug output from urllib by doing
import httplib
import urllib
httplib.HTTPConnection.debuglevel = 1
response = urllib.urlopen('http://example.com').read()
However, in python 3 it looks like this has been moved to
http.client.HTTPCon... | Turning on debug output for python 3 urllib | In python 2, it was possible to get debug output from urllib by doing
import httplib
import urllib
httplib.HTTPConnection.debuglevel = 1
response = urllib.urlopen('http://example.com').read()
However, in python 3 it looks like this has been moved to
http.client.HTTPConnection.set_debuglevel(level)
However, I'm using... | [
"You were right the first time. You can simply add the line http.client.HTTPConnection.debuglevel = 1 at the start of your file to turn on HTTP debugging application-wide. urllib.request still uses http.client.\nIt seems that there's also a way to set the debuglevel for a single handler (by creating urllib.request.... | [
20,
0
] | [] | [] | [
"debugging",
"http",
"python",
"python_3.x",
"urllib"
] | stackoverflow_0000789856_debugging_http_python_python_3.x_urllib.txt |
Q:
How to access a list from other class in python -- AttributeError: type object 'A' has no attribute 'lst1'
I want to access a list from Class A in Class B
class A:
def __init__(self):
self.lst1 = [1,2,3]
class B:
def __init__(self):
self.lst2 = A.lst1
def printLst(self):
print(self.lst2)
b =... | How to access a list from other class in python -- AttributeError: type object 'A' has no attribute 'lst1' | I want to access a list from Class A in Class B
class A:
def __init__(self):
self.lst1 = [1,2,3]
class B:
def __init__(self):
self.lst2 = A.lst1
def printLst(self):
print(self.lst2)
b = B()
b.printLst()
I want to show that
b.printLst() -- [1,2,3]
What I get now:
AttributeError: type object 'A' ... | [
"The problem you are having is that you are confusing a static attribute with an object attribute. When you define the list on the A class, you are stating that when you create an A object, it will have the \"lst1\" attribute. This means that the class A do not have the list, but an object of type A does.\nThere ar... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074416533_python.txt |
Q:
python 3 urllib and http.client - unable to turn on debug messages
Hi Stackoverflow community,
I'm trying to get familiar with the urllib.request standard library and use it in my scripts at work instead of wget.
I'm however unable to get the detailed HTTP messages displayed neither in IDLE nor using script file o... | python 3 urllib and http.client - unable to turn on debug messages | Hi Stackoverflow community,
I'm trying to get familiar with the urllib.request standard library and use it in my scripts at work instead of wget.
I'm however unable to get the detailed HTTP messages displayed neither in IDLE nor using script file or manually typing the commandy into cmd (py).
I'm using Python on Window... | [
"The example in the issue you linked shows the working code, a version reproduced below:\nimport urllib.request\n\nhandler = urllib.request.HTTPHandler(debuglevel=10)\nopener = urllib.request.build_opener(handler)\ncontent = opener.open('http://stackoverflow.com').read()\n\nprint(content[0:120])\n\nThis is pretty c... | [
1,
0
] | [] | [] | [
"debugging",
"python",
"python_3.x",
"urllib"
] | stackoverflow_0042876579_debugging_python_python_3.x_urllib.txt |
Q:
append dictionary to data frame
I have a function, which returns a dictionary like this:
{'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116}
I am trying to append this dictionary to a dataframe like so:
ou... | append dictionary to data frame | I have a function, which returns a dictionary like this:
{'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116}
I am trying to append this dictionary to a dataframe like so:
output = pd.DataFrame()
output.append(d... | [
"You don't assign the value to the result.\noutput = pd.DataFrame()\noutput = output.append(dictionary, ignore_index=True)\nprint(output.head())\n\n",
"The previous answer (user alex, answered Aug 9 2018 at 20:09) now triggers a warning saying that appending to a dataframe will be deprecated in a future version.\... | [
205,
69,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0051774826_dataframe_pandas_python_python_3.x.txt |
Q:
How to split text into separate lines?
I have this text and i need to split it into separate lines:
text = """
| Post code | Cost, thousands USD |
|-----------+----------------------|
| 33022 | 0.543 |
| 33145 | 9563.214 |
| 33658 | 85.543 |
| 33854 | ... | How to split text into separate lines? | I have this text and i need to split it into separate lines:
text = """
| Post code | Cost, thousands USD |
|-----------+----------------------|
| 33022 | 0.543 |
| 33145 | 9563.214 |
| 33658 | 85.543 |
| 33854 | 0.010 |
| 33698 | 100... | [
"My approach would be to split this string by \"\\n\" and to reference only the lines where are the values and split them by \"|\", removing additional spaces to add each item in a tuple.\ntext = \"\"\"\n| Post code | Cost, thousands USD |\n|-----------+----------------------|\n| 33022 | 0.543 |... | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074416449_python_string.txt |
Q:
NameError in part of code for resizing image
I keep getting the name error repeatedly, though I do not understand what I should do further please help
Edit: code before error part
so when i remove these four lines, the error is resolved, what was the problem?
A:
Several of the variables you're using aren't there... | NameError in part of code for resizing image |
I keep getting the name error repeatedly, though I do not understand what I should do further please help
Edit: code before error part
so when i remove these four lines, the error is resolved, what was the problem?
| [
"Several of the variables you're using aren't there. Make sure you've run all the previous cells of the notebook in order. If you've copied this specific bit of code from somewhere, you probably need to copy some more context along with it\n",
"Check the variables here, many of them aren’t defined so please reche... | [
1,
0
] | [] | [] | [
"nameerror",
"python"
] | stackoverflow_0074416686_nameerror_python.txt |
Q:
Replace 500 random elements in an array from 0 to 1
Numpy: Replace 500 random elements in an array from 0 to 1
import numpy as np
import random
# 2D Grid world of 100 x 100 cells
arr = np.zeros((100,100))
# Arbitrarily change 500 elements from 0 to 1
for
A:
You can select 500 random unique numbers between 0 ... | Replace 500 random elements in an array from 0 to 1 | Numpy: Replace 500 random elements in an array from 0 to 1
import numpy as np
import random
# 2D Grid world of 100 x 100 cells
arr = np.zeros((100,100))
# Arbitrarily change 500 elements from 0 to 1
for
| [
"You can select 500 random unique numbers between 0 and 100*100 to index your array as 1D and assign 1:\nimport numpy as np\n\n# 2D Grid world of 100 x 100 cells\narr = np.zeros((100,100))\n\narr.flat[np.random.choice(np.arange(arr.size), 500, replace=False)] = 1\n\nExample with 10 random 1s in a 10x10 array:\narr ... | [
2
] | [] | [] | [
"numpy",
"python",
"random"
] | stackoverflow_0074416604_numpy_python_random.txt |
Q:
transform a list into rown in pandas dataframe
I recuperated my data from TMDB and i've reached to a dataframe that contains:
id (tmdb movie id), nameperson(nameof the each member of the cast), knownfor (movies they participated) and popularity (for each of the ppl).
i've reached at this point
My issue is that aft... | transform a list into rown in pandas dataframe | I recuperated my data from TMDB and i've reached to a dataframe that contains:
id (tmdb movie id), nameperson(nameof the each member of the cast), knownfor (movies they participated) and popularity (for each of the ppl).
i've reached at this point
My issue is that after the explodes, i arrived at the point where i have... | [
"You can apply pandas.Series constructor with pandas.Series.explode\nto explode all the columns that hold a list.\nTry this :\nout = df.set_index('id').apply(pd.Series.explode).reset_index()\n\nout.columns= out.columns.str.replace(r\"\\d+\", \"\", regex=True) #to get rid of the suffix number\n\nOutput :\nprint(out.... | [
1
] | [] | [] | [
"dataframe",
"explode",
"pandas",
"pandas_explode",
"python"
] | stackoverflow_0074416544_dataframe_explode_pandas_pandas_explode_python.txt |
Q:
Python Django: getting data from modal gives error
I'm trying to get a value from a modal, that gets the value using jQuery from a list.
Let's explain.
I have a list of objects in an HTML page using a for loop, and in each row, there is a delete button.
This delete button launches a confirmation Modal.
To get the... | Python Django: getting data from modal gives error | I'm trying to get a value from a modal, that gets the value using jQuery from a list.
Let's explain.
I have a list of objects in an HTML page using a for loop, and in each row, there is a delete button.
This delete button launches a confirmation Modal.
To get the id of the row and use it in the Modal, I use jQuery:
{% ... | [
"I could see one mistake, you defined name two times in hidden input field inside form tag of Html, and also you haven't provided any value attribute, and you should also use @require_POST decorator on the view. By looking at jQuery code it seems following will be the right code try it.\nTemplate file:\n{% for a in... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"jquery",
"python"
] | stackoverflow_0074409505_django_django_forms_django_templates_jquery_python.txt |
Q:
How to apply a function on pandas dataframe column
I have a pandas dataframe like this, with user_id, title of the song listened by the user and the number of times that a specific user has listened to that song (listen_count).
Goal to achieve:
I'm new to python and pandas and I'm trying to build a recommender sy... | How to apply a function on pandas dataframe column | I have a pandas dataframe like this, with user_id, title of the song listened by the user and the number of times that a specific user has listened to that song (listen_count).
Goal to achieve:
I'm new to python and pandas and I'm trying to build a recommender system. I want to transform these implicit feedbacks (list... | [
"You should be able to solve this problem by using DataFrame.groupby(). Assuming that your dataframe is called df, you can try the following(it's hard for me to check if it produces the right result without the data).\n# get the total listen count for each user_id\ndf['total_listen_count_per_user'] = df.groupby('us... | [
0
] | [] | [] | [
"collaborative_filtering",
"pandas",
"python",
"python_3.x",
"recommendation_engine"
] | stackoverflow_0074416522_collaborative_filtering_pandas_python_python_3.x_recommendation_engine.txt |
Q:
How to handle symbols in Python?
How can I regroup all the symbols like "!@#$%^&*()_+[]{}'\"|./?><" and use them, if the variable contains the symbols it will return False?
I'm trying to create a code for the password, and if the password contains only symbols like "!@#$%^&*()_+[]{}'\"|./?><", return False.
A:
I... | How to handle symbols in Python? | How can I regroup all the symbols like "!@#$%^&*()_+[]{}'\"|./?><" and use them, if the variable contains the symbols it will return False?
I'm trying to create a code for the password, and if the password contains only symbols like "!@#$%^&*()_+[]{}'\"|./?><", return False.
| [
"If you're interested in checking that a string s consists only of symbols from t = \"!@#$%^&*()_+[]{}'\\\"|./?><\", then you can do something like:\nt = set(t)\n\nall(c in t for c in s) # This will be True if s consists only of symbols from t\n\nEDIT: Improved the code according to @rioV8 's comment\n",
"Here's... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074416689_python.txt |
Q:
How to query bytearray data in pandas dataframe using duckdb?
df_image : is a pandas data frame with a column labelled 'bytes', which contains image data in bytearray format.
I display the images as follows:
[display(Image(copy.copy(BytesIO(x)).read(),width=300,height=170)) for x in df_image['bytes']]
Now I try a... | How to query bytearray data in pandas dataframe using duckdb? | df_image : is a pandas data frame with a column labelled 'bytes', which contains image data in bytearray format.
I display the images as follows:
[display(Image(copy.copy(BytesIO(x)).read(),width=300,height=170)) for x in df_image['bytes']]
Now I try a different method:
c = duckdb.query(
"select a.bytes \
from... | [
"There's no need to use BytesIO, Pandas Series already contains byte array objects. For example:\nimport duckdb\nfrom IPython.display import Image, display\n\nwith open('image.png', 'rb') as f:\n data = f.read()\n \ncon = duckdb.connect()\ncon.execute(\"create table test (b blob)\")\nrel = con.table(\"test\")... | [
1
] | [] | [] | [
"arrays",
"bytesio",
"duckdb",
"pandas",
"python"
] | stackoverflow_0073457316_arrays_bytesio_duckdb_pandas_python.txt |
Q:
python daemon, won't run when called from console script
I'm using the python-daemon package to create a daemon.
Here is a sample of what I'm doing:
def main():
import daemon
import os
here = os.path.dirname(os.path.abspath(__file__))
out = open("debug.log", "w+")
with daemon.DaemonContext(wo... | python daemon, won't run when called from console script | I'm using the python-daemon package to create a daemon.
Here is a sample of what I'm doing:
def main():
import daemon
import os
here = os.path.dirname(os.path.abspath(__file__))
out = open("debug.log", "w+")
with daemon.DaemonContext(working_directory=here, stdout=out):
import asyncio
... | [
"As mentioned in one of the comments, this approach is old and there are better ways to do it. I've since moved to using a process supervisor and all is well.\nThis still bugged me though.\nAfter doing a bit more research, I found the culprit.\nloop = asyncio.get_event_loop()\n\nI changed this to:\nloop = asyncio.n... | [
0
] | [] | [] | [
"python",
"python_daemon",
"python_poetry"
] | stackoverflow_0074409206_python_python_daemon_python_poetry.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'strip' how to solve?
Hello i cant figure out why i get this error :/
full code:
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(... | AttributeError: 'NoneType' object has no attribute 'strip' how to solve? | Hello i cant figure out why i get this error :/
full code:
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message... | [
"I solved it like this\n\nInstall \"pip install python-dotenv\"\nPut this in your code:\n\nfrom dotenv import load_dotenv\nload_dotenv(os.path.join(os.getcwd(), '.env'))\nSECRET_KEY = os.getenv(\"TOKEN\")\nclient.run(SECRET_KEY)\n\n",
"I added strip() to the wrong method (.append() instead of the str())\ningredie... | [
0,
0
] | [] | [] | [
"api",
"bots",
"discord",
"python",
"strip"
] | stackoverflow_0065505508_api_bots_discord_python_strip.txt |
Q:
How to solve KeyError in discord.py?
I'm making a warn command in discord.py аnd the program responds to me:
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\ivanb\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await... | How to solve KeyError in discord.py? | I'm making a warn command in discord.py аnd the program responds to me:
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\ivanb\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, *kwargs)
File "C:\Users\iva... | [
"Short answer: warns.setdefault(str(member.guild.name), {})[str(member.id)] = 0.\nEssentially, your statement has to dictionary element accesses. The second is a __setitem__ -- it assigns a value to a key. But the first one is a __getitem__ that is supposed to get the value (happening to be another dict) by the key... | [
0,
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074416751_discord.py_python.txt |
Q:
How to upload a file in Jira Issue using python?
I need to upload a file to jira issue using python and attach the file in a particular comment.
jira.add_attachment(issue=issue, attachment='inputFile.xlsx')
# read and upload a file (note binary mode for opening, it's important):
with open('inputFile.xlsx', 'rb') ... | How to upload a file in Jira Issue using python? | I need to upload a file to jira issue using python and attach the file in a particular comment.
jira.add_attachment(issue=issue, attachment='inputFile.xlsx')
# read and upload a file (note binary mode for opening, it's important):
with open('inputFile.xlsx', 'rb') as f:
jira.add_attachment(issue=issue, attachment=... | [
"The attachment.write(data) part of the example assumes you have a variable called data that points to a string. That part of the example is intended to show how you would upload an attachment when you don't already have a file containing the data that you want to attach to the issue. It would be given the name c... | [
1
] | [] | [] | [
"jira",
"python"
] | stackoverflow_0074414036_jira_python.txt |
Q:
Untar gzip to different directories
I have a .tar.gz file which may have the following files:
folder1/folder2/folder3/imp_folder1/file11.jpg
folder1/folder2/folder3/imp_folder1/file12.jpg
folder1/folder2/folder3/imp_folder2/file21.jpg
folder1/folder2/folder3/imp_folder3/file31.jpg
...
...
I want to untar it to th... | Untar gzip to different directories | I have a .tar.gz file which may have the following files:
folder1/folder2/folder3/imp_folder1/file11.jpg
folder1/folder2/folder3/imp_folder1/file12.jpg
folder1/folder2/folder3/imp_folder2/file21.jpg
folder1/folder2/folder3/imp_folder3/file31.jpg
...
...
I want to untar it to the following directories:
/new_folder1/new... | [
"You need to use the --transform option for tar. This posting discussed the usage of that option for a similar problem.\nHere is a demo of the option's usage:\n#!/bin/sh\n\n### Create test data\nTESTDIR=\"TEST_2\"\n\nmkdir \"${TESTDIR}\"\nfor i in ab DF jkL\ndo\n echo \"${i}\" >\"${TESTDIR}/testFile_${i}.txt\"\... | [
0
] | [] | [] | [
"python",
"tar",
"tarfile"
] | stackoverflow_0074303422_python_tar_tarfile.txt |
Q:
Filter a dataframe using values from a dict
I have a dataframe DF, I want to filter rows based on values on a dictionary
fruits = {'BN':'Banana', 'LM': 'Lemon', 'AP':'Apple', 'MG': 'Mango'}
I tried the following, but it didn't work
df = df.loc[df['FruitName'] in fruits.values()]
I get the following error:
ValueE... | Filter a dataframe using values from a dict | I have a dataframe DF, I want to filter rows based on values on a dictionary
fruits = {'BN':'Banana', 'LM': 'Lemon', 'AP':'Apple', 'MG': 'Mango'}
I tried the following, but it didn't work
df = df.loc[df['FruitName'] in fruits.values()]
I get the following error:
ValueError: The truth value of a Series is ambiguous. U... | [
"You can use .isin():\ndf = df[df[\"FruitName\"].isin(fruits.values())]\nprint(df)\n\nPrints:\n FruitName\n0 Lemon\n2 Mango\n\n\nDataframe used:\n FruitName\n0 Lemon\n1 Grapefruit\n2 Mango\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"dictionary",
"lines_of_code",
"pandas",
"python"
] | stackoverflow_0074416855_dataframe_dictionary_lines_of_code_pandas_python.txt |
Q:
Creating a Dataframe in for loop pythin from list and list of sublists
can anybody help me to create a Dataframe in python with for loop: I want to create a Dataframe from two lists:
list1 and list of lists (list2) where the length of list1 = the number of sublists in list2:
an example:
list1= ["A", "B", "C", "D"]... | Creating a Dataframe in for loop pythin from list and list of sublists | can anybody help me to create a Dataframe in python with for loop: I want to create a Dataframe from two lists:
list1 and list of lists (list2) where the length of list1 = the number of sublists in list2:
an example:
list1= ["A", "B", "C", "D"]
list2= [[1, 2, 3, 4], [1, 3, 4, 6, 7], [2, 3, 4, 5, 6], [2, 4, 5, 7, 8]]=>
... | [
"Try:\nlist1 = [\"A\", \"B\", \"C\", \"D\"]\nlist2 = [[1, 2, 3, 4], [1, 3, 4, 6, 7], [2, 3, 4, 5, 6], [2, 4, 5, 7, 8]]\n\ndf = pd.DataFrame(zip(list1, list2), columns=[\"Col1\", \"Col2\"]).explode(\"Col2\")\nprint(df)\n\nPrints:\n Col1 Col2\n0 A 1\n0 A 2\n0 A 3\n0 A 4\n1 B 1\n1 B ... | [
1,
1,
0
] | [] | [] | [
"dataframe",
"for_loop",
"list",
"python"
] | stackoverflow_0074416770_dataframe_for_loop_list_python.txt |
Q:
How to write a function/procedure that multiply 2 natural numbers without * operator?
So I was given a computer science problem to write a function which accepts two natural numbers and returns their product. The rules are that I am only allowed to use the addition of 1 (variable + 1), assigning and comparison ope... | How to write a function/procedure that multiply 2 natural numbers without * operator? | So I was given a computer science problem to write a function which accepts two natural numbers and returns their product. The rules are that I am only allowed to use the addition of 1 (variable + 1), assigning and comparison operation. I end up with this code in python:
def multiplication_of_ab(a, b):
placeholder ... | [
"You can use a nested loop:\ndef multiply(a, b):\n c = 0\n for i in range(a):\n for j in range(b):\n c += 1\n return c\n\n",
"Since it says \"only comparisons\", I assume that range is not allowed - fortunately, you can do the same thing with a while loop. (I guess while loops are allow... | [
1,
0
] | [] | [] | [
"multiplication",
"python"
] | stackoverflow_0074416494_multiplication_python.txt |
Q:
getting the Length of all lists in a dictionary
listdict = {
'list_1' : ['1'],
'list_2' : ['1','2'],
'list_3' : ['2'],
'list_4' : ['1', '2', '3', '4']
}
print(len(listdict))
This is my code for example. I want it to print:
8
I have tried length as u can see but it prints 4 of course the amount of li... | getting the Length of all lists in a dictionary | listdict = {
'list_1' : ['1'],
'list_2' : ['1','2'],
'list_3' : ['2'],
'list_4' : ['1', '2', '3', '4']
}
print(len(listdict))
This is my code for example. I want it to print:
8
I have tried length as u can see but it prints 4 of course the amount of lists but I want it to print
the amount of items in th... | [
"You have 4 lists as values in your dictionary, so you have to sum the lengths:\nprint(sum(map(len, listdict.values())))\n\nPrints:\n8\n\n",
"Consider utilizing another inbuilt function sum (len is a built in function):\n>>> listdict = {\n... 'list_1' : ['1'],\n... 'list_2' : ['1','2'],\n... 'list_3' : ['2'... | [
1,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074416862_dictionary_list_python.txt |
Q:
How can I turn this into a DataFrame?
I am new to Python, and was trying to run a basic web scraper. My code looks like this
import requests
import pandas as pd
x = requests.get('https://www.baseball-reference.com/players/p/penaje02.shtml')
dfs = pd.read_html(x.content)
print(dfs)
df = pd.DataFrame(dfs)
when... | How can I turn this into a DataFrame? | I am new to Python, and was trying to run a basic web scraper. My code looks like this
import requests
import pandas as pd
x = requests.get('https://www.baseball-reference.com/players/p/penaje02.shtml')
dfs = pd.read_html(x.content)
print(dfs)
df = pd.DataFrame(dfs)
when printing dfs it looks like this. I only wa... | [
"What do you mean you only want the second table? There's only one table, it's 6 rows and 30 columns. The backslashes show up when whatever you're trying to print to isn't wide enough to contain the dataframe without line wrapping. Here's the dataframe printed in a wider terminal:\n\nThe pd.read_html() function ret... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074416858_dataframe_pandas_python.txt |
Q:
Getting the target of a symbolic link with pathlib
Is there a way to get the target of a symbolic link using pathlib? I know that this can be done using os.readlink().
I want to create a dictionary composed by links and their target files.
links = [link for link in root.rglob('*') if link.is_symlink()]
files = [Pa... | Getting the target of a symbolic link with pathlib | Is there a way to get the target of a symbolic link using pathlib? I know that this can be done using os.readlink().
I want to create a dictionary composed by links and their target files.
links = [link for link in root.rglob('*') if link.is_symlink()]
files = [Path(os.readlink(str(pointed_file))) for pointed_file in l... | [
"Update: Python 3.9 introduced Path.readlink() method, so explanations below apply to earlier releases only.\nNope, it's currently not possible to get the results from pathlib that os.readlink() gives. Path.resolve() doesn't work for broken links and either raises FileNotFoundError (Python <3.5) or returns potentia... | [
17,
1
] | [] | [] | [
"pathlib",
"python",
"python_3.x",
"symlink"
] | stackoverflow_0041460434_pathlib_python_python_3.x_symlink.txt |
Q:
list to dictionary conversion with multiple values per key?
I have a Python list which holds pairs of key/value:
l = [[1, 'A'], [1, 'B'], [2, 'C']]
I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple:
{1: ('A', 'B'), 2: ('C',)}
The iterative solution is tr... | list to dictionary conversion with multiple values per key? | I have a Python list which holds pairs of key/value:
l = [[1, 'A'], [1, 'B'], [2, 'C']]
I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple:
{1: ('A', 'B'), 2: ('C',)}
The iterative solution is trivial:
l = [[1, 'A'], [1, 'B'], [2, 'C']]
d = {}
for pair in l:
... | [
"from collections import defaultdict\n\nd1 = defaultdict(list)\n\nfor k, v in l:\n d1[k].append(v)\n\nd = dict((k, tuple(v)) for k, v in d1.items())\n\nd contains now {1: ('A', 'B'), 2: ('C',)}\nd1 is a temporary defaultdict with lists as values, which will be converted to tuples in the last line. This way you a... | [
55,
17,
10,
3,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"type_conversion"
] | stackoverflow_0005378231_dictionary_list_python_type_conversion.txt |
Q:
Python - Fill in form on website when Outlook appointment is created
I am looking for a way to automate the below scenario for free. I considered Zapier but the webhook is a premium feature (=not free)
Is the following scenario possible by using Python?
If so, can you please advise how to get started and what I wo... | Python - Fill in form on website when Outlook appointment is created | I am looking for a way to automate the below scenario for free. I considered Zapier but the webhook is a premium feature (=not free)
Is the following scenario possible by using Python?
If so, can you please advise how to get started and what I would need to make it happen as a beginner?
Scenario/requirements:
User cre... | [
"Sounds like a subject for an Outlook add-in where you could subscribe to the PropertyChange event of Outlook items. The event is fired when an explicit built-in property (for example, Subject) of the object is changed. See Walkthrough: Create your first VSTO Add-in for Outlook to get started quickly.\nPython is no... | [
0
] | [] | [] | [
"outlook",
"python"
] | stackoverflow_0074391741_outlook_python.txt |
Q:
How can I extend a built-in type in cython?
I'm trying to extend the basic float in python with cython additional methods. I have a python implementation and I know I could create my own extended type by keeping an internal float value. But I'm trying to keep the same code base for interpreted and compiled code us... | How can I extend a built-in type in cython? | I'm trying to extend the basic float in python with cython additional methods. I have a python implementation and I know I could create my own extended type by keeping an internal float value. But I'm trying to keep the same code base for interpreted and compiled code using the benefits of pure python mode.
So how can ... | [
"from the open issue on the problem support __new__() in extension types https://github.com/cython/cython/issues/799\nit seems you cannot use the __new__ method in a cdef class, and have to use it in a wrapper python class.\nimport cython\n\n@cython.cclass\nclass _Bearing(float):\n def __add__(self: Bearing, oth... | [
1
] | [] | [] | [
"built_in_types",
"cython",
"python",
"subclass"
] | stackoverflow_0074416698_built_in_types_cython_python_subclass.txt |
Q:
Include the track changes in word using python
I am trying to extract some part of a document and put it into a table in Excel. So far so good, I was able to do it.
However, when I change something in the text with "track changes" in word the python code does not include that changes. I want to have the track chan... | Include the track changes in word using python | I am trying to extract some part of a document and put it into a table in Excel. So far so good, I was able to do it.
However, when I change something in the text with "track changes" in word the python code does not include that changes. I want to have the track changes visible in the table as well.
Here how it works ... | [
"You can use the TrackRevisions property of the Document class from the Word object model:\n'Turn on Track Changes\nWordApplication.ActiveDocument.TrackRevisions = True\n\nAnd you may turn them off:\n'Turn off Track Changes\nWordApplication.ActiveDocument.TrackRevisions = False\n\n"
] | [
0
] | [] | [] | [
"excel",
"ms_word",
"office_automation",
"python"
] | stackoverflow_0074387328_excel_ms_word_office_automation_python.txt |
Q:
How to transmit Android real-time sensor data to computer?
I wish to transmit real-time sensor data collected by Android smartphone to my computer and do the signal process on my computer. How may I achieve that? Any helpful links to tutorials are very well welcomed.
Either by wireless means or USB cables is accep... | How to transmit Android real-time sensor data to computer? | I wish to transmit real-time sensor data collected by Android smartphone to my computer and do the signal process on my computer. How may I achieve that? Any helpful links to tutorials are very well welcomed.
Either by wireless means or USB cables is acceptable.
When the data are transmitted, how may the computer proce... | [
"Some Android apps allow you to share the sensors via the network:\n\nPhonePi (using websockets)\nSensor Node (via MQTT)\nIP Webcam (can be used as a webapi by accessing http://SMARTPHONE_IP:8080/sensors.json)\nTasker publisher\n\nYou can also read the sensors via ADB!\n",
"There exist multiple Android apps to tr... | [
10,
5,
4,
1,
0
] | [] | [] | [
"android",
"data_transfer",
"python",
"transmission"
] | stackoverflow_0018245849_android_data_transfer_python_transmission.txt |
Q:
attributeerror: 'list' object has no attribute 'send_keys'. How do fix this?
I want to make automated login to router web GUI, but if I use
input_tags.send_keys("PASSWORD"), then I get error
AttributeError: 'list' object has no attribute 'send_keys'.
Here is my code example
#imports
import time
from selenium imp... | attributeerror: 'list' object has no attribute 'send_keys'. How do fix this? | I want to make automated login to router web GUI, but if I use
input_tags.send_keys("PASSWORD"), then I get error
AttributeError: 'list' object has no attribute 'send_keys'.
Here is my code example
#imports
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
#login
driver = webdriv... | [
"driver.find_elements returns you a list of elements. If you're certain there's only a single element that satisfiers your criterion, you can just use:\npassword = driver.find_elements(By.ID, \"login_password\")[0]\n\n",
"In case there is only 1 element on that page having id = 'login_password' all you need to ma... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074416720_python_python_3.x_selenium_selenium_chromedriver_selenium_webdriver.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.