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 remove from QuerySet by some condition
I have a queryset, and lets say its described like this (in JSON)
{
[
{
"name": "Alex",
"01_correct_answers": 1,
"02_correct_answers": 3,
},
{
"name": "John",
"01_correct_answers": null,
"02_correct_answers": null,
... | How to remove from QuerySet by some condition | I have a queryset, and lets say its described like this (in JSON)
{
[
{
"name": "Alex",
"01_correct_answers": 1,
"02_correct_answers": 3,
},
{
"name": "John",
"01_correct_answers": null,
"02_correct_answers": null,
},
{
"name": "James",
"01_correct_... | [
"You can query with:\nsubjects = ['01', '02']\n\nnew_queryset = q.exclude(\n Q(*[(f'{sub}_correct_answers', None) for sub in subjects])\n)\n"
] | [
2
] | [] | [] | [
"django",
"django_orm",
"django_rest_framework",
"python"
] | stackoverflow_0074347662_django_django_orm_django_rest_framework_python.txt |
Q:
expected string or bytes-like object' in dictionary
I try to show the contents of a dictionary that has to return this output:
'Watermeloenen': 466, 'Appels': 688, 'Sinaasappels': 803
So I have this method:
def total_fruit_per_sort(self, file_content):
file_contents = self.extractingText.extract_text_... | expected string or bytes-like object' in dictionary | I try to show the contents of a dictionary that has to return this output:
'Watermeloenen': 466, 'Appels': 688, 'Sinaasappels': 803
So I have this method:
def total_fruit_per_sort(self, file_content):
file_contents = self.extractingText.extract_text_from_image(
file_content)
number_foun... | [
"Check that the result of\nfile_contents = self.extractingText.extract_text_from_image(file_content)\n\nis actually a string or bytes-like object. You'll get this error from re.findall(...) when the second parameter is not a string or bytes-like object. For example: re.findall(\"somestring\", None).\nWhen I run you... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074348189_python.txt |
Q:
installing dionysus on windows
I am trying to run this project in GitHub.
Everything seems good until I try to import this library:
dionysus by pip install dionysus, (in the file drawDiagram.ipynb) an error throw:
error: subprocess-exited-with-error
**× python setup.py bdist_wheel did not run successfully.
... | installing dionysus on windows | I am trying to run this project in GitHub.
Everything seems good until I try to import this library:
dionysus by pip install dionysus, (in the file drawDiagram.ipynb) an error throw:
error: subprocess-exited-with-error
**× python setup.py bdist_wheel did not run successfully.
│ exit code: 1
╰─> [73 lines of o... | [
"I don't know if this answers your question directly, but it may solve the problem.\nThe only solution I have been able to find is running it on windows subsystem for linux (WSL). Here are the steps I took:\n\nTurn on WSL in settings. This will require a restart.\nInstall ubunto. Can get from microsoft store.\nComm... | [
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0073848257_pip_python.txt |
Q:
How do i make extra items of a list to print at the end of the rest
I have this program which takes two lists as input from the user and then combines the two while alternating the items of each list. The thing is if one list is larger in length than the other i want it to print the rest of the items at the end of... | How do i make extra items of a list to print at the end of the rest | I have this program which takes two lists as input from the user and then combines the two while alternating the items of each list. The thing is if one list is larger in length than the other i want it to print the rest of the items at the end of the result. I apologize for the bad writing of this i am new to the site... | [
"itertools.zip_longest(*iterables, fillvalue=None)\n\nFrom the itertools docs\n\nMake an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.\n\n",
"You are loo... | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074348472_python_python_3.x.txt |
Q:
2D Elastic Collision, momentum not conserved in the y direction
I am a high school student trying to model a 2D Elastic Collision between two billiard balls. I used vector rotation as shown in this video and I also referenced this website as well. Despite that, the collisions weren't working specifically when the ... | 2D Elastic Collision, momentum not conserved in the y direction | I am a high school student trying to model a 2D Elastic Collision between two billiard balls. I used vector rotation as shown in this video and I also referenced this website as well. Despite that, the collisions weren't working specifically when the two balls collide having the same x value (a vertical collision).
As ... | [
"The problem with your code lies in the way you rotate back your velocities in your BallCollision function:\n#Rotate back\nv1x = v1x * cos(angle) - v1y * sin(angle)\nv1y = v1y * cos(angle) + v1x * sin(angle)\nv2x = v2x * cos(angle) - v2y * sin(angle)\nv2y = v2y * cos(angle) + v2x * sin(angle)\n\nIn these lines you ... | [
0
] | [] | [] | [
"game_physics",
"physics",
"python"
] | stackoverflow_0074319716_game_physics_physics_python.txt |
Q:
How to print a symmetrical grid in python (see example)
lst = ['40', '36', '112', 'Eric', '30', 'Bob', '15', '125', '45', 'Philippe']
d = []
things = 0
summ = 0
for val in lst:
try:
summ+= float(val)
things+= 1
except ValueError:
name = val
d.append((name, summ, things))
... | How to print a symmetrical grid in python (see example) | lst = ['40', '36', '112', 'Eric', '30', 'Bob', '15', '125', '45', 'Philippe']
d = []
things = 0
summ = 0
for val in lst:
try:
summ+= float(val)
things+= 1
except ValueError:
name = val
d.append((name, summ, things))
summ= 0
things= 0
print("Name total... | [
"I'd use a format-string and specify field widths and alignment to let Python automatically space things out for me, something like:\nfor name, value, nitems in d:\n print(f\"{name:10} {value:>10.2f} $ {nitems:>16}\")\n\ngiving:\nName total # items\nEric 188.00 $ 3\... | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074348603_list_python.txt |
Q:
How to Limit the content of the list when printed?
How can I fix the "input ==1:" on line 19 problem such that if i input "1" it must have an output of
A-C,2-C,3-C,4-C,5-C,6-C,7-C,8-C,9-C,10-C,J-C,Q-C,K-C
This is my trial and error code for this problem
from typing import List, Any
import random
def printmenu():... | How to Limit the content of the list when printed? | How can I fix the "input ==1:" on line 19 problem such that if i input "1" it must have an output of
A-C,2-C,3-C,4-C,5-C,6-C,7-C,8-C,9-C,10-C,J-C,Q-C,K-C
This is my trial and error code for this problem
from typing import List, Any
import random
def printmenu():
print("Menu")
print("1. Show first 13 cards")
... | [
"For the string value that you're looking for, you could do something like\ndeck = \",\".join(map(lambda x: x + '-C', value))\n\nwhere each suit will be concatenated with -C, then joined together into one string with each element separated by a comma.\n"
] | [
0
] | [] | [] | [
"card",
"poker",
"python"
] | stackoverflow_0074348325_card_poker_python.txt |
Q:
lda model corpus TypeError: '<' not supported between instances of 'int' and 'tuple'
I am trying to find the dominant topic in each article through following:
lda_model is the model, corpus consist of id2word.doc2bow(text), texts is text data on which model is applied.
def format_topics_sentences(ldamodel=lda_mode... | lda model corpus TypeError: '<' not supported between instances of 'int' and 'tuple' | I am trying to find the dominant topic in each article through following:
lda_model is the model, corpus consist of id2word.doc2bow(text), texts is text data on which model is applied.
def format_topics_sentences(ldamodel=lda_model, corpus=corpus, texts=data):
# Init output
sent_topics_df = pd.DataFrame()
... | [
"Your data is borked.\nReplacing ), with ),\\n, and adding some indentation manually, the first few lines of your input looks like this:\n(\n [\n (5, 0.28596485),\n (6, 0.16911359),\n (8, 0.030976538),\n (10, 0.011954311),\n (11, 0.068368636),\n (13, 0.34729925),\n ... | [
0
] | [] | [] | [
"lda",
"nlp",
"python",
"topic_modeling",
"typeerror"
] | stackoverflow_0074348227_lda_nlp_python_topic_modeling_typeerror.txt |
Q:
Tensorflow Lite Android Object Detection -- Mobile SSD models are expected to have exactly 4 outputs, found 8
PROBLEM ENCOUNTERED:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.tensorflow.lite.examples.detection, PID: 14719
java.lang.AssertionError: Error occurred when initializing ObjectDetector: Mobile S... | Tensorflow Lite Android Object Detection -- Mobile SSD models are expected to have exactly 4 outputs, found 8 | PROBLEM ENCOUNTERED:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.tensorflow.lite.examples.detection, PID: 14719
java.lang.AssertionError: Error occurred when initializing ObjectDetector: Mobile SSD models are expected to have exactly 4 outputs, found 8
Problem Description
Android Application Source: TensorF... | [
"After further study, I believe the aforementioned issue was raised since the model has 8 tensors output but the Android application written in Java can only support 4 tensors output (at least the example provided by Google only supports 4 tensors output)\nI am not very certain about the number of tensors output on... | [
2,
0
] | [] | [] | [
"android",
"java",
"python",
"tensorflow",
"tensorflow_lite"
] | stackoverflow_0066488745_android_java_python_tensorflow_tensorflow_lite.txt |
Q:
Vispy surface plot highlight particular section with color and image
Question 1: I am trying to highlight particular section from Vispy Surface Plot example in a particular colour somewhat similar to below modified image.
Question 2: Similarly I would like to add an image data as overlay texture to the Vispy surf... | Vispy surface plot highlight particular section with color and image | Question 1: I am trying to highlight particular section from Vispy Surface Plot example in a particular colour somewhat similar to below modified image.
Question 2: Similarly I would like to add an image data as overlay texture to the Vispy surface plot
Can SurfacePlotVisual be used for this?
I am unable to find any ... | [
"Answer 1\nThe set_data method of the SurfacePlotVisual takes an array of colors:\nhttps://github.com/vispy/vispy/blob/df6c6be9c5aa6a67abf7e3072780264886e2be77/vispy/visuals/surface_plot.py#L132-L151\nYou should be able to pass whatever colors you want to that as an RGBA array (MxNx4). Note these are colors for the... | [
1
] | [] | [] | [
"numpy",
"plot",
"python",
"surface",
"vispy"
] | stackoverflow_0074300215_numpy_plot_python_surface_vispy.txt |
Q:
Django does not create superuser using Custom User Model
I am creating a Django application and I am implementing a Custom User Model for authentication. I cannot create a superuser. I get an error saying RecursionError: maximum recursion depth exceeded while calling a Python object. I am using Django version 4.1.... | Django does not create superuser using Custom User Model | I am creating a Django application and I am implementing a Custom User Model for authentication. I cannot create a superuser. I get an error saying RecursionError: maximum recursion depth exceeded while calling a Python object. I am using Django version 4.1.2.
Here is my User Model
class CustomAccountManager(BaseUserMa... | [
"You are calling the function create_superuser recursively:\nclass CustomAccountManager(BaseUserManager):\n def create_superuser(self, user_name, email, first_name, last_name, phone, password, **other_fields):\n\n other_fields.setdefault('is_staff', True)\n other_fields.setdefault('is_superuser', T... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074348486_django_django_models_python.txt |
Q:
median downsampling in python
I would like to downsample an image using a median filter. The block_reduce method in skimage together with func=numpy.median seems to be appropriate at first sight. However, I got the impression that block_reduce applies the func one axis at a time, while I would expect the median fi... | median downsampling in python | I would like to downsample an image using a median filter. The block_reduce method in skimage together with func=numpy.median seems to be appropriate at first sight. However, I got the impression that block_reduce applies the func one axis at a time, while I would expect the median filter to be applied to the whole blo... | [
"Here is some hack which solves your specific issue.\ndef clever_func(block, axis):\n # axis unused on purpose\n if len(block.shape) == 4:\n return np.median(block, axis=[2, 3])\n else:\n return block\n\nactual = block_reduce(image, (2,2), func=clever_func)\n\nEssentially, the argument func t... | [
1,
0
] | [] | [] | [
"python",
"scikit_image"
] | stackoverflow_0050485458_python_scikit_image.txt |
Q:
selenium.common.exceptions.WebDriverException: Message: invalid session id using Selenium with ChromeDriver and Chrome through Python
I'm writing some code using Selenium, and at one point I make 7 requests, all to different websites. For the first one, this works fine. However, for others, I get a session ID erro... | selenium.common.exceptions.WebDriverException: Message: invalid session id using Selenium with ChromeDriver and Chrome through Python | I'm writing some code using Selenium, and at one point I make 7 requests, all to different websites. For the first one, this works fine. However, for others, I get a session ID error. I think that my browser is configured correctly, as I do get results from the first website. I have tried to put a WebDriverWait in betw... | [
"invalid session id\nThe invalid session ID error is a WebDriver error that occurs when the server does not recognize the unique session identifier. This happens if the session has been deleted or if the session ID is invalid.\nA WebDriver session can be deleted through either of the following ways:\n\nExplicit ses... | [
45,
3,
2,
1,
0,
0
] | [] | [] | [
"google_chrome",
"python",
"selenium",
"selenium_chromedriver",
"webdriver"
] | stackoverflow_0056483403_google_chrome_python_selenium_selenium_chromedriver_webdriver.txt |
Q:
Applying a function to each of the groups in groupby
I would like to apply a function to each of the groups in my .groupby result. My original df looks like this:
Id Cust_type DPP
1 A Detractor
2 B Detractor
3 C Detractor
4 D Promoter
5 A Promoter
6 ... | Applying a function to each of the groups in groupby | I would like to apply a function to each of the groups in my .groupby result. My original df looks like this:
Id Cust_type DPP
1 A Detractor
2 B Detractor
3 C Detractor
4 D Promoter
5 A Promoter
6 B Passive
7 B Detractor
8 C ... | [
"You have many syntax errors in your code.\nHere is a slightly simplified version:\ndef score(x):\n return (x['DPP'].eq('Promoter').sum()-x['DPP'].eq('Detractor').sum())/len(x)*100\n\ndf.groupby('Cust_type').apply(score)\n\nOr, as you use only a single column:\ndef score(x):\n return (x.eq('Promoter').sum()-x... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074348849_pandas_python.txt |
Q:
Group log statements per second
I wrote a logger to log some canbus values to a file, where the timestamp is in seconds. An example:
Timestamp, Can ID, data, datalength
07-Nov-22 13:40:41, 418385469, a00f325bffffffff, 8
07-Nov-22 13:40:41, 217056317, ffffff0000ffffff, 8
07-Nov-22 13:40:41, 486535229, 000000000000f... | Group log statements per second | I wrote a logger to log some canbus values to a file, where the timestamp is in seconds. An example:
Timestamp, Can ID, data, datalength
07-Nov-22 13:40:41, 418385469, a00f325bffffffff, 8
07-Nov-22 13:40:41, 217056317, ffffff0000ffffff, 8
07-Nov-22 13:40:41, 486535229, 000000000000ffff, 8
07-Nov-22 13:40:41, 217064509,... | [
"If you load the CSV into a dataframe df, then you can do:\ndf = df.pivot(index=\"Timestamp\", columns=\"Can ID\", values=\"data\").reset_index()\ndf.columns.name = None\n\nprint(df)\n\nPrints:\n Timestamp 217056317 217064509 418385469 486535229\n0 07-Nov-22 13:40:41 fff... | [
0
] | [] | [] | [
"dictionary",
"key",
"python",
"timestamp"
] | stackoverflow_0074348522_dictionary_key_python_timestamp.txt |
Q:
How to go from Python 3.10 to 3.9 in existing Jupiter Lab Environment
I recently upgrade python3 to 3.10 from 3.9 and it turns out that nbconvert doesn't work with 3.10 in Jupyter Lab. I already have an existing environment that needs to be downgraded back to 3.9 so that nbconvert works. Does anyone know how to do... | How to go from Python 3.10 to 3.9 in existing Jupiter Lab Environment | I recently upgrade python3 to 3.10 from 3.9 and it turns out that nbconvert doesn't work with 3.10 in Jupyter Lab. I already have an existing environment that needs to be downgraded back to 3.9 so that nbconvert works. Does anyone know how to do this? FYI I am on a Mac system
| [
"Depending on whether or not you used a virtual environment such as virtualenv, pipenv or similar, there are a few possibilities that come to mind:\n\ninstalling another Python version in parallel on your system (in your case python3.9). Then create a virtualenv / pipenv, whatever you prefer, with that specific pyt... | [
0
] | [] | [] | [
"nbconvert",
"python"
] | stackoverflow_0074348051_nbconvert_python.txt |
Q:
How to remove specific lines into one .csv?
Here is an example of the csv
17/10/2022 23:00;10
18/10/2022 00:00;10
19/10/2022 19:00;9
I want to remove specific rows depends on a date.
How would you do that?
Thank you so much.
I would like to do it as you introduce a range of dates, and it deletes everything out of... | How to remove specific lines into one .csv? | Here is an example of the csv
17/10/2022 23:00;10
18/10/2022 00:00;10
19/10/2022 19:00;9
I want to remove specific rows depends on a date.
How would you do that?
Thank you so much.
I would like to do it as you introduce a range of dates, and it deletes everything out of the range.
I havent tried it yet because i,m st... | [
"You as example.\ntmp = pd.DataFrame({'date':['16/10/2022 23:00','17/10/2022 23:00','18/10/2022 00:00'],'val':[6,12,10]})\ntmp[tmp['date']>'17/10/2022']\n\nIn this way you filter the dataframe by date value. I suggest before continuing to study the docs and learn the basics of python.\nFor example here there is the... | [
0,
0
] | [] | [] | [
"csv",
"python",
"row"
] | stackoverflow_0074347600_csv_python_row.txt |
Q:
TypeError: setup_module() got an unexpected keyword argument 'data'
May I please get assistance on this error as I've been trying but it returns a TypeError.
bank = setup_module(data = data, target = 'Creditability',
normalize = True, stage=None,
transformation = True,
... | TypeError: setup_module() got an unexpected keyword argument 'data' | May I please get assistance on this error as I've been trying but it returns a TypeError.
bank = setup_module(data = data, target = 'Creditability',
normalize = True, stage=None,
transformation = True,
train_size = 0.8, # training over 80% of available data
... | [
"The best route would be to look into the function \"setup_module\" and find out what the keyword argument for data is. For example, it might be \"dataset=\".\nYou can find this out by holding ctrl and clicking the function name to go directly to it's source code.\nIt is not recommended but you could also just remo... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074348821_python.txt |
Q:
Get the key corresponding to the minimum value within a dictionary
If I have a Python dictionary, how do I get the key to the entry which contains the minimum value?
I was thinking about something to do with the min() function...
Given the input:
{320:1, 321:0, 322:3}
It would return 321.
A:
Best: min(d, key=d.... | Get the key corresponding to the minimum value within a dictionary | If I have a Python dictionary, how do I get the key to the entry which contains the minimum value?
I was thinking about something to do with the min() function...
Given the input:
{320:1, 321:0, 322:3}
It would return 321.
| [
"Best: min(d, key=d.get) -- no reason to interpose a useless lambda indirection layer or extract items or keys!\n>>> d = {320: 1, 321: 0, 322: 3}\n>>> min(d, key=d.get)\n321\n\n",
"Here's an answer that actually gives the solution the OP asked for:\n>>> d = {320:1, 321:0, 322:3}\n>>> d.items()\n[(320, 1), (321, 0... | [
886,
74,
49,
14,
8,
8,
7,
4,
4,
4,
2,
2,
2,
2,
1,
0
] | [
"# python \nd={320:1, 321:0, 322:3}\nreduce(lambda x,y: x if d[x]<=d[y] else y, d.iterkeys())\n 321\n\n"
] | [
-1
] | [
"dictionary",
"idioms",
"min",
"minimum",
"python"
] | stackoverflow_0003282823_dictionary_idioms_min_minimum_python.txt |
Q:
Count consecutive row values but reset count with every 0 in row
within a data frame, I need to count and sum conescutive row values in column A into a new column, column B.
Starting with column A, the script would count the consecutive runs in 1s but when a 0 appears it prints the total count in column B, it then... | Count consecutive row values but reset count with every 0 in row | within a data frame, I need to count and sum conescutive row values in column A into a new column, column B.
Starting with column A, the script would count the consecutive runs in 1s but when a 0 appears it prints the total count in column B, it then resets the count and continues through the remaining data.
Desired ou... | [
"Here is one way to do it. However, I get the feeling that there might be better ways.. But you can try this for now:\n\nThe routine function is use to increment the counter variable until it encounters a value of 0 in the A column. At which point it grabs the total count, and then resets the counter variable.\nI u... | [
0,
0
] | [] | [] | [
"counting",
"cumulative_sum",
"finance",
"python",
"quantitative_finance"
] | stackoverflow_0074348572_counting_cumulative_sum_finance_python_quantitative_finance.txt |
Q:
Kernel Density Estimation using scipy's gaussian_kde and sklearn's KernelDensity leads to different results
I created some data from two superposed normal distributions and then applied sklearn.neighbors.KernelDensity and scipy.stats.gaussian_kde to estimate the density function. However, using the same bandwith (... | Kernel Density Estimation using scipy's gaussian_kde and sklearn's KernelDensity leads to different results | I created some data from two superposed normal distributions and then applied sklearn.neighbors.KernelDensity and scipy.stats.gaussian_kde to estimate the density function. However, using the same bandwith (1.0) and the same kernel, both methods produce a different outcome. Can someone explain me the reason for this? T... | [
"What is meant by bandwidth in scipy.stats.gaussian_kde and sklearn.neighbors.KernelDensity is not the same. Scipy.stats.gaussian_kde uses a bandwidth factor https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html. For a 1-D kernel density estimation the following formula is applied:\nthe... | [
3,
1
] | [
"Increase the size of 'random normal'. your data points are too few.\ntry with n=500000 and check the results.\n"
] | [
-1
] | [
"kernel_density",
"probability_density",
"python",
"scikit_learn",
"scipy"
] | stackoverflow_0068396403_kernel_density_probability_density_python_scikit_learn_scipy.txt |
Q:
How can i get Certificate issuer information in python?
I want the 'issued to' information from certificate in python. I try to use the SSL and SSLSocket library but did not happen.
A:
Updated answer
If you can establish a connection to the remote server you can use the ssl standard library module:
import ssl, s... | How can i get Certificate issuer information in python? | I want the 'issued to' information from certificate in python. I try to use the SSL and SSLSocket library but did not happen.
| [
"Updated answer\nIf you can establish a connection to the remote server you can use the ssl standard library module:\nimport ssl, socket\n\nhostname = 'google.com'\nctx = ssl.create_default_context()\nwith ctx.wrap_socket(socket.socket(), server_hostname=hostname) as s:\n s.connect((hostname, 443))\n cert = s... | [
40,
2,
2,
0
] | [
"\nimport os\nimport re\nos.system('keytool -printcert -sslserver google.com:443 >cert.txt')\nfh = open(\"cert.txt\", \"r\")\ncontent = fh.readlines()\nfh.close()\ncontent = content[2]\nm = re.search('CN=(.+?),', content)\nif m:\n found = m.group(1)\nprint found\n\n"
] | [
-3
] | [
"certificate",
"python",
"ssl",
"ssl_certificate"
] | stackoverflow_0030862099_certificate_python_ssl_ssl_certificate.txt |
Q:
Binary matrix with row and column sum constraint
I want to find all the combinations of a binary matrix (ones and zeros) of size 18 x 9 where each row is equal to 5 and each column is equal to 10.
Also each block must have a 1 in each column.
The total number of combinations of that grid size is... well, too much ... | Binary matrix with row and column sum constraint | I want to find all the combinations of a binary matrix (ones and zeros) of size 18 x 9 where each row is equal to 5 and each column is equal to 10.
Also each block must have a 1 in each column.
The total number of combinations of that grid size is... well, too much to iterate over:
2 ** (18 x 9) combinations = 5,846,00... | [
"Binary matrix with row and column sum constraint.\nsolve(4^3^2^x - 2^162 == 0, x)\n\n"
] | [
0
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0067807646_matrix_python.txt |
Q:
Python Pandas Replacing Header with Top Row
I currently have a dataframe that looks like this:
Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4
0 Sample Number Group Number Sample Name Group Name
1 1.0 1.0 s_1 g_1
2 2.0 1.0 s_2 ... | Python Pandas Replacing Header with Top Row | I currently have a dataframe that looks like this:
Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4
0 Sample Number Group Number Sample Name Group Name
1 1.0 1.0 s_1 g_1
2 2.0 1.0 s_2 g_1
3 3.0 1.0 ... | [
"new_header = df.iloc[0] #grab the first row for the header\ndf = df[1:] #take the data less the header row\ndf.columns = new_header #set the header row as the df header\n\n",
"The dataframe can be changed by just doing\ndf.columns = df.iloc[0]\ndf = df[1:]\n\nThen \ndf.to_csv(path, index=False) \n\nShould do the... | [
301,
88,
67,
17,
10,
6,
5,
1,
1,
0,
0
] | [
"The best practice and Best OneLiner:\ndf.to_csv(newformat,header=1)\n\nNotice the header value:\nHeader refer to the Row number(s) to use as the column names. Make no mistake, the row number is not the df but from the excel file(0 is the first row, 1 is the second and so on).\nThis way, you will get the column nam... | [
-3
] | [
"header",
"pandas",
"python",
"row"
] | stackoverflow_0031328861_header_pandas_python_row.txt |
Q:
Server error when sending POST request to hosted fastapi
I have a simple Fastapi where am expecting python dictionary or json data.
I can POST and GET data when running on local server. I hosted same api on https://deta.sh but i can only send GET request. POST request is returning status code 500.
I tried hosting ... | Server error when sending POST request to hosted fastapi | I have a simple Fastapi where am expecting python dictionary or json data.
I can POST and GET data when running on local server. I hosted same api on https://deta.sh but i can only send GET request. POST request is returning status code 500.
I tried hosting the same api on Heroku but i get status code 503
here is the s... | [
"Unfortunately, micros only support read-only SQLite, which you could deploy with your code. You can use Deta Base instead of SQLite.\n"
] | [
1
] | [] | [] | [
"fastapi",
"python",
"python_requests"
] | stackoverflow_0072280435_fastapi_python_python_requests.txt |
Q:
How to detect a new usb device is connected on python
I want to make something which will run on the background and only after the computer detect new device is connected the rest of the code will run, is there any elegant way to do such a thing?
A:
this is operating system dependent
in linux you can use pyudev ... | How to detect a new usb device is connected on python | I want to make something which will run on the background and only after the computer detect new device is connected the rest of the code will run, is there any elegant way to do such a thing?
| [
"this is operating system dependent\nin linux you can use pyudev for this :\n\nAlmost the complete libudev functionality is exposed. You can:\n\nEnumerate devices, filtered by specific criteria (pyudev.Context)\nQuery device information, properties and attributes,\nMonitor devices, both synchronously and asynchrono... | [
8,
3,
0,
0,
0
] | [] | [] | [
"python",
"pyudev",
"usb"
] | stackoverflow_0047495206_python_pyudev_usb.txt |
Q:
Combining looping and conditional to make new columns on dataframe
I want to make a function with loop and conditional, that count only when Actual Result = 1.
So the numbers always increase by 1 if the Actual Result = 1.
This is my dataframe:
This is my code but it doesnt produce the result that i want :
def fun... | Combining looping and conditional to make new columns on dataframe | I want to make a function with loop and conditional, that count only when Actual Result = 1.
So the numbers always increase by 1 if the Actual Result = 1.
This is my dataframe:
This is my code but it doesnt produce the result that i want :
def func_count(x):
for i in range(1,880):
if x['Actual Result']==1:
... | [
"Try something like this:\nimport pandas as pd\n\ndf = pd.DataFrame({\n 'age': [30,25,40,12,16,17,14,50,22,10],\n 'actual_result': [0,1,1,1,0,0,1,1,1,0]\n})\n\ncount = 0\nlst_count = []\nfor i in range(len(df)):\n if df['actual_result'][i] == 1:\n count+=1\n lst_count.append(count)\n else:... | [
0,
0
] | [] | [] | [
"for_loop",
"function",
"loops",
"python"
] | stackoverflow_0074342788_for_loop_function_loops_python.txt |
Q:
How to convert "month-day" object to date format in pandas dataframe
I have a df with a column:
column
Dec-01
The column datatype is an object.
I am trying to change it to a datatype date.
This is what I've tried:
df['column'] = pd.to_datetime(df['column']).dt.strftime(%d-%b')
This is the error I receive:
pan... | How to convert "month-day" object to date format in pandas dataframe | I have a df with a column:
column
Dec-01
The column datatype is an object.
I am trying to change it to a datatype date.
This is what I've tried:
df['column'] = pd.to_datetime(df['column']).dt.strftime(%d-%b')
This is the error I receive:
pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime: Out of bounds n... | [
"You can use:\ndf['date'] = pd.to_datetime(df['column'], format='%b-%d').dt.strftime('%m/%d/22')\n\nNB. you must hardcode the year as it is undefined in your original data and pandas will by default use 1970.\noutput:\n column date\n0 Dec-01 12/01/22\n\n"
] | [
1
] | [] | [] | [
"datetime",
"datetime_format",
"pandas",
"python"
] | stackoverflow_0074348647_datetime_datetime_format_pandas_python.txt |
Q:
How to create a dictionary that will automatically be filled in from sample ID's I need?
I have been working on a code to help automate one of the processes in the lab I work at. To summarize the entire purpose of the code, I am creating a way to take experiment data, create a file of data, and send it to the webs... | How to create a dictionary that will automatically be filled in from sample ID's I need? | I have been working on a code to help automate one of the processes in the lab I work at. To summarize the entire purpose of the code, I am creating a way to take experiment data, create a file of data, and send it to the website host that retains all of this information. I'm having some trouble figuring out how to cre... | [
"The code you supply suggests that you want a dictionary with numeric keys that start from 0. If so, here's how to get such a dictionary, where the values are taken directly from the result of the web query:\nr = {i: v for i, v in enumerate(vcfs)}\npprint(r)\n\nA result of three items would look like this:\n{0: {'... | [
0
] | [] | [] | [
"biopython",
"data_science",
"dictionary",
"export_to_csv",
"python"
] | stackoverflow_0074348608_biopython_data_science_dictionary_export_to_csv_python.txt |
Q:
How to detect if USB device is plugged in using python?
I want to create a script that detects once the USB drive is plugged into the computer and for now just to print in the cmd detect.
Note I am using windows after my search I found that I need to use pyudev package in order to communicate with serial ports and... | How to detect if USB device is plugged in using python? | I want to create a script that detects once the USB drive is plugged into the computer and for now just to print in the cmd detect.
Note I am using windows after my search I found that I need to use pyudev package in order to communicate with serial ports and I need to know the Vendor ID of the USB device.
i tried to ... | [
"i solved my question and i wrote this script that allow me to detect the last removable device that is plugged in.\ncode:\nimport win32api\nimport win32file\n\n# Returns a list containing letters from removable drives\ndrive_list = win32api.GetLogicalDriveStrings()\ndrive_list = drive_list.split(\"\\x00\")[0:-1] ... | [
2,
0,
0
] | [] | [] | [
"python",
"pyudev"
] | stackoverflow_0060014591_python_pyudev.txt |
Q:
How to get an index of max value element from a list column in python polars?
I have a data frame:
pl.DataFrame({'no_of_docs':[[9,4,2],
[3,9,1,10],
[10,3,2,1],
[10,30],
[1,2,3,6,4,5]]})
Here the column:... | How to get an index of max value element from a list column in python polars? | I have a data frame:
pl.DataFrame({'no_of_docs':[[9,4,2],
[3,9,1,10],
[10,3,2,1],
[10,30],
[1,2,3,6,4,5]]})
Here the column: no_of_docs is a list[int] type one: i would like to add a new column with the max ... | [
"I have found a way to do it for list[int] type as below:\ndf.with_column(pl.col('no_of_docs').arr.arg_max().alias('idx')\n\nThe same thing to be done to list[str] type.\n",
"I mean you answered the question mostly yourself, but in case you still need the casting to List[i64]. Here would be the solution\ndf.with_... | [
2,
1,
0
] | [] | [] | [
"python",
"python_polars"
] | stackoverflow_0074344367_python_python_polars.txt |
Q:
Getting only a part of the page source using selenium webdriver
I'm trying to get the HTML of Billboard's top 100 chart, but I keep getting only about half of the page.
I tried getting the page source using this code:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriv... | Getting only a part of the page source using selenium webdriver | I'm trying to get the HTML of Billboard's top 100 chart, but I keep getting only about half of the page.
I tried getting the page source using this code:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
s=Service(ChromeDriverMa... | [
"Not sure why you are getting 53 elements. Using explicit waits I am getting all 100 elements.\nUser webdriverwait() as an explicit wait.\ndriver.get('https://www.billboard.com/charts/hot-100/')\nelements=WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, \"ul.lrv-a-unstyle-list h3... | [
2,
0
] | [] | [] | [
"html",
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074348691_html_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
String slice of a column in a datframe
data = [['Tom', '5-123g'], ['Max', '6-745.0d'], ['Bob', '5-900.0e'], ['Ben', '2-345',], ['Eva', '9-712.x']]
df = pd.DataFrame(data, columns=['Person', 'Action'])
I want to shorten the "Action" column to a length of 5. My current df has two columns:
['Person'] and ['Action'] ... | String slice of a column in a datframe | data = [['Tom', '5-123g'], ['Max', '6-745.0d'], ['Bob', '5-900.0e'], ['Ben', '2-345',], ['Eva', '9-712.x']]
df = pd.DataFrame(data, columns=['Person', 'Action'])
I want to shorten the "Action" column to a length of 5. My current df has two columns:
['Person'] and ['Action']
I need it to look like this:
person A... | [
"Try this:\ndf['Action_short'] = df['Action'].str.slice(0, 5)\n\nBy using .str on a DataFrame or a single column of a DataFrame (which is a pd.Series), you can access pandas string manipulation methods that are designed to look like the string operations on standard python strings.\n",
"\n# slice by specifying th... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074349104_dataframe_pandas_python.txt |
Q:
Pandas : fill NaN with the closest value, according to a category column
Let's take a sample dataframe :
df = pd.DataFrame({"Date": ["2022-10-01","2022-10-02","2022-10-03","2022-10-04","2022-10-05","2022-10-06","2022-10-01","2022-10-02","2022-10-03","2022-10-04","2022-10-05","2022-10-06"],
"Anim... | Pandas : fill NaN with the closest value, according to a category column | Let's take a sample dataframe :
df = pd.DataFrame({"Date": ["2022-10-01","2022-10-02","2022-10-03","2022-10-04","2022-10-05","2022-10-06","2022-10-01","2022-10-02","2022-10-03","2022-10-04","2022-10-05","2022-10-06"],
"Animal" :["Cat","Cat","Cat","Cat","Cat","Cat","Dog","Dog","Dog","Dog","Dog","Dog"]... | [
"You can use ffill/bfill per group:\ndf['Quantity'] = (df.groupby('Animal', group_keys=False)['Quantity']\n .apply(lambda s: s.bfill().ffill())\n )\n\nOutput:\n Date Animal Quantity\n0 2022-10-01 Cat 4.0\n1 2022-10-02 Cat 4.0\n2 2022-10-03 Cat ... | [
2,
0
] | [] | [] | [
"dataframe",
"missing_data",
"nan",
"pandas",
"python"
] | stackoverflow_0074348938_dataframe_missing_data_nan_pandas_python.txt |
Q:
How to remove the ticklabels from a seaborn.objects plot
How to disable the axes' ticklabels for seaborn.objects generated image?
import seaborn as sns
from seaborn import objects as so
tips = sns.load_dataset("tips")
(
so.Plot(tips, "total_bill", "tip")
.add(so.Dots())
.layout(size=(4, 5))
.label... | How to remove the ticklabels from a seaborn.objects plot | How to disable the axes' ticklabels for seaborn.objects generated image?
import seaborn as sns
from seaborn import objects as so
tips = sns.load_dataset("tips")
(
so.Plot(tips, "total_bill", "tip")
.add(so.Dots())
.layout(size=(4, 5))
.label(x=None, y=None)
.save("data/dot_01.png")
.show()
)
T... | [
"import seaborn as sns\nimport seaborn.objects as so\nfrom matplotlib.ticker import FixedFormatter\n\ntips = sns.load_dataset(\"tips\")\nempty_formatter = FixedFormatter([])\n\n(\n so.Plot(tips, \"total_bill\", \"tip\")\n .add(so.Dots())\n .layout(size=(4, 5))\n .label(x=None, y=None)\n .scale(\n ... | [
2
] | [] | [] | [
"python",
"seaborn",
"seaborn_0.12.x"
] | stackoverflow_0074333747_python_seaborn_seaborn_0.12.x.txt |
Q:
SQLALCHEMY_DATABASE_URI' config is not set. Bind key 'None' is not in 'SQLALCHEMY_BINDS' config
I'm new to Flask and Python and I don't understand why it gives me this error:
Traceback (most recent call last):
File "C:\Users\Lucía\Documents\TFG\herfontsistemas-app\herfontsistemas-back\index.py", line 6, ... | SQLALCHEMY_DATABASE_URI' config is not set. Bind key 'None' is not in 'SQLALCHEMY_BINDS' config | I'm new to Flask and Python and I don't understand why it gives me this error:
Traceback (most recent call last):
File "C:\Users\Lucía\Documents\TFG\herfontsistemas-app\herfontsistemas-back\index.py", line 6, in <module>
db.create_all()
File "C:\Users\Lucía\Documents\TFG\herfontsistemas-app\herfonts... | [
"I am assuming you are using Flask-SQLAlchemy version > 3.\nYou do not have to create your SQLAlchemy(app) in your app.py file. I would give the following a try.\nindex.py:\nfrom app import app\nfrom utils.db import db\n\n#Cuando arranque la aplicacion creará las tablas dee contact.py\n\n#ADD THIS LINE HERE\ndb.ini... | [
0,
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074039332_flask_python.txt |
Q:
Python Tkinter VERTICAL Slider and HOROZONTAL Slider beneath each other
I'am relative new to python and just wanted to create a GUI with a VERTICAL Slider on the left and like 4 HORIZOTAL Slider on the right without Space. This is my current Code, and as you can see, the Vertical Slider is above the Horozontal Sli... | Python Tkinter VERTICAL Slider and HOROZONTAL Slider beneath each other | I'am relative new to python and just wanted to create a GUI with a VERTICAL Slider on the left and like 4 HORIZOTAL Slider on the right without Space. This is my current Code, and as you can see, the Vertical Slider is above the Horozontal Slider. So how do I get the Vertical Slider to the left and all other beside the... | [
"In this very specific case, Slider1.pack(side=\"left\") is what you need to do before calling pack on any of the other sliders.\npack works by reserving a side of the available space, and then placing the widget inside that space. By packing something with side='left' you're requesting the widget to be along the l... | [
0
] | [] | [] | [
"python",
"slider",
"tkinter"
] | stackoverflow_0074344946_python_slider_tkinter.txt |
Q:
send Youtube videos to telegram
i wrote this program :
import scrapetube
import hashlib
import telegram
import requests
import json
from pytube import YouTube
from time import sleep
import os
bot_token = 'my token'
bot_chatID = '@PinkPanthersShow'
bot = telegram.Bot(token=f'{bot_token}')
c_videos = scrapetube.g... | send Youtube videos to telegram | i wrote this program :
import scrapetube
import hashlib
import telegram
import requests
import json
from pytube import YouTube
from time import sleep
import os
bot_token = 'my token'
bot_chatID = '@PinkPanthersShow'
bot = telegram.Bot(token=f'{bot_token}')
c_videos = scrapetube.get_channel("UC1fIyfhQtm1fSljyKBf2uKA"... | [
"If you want To send All videos Of a Youtube channel to telegram, you can use ytt, which is a module I have written:\nhttps://nimafanniasl.github.io/py_youtube_to_telegram/\nIf you want to use an app , You can use ytt app, but if you want to use it in python, you can use ytt module, example:\npip install ytt\n\npyt... | [
0,
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram",
"telegram_bot",
"video"
] | stackoverflow_0069538872_python_python_telegram_bot_telegram_telegram_bot_video.txt |
Q:
zlib.error: Error -3 while decompressing data: too many length or distance symbols
Encountering this error for decompressing chunks of a file.
I already decompressed successfully about 5 chunks of data.
But there is just one range of data that doens't get decompressed.
The header should be right.
Header 78 9C
This... | zlib.error: Error -3 while decompressing data: too many length or distance symbols | Encountering this error for decompressing chunks of a file.
I already decompressed successfully about 5 chunks of data.
But there is just one range of data that doens't get decompressed.
The header should be right.
Header 78 9C
This is only a chunk of the whole file. The file itself consists of multiple compressed chun... | [
"That is a valid zlib header, but the deflate data that follows has an error in the first two bytes. Your data was corrupted somehow.\n"
] | [
1
] | [] | [] | [
"compression",
"decompiling",
"hex",
"python",
"zlib"
] | stackoverflow_0074347344_compression_decompiling_hex_python_zlib.txt |
Q:
Save HTML File to S3 bucket
After converting a Plotly graph to an HTML Page by this code:
import plotly
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x='date', y="GOOG")
plotly.offline.plot(fig , filename = 'filename.html', auto_open=False)
How can I store this HTML Page on an S3 bucket?
I... | Save HTML File to S3 bucket | After converting a Plotly graph to an HTML Page by this code:
import plotly
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x='date', y="GOOG")
plotly.offline.plot(fig , filename = 'filename.html', auto_open=False)
How can I store this HTML Page on an S3 bucket?
I tried this code:
fig.write_html... | [
"To get the latest code examples of all AWS SDKs, including Python, look at the new AWS Code Library here:\nhttps://docs.aws.amazon.com/code-library/latest/ug/what-is-code-library.html\nYou will find hundreds of code examples in many different programming languages. Included in this doc is how to perform Amazon S3... | [
1,
1
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"aws_lambda",
"plotly",
"python"
] | stackoverflow_0074346998_amazon_s3_amazon_web_services_aws_lambda_plotly_python.txt |
Q:
how to convert date in dd/mm/yyyy to days in python csv
i will like to covert dates to days
Example 01/01/2001 should be Day 1, 02/01/2001 should be Day 2
I have tried
prices_df['01/01/2001'] = prices_df['days'].dt.days
A:
Without using any external function or a complicated solution, you can simply take the fir... | how to convert date in dd/mm/yyyy to days in python csv | i will like to covert dates to days
Example 01/01/2001 should be Day 1, 02/01/2001 should be Day 2
I have tried
prices_df['01/01/2001'] = prices_df['days'].dt.days
| [
"Without using any external function or a complicated solution, you can simply take the first 2 chars of the string.\nint('01/01/2001'[0:2])\n\nOutput:\n1\n\nIf you have to do this in a pandas column:\nimport pandas as pd\npd.to_numeric(df['days'].str[0:2])\n\nN.B. This works if all date are in the form day/month/y... | [
0
] | [] | [] | [
"data_cleaning",
"date",
"days",
"python"
] | stackoverflow_0074349202_data_cleaning_date_days_python.txt |
Q:
highlight two rows on condition in one row pandas
I want to highlight condition 1: every row in B which contains "a" and condition 2: if a row in B is highlighted the corresponding row in ID should be highlighted as well
import pandas as pd
import numpy as np
data = {'ID':[1,2,3,4,5,6,7,8,9,10],
'B':["a","... | highlight two rows on condition in one row pandas | I want to highlight condition 1: every row in B which contains "a" and condition 2: if a row in B is highlighted the corresponding row in ID should be highlighted as well
import pandas as pd
import numpy as np
data = {'ID':[1,2,3,4,5,6,7,8,9,10],
'B':["a","b","c","a","e","f","a","h","c","a"],
'C': [5,7,... | [
"One option using axis=None to work on the whole DataFrame at once:\ndef color(df, cols=None):\n if cols is None:\n cols = df.columns\n \n mask = pd.DataFrame(columns=df.columns, index=df.index)\n \n mask[cols] = np.tile(np.where(df['B'].eq('a'),\n 'background-co... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074348914_pandas_python.txt |
Q:
How to change size of plot in xgboost.plot_importance?
xgboost.plot_importance(model, importance_type='gain')
I am not able to change size of this plot. I want to save this figure with proper size so that I can use it in pdf. I want similar like figize
A:
It looks like plot_importance return an Axes object
ax =... | How to change size of plot in xgboost.plot_importance? | xgboost.plot_importance(model, importance_type='gain')
I am not able to change size of this plot. I want to save this figure with proper size so that I can use it in pdf. I want similar like figize
| [
"It looks like plot_importance return an Axes object\nax = xgboost.plot_importance(...)\nfig = ax.figure\nfig.set_size_inches(h, w)\n\nIt also looks like you can pass an axes in\nfig, ax = plt.subplots(figsize=(h, w))\nxgboost.plot_importance(..., ax=ax)\n\n",
"import matplotlib.pyplot as plt\nfig, ax = plt.subpl... | [
45,
1
] | [] | [] | [
"machine_learning",
"matplotlib",
"python",
"python_3.x",
"xgboost"
] | stackoverflow_0040664776_machine_learning_matplotlib_python_python_3.x_xgboost.txt |
Q:
use asyncio for parallel tasks
I was wondering how I could use asyncio to handle tasks similar to what nodeJS does. I want to run tasks at the same time without opening threads.
Example:
import asyncio
@asyncio.coroutine
def my_coroutine(task_name, seconds_to_sleep=3):
print('{0} sleeping for: {1} seconds'.f... | use asyncio for parallel tasks | I was wondering how I could use asyncio to handle tasks similar to what nodeJS does. I want to run tasks at the same time without opening threads.
Example:
import asyncio
@asyncio.coroutine
def my_coroutine(task_name, seconds_to_sleep=3):
print('{0} sleeping for: {1} seconds'.format(task_name, seconds_to_sleep))
... | [
"asyncio doesn't run things in parallel. It runs one task until it awaits, then moves on to the next. The sleeps in your first example are what make the tasks yield control to each other. Your second example doesn't await anything, so each task runs until completion before the event loop can give control to another... | [
11,
1
] | [] | [] | [
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0040558484_python_python_3.x_python_asyncio.txt |
Q:
Create random bool array
I want to create a randomized bool array with a given length a given number of True values efficiently in Python. I could not find a single command to do so, the following does what I want (twice). Is there anything more elegant way to do it?
import numpy as np
def randbool(length,numtrue... | Create random bool array | I want to create a randomized bool array with a given length a given number of True values efficiently in Python. I could not find a single command to do so, the following does what I want (twice). Is there anything more elegant way to do it?
import numpy as np
def randbool(length,numtrue):
index_array=np.random.c... | [
"Still another option:\ndef randbool(l,n):\n return np.random.permutation(l)<n\n\nnp.random.permutation randomly permute np.arange(l).\n",
"Another suggestion:\ndef randbool3(length, numtrue):\n return np.random.choice(length, length, replace=False) < numtrue\n\nSimilar in efficiency to the first approach bu... | [
4,
1,
1
] | [] | [] | [
"numpy",
"python",
"random"
] | stackoverflow_0074348193_numpy_python_random.txt |
Q:
AttributeError: module 'PyQt5.QtCore' has no attribute 'DisplayRole'/my friend run it fine but not me, Is anyone know how can I fix these error?
It's some thing like this
from msilib import add_data
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
class pandasModel(QtCore):
def __init... | AttributeError: module 'PyQt5.QtCore' has no attribute 'DisplayRole'/my friend run it fine but not me, Is anyone know how can I fix these error? | It's some thing like this
from msilib import add_data
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
class pandasModel(QtCore):
def __init__(self, data):
QtCore.__init__(self)
self._data = data
def rowCount(self, parent=None):
return self._data.shape[0]
... | [
"Seems that the more recent version of PyQt have changed where DisplayRole, etc. live.\nfrom PyQt5.QtCore import Qt\n\n...\n\ndef headerData(self, col, orientation, role ):\n if role == Qt.ItemDataRole.DisplayRole:\n ...\n\n"
] | [
0
] | [] | [] | [
"pyqt5",
"python"
] | stackoverflow_0074070033_pyqt5_python.txt |
Q:
find_element(By.CLASS_NAME...) InvalidSelectorException
I need to navigate to the object with special class, that changes every page refresh
So i decided to use bs to find the element class, that works, but selenium raises an exception about invalid selector. class is existing, i can find it in page source. There ... | find_element(By.CLASS_NAME...) InvalidSelectorException | I need to navigate to the object with special class, that changes every page refresh
So i decided to use bs to find the element class, that works, but selenium raises an exception about invalid selector. class is existing, i can find it in page source. There are some spaces at the beginning and at the ending of class n... | [
"driver.find_element expects two arguments: By and a string containing a class name.\nvehicle_menu_class variable is built using this line: vehicle_menu_class = '\" ' + str(vehicle_menu_parent)[11:50] + ' \"'. So, in this case it is \" x-grid-cell x-grid-cell-gridcolumn-1331 \".\nThe spaces inside the class att... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium"
] | stackoverflow_0074349030_beautifulsoup_python_selenium.txt |
Q:
How to rotate a Vector2 in pygame
I am trying to make something like a clock, but I am having trubles rotating the vector.
For what I can tell the vector is rotating in respect of the point (0, 0) of the screen, but I want it to rotate in respect of the 'center' vector.
Another problem I am having is that, even th... | How to rotate a Vector2 in pygame | I am trying to make something like a clock, but I am having trubles rotating the vector.
For what I can tell the vector is rotating in respect of the point (0, 0) of the screen, but I want it to rotate in respect of the 'center' vector.
Another problem I am having is that, even tho the fps are locked on 60, it seems li... | [
"rotate_ip rotates the vector itself. As you increase the angle, the vector rotates more and more with each iteration. You must rotate the vector in place by a constant angle at each iteration:\nvector.rotate_ip(1)\n\nThe other option is to create a new vector from the original vector with increasing angle with the... | [
2
] | [] | [] | [
"pygame",
"python",
"vector",
"vector2"
] | stackoverflow_0074349387_pygame_python_vector_vector2.txt |
Q:
Python: error opening excel workbook with win32com
I am trying to make a program to open existing excel files, in order to read and write their contents. I am already having trouble opening files.
My code:
def open_sheet():
excel = win32com.client.Dispatch("Excel.Application")
wb = excel.Workbooks(r'C:\Us... | Python: error opening excel workbook with win32com | I am trying to make a program to open existing excel files, in order to read and write their contents. I am already having trouble opening files.
My code:
def open_sheet():
excel = win32com.client.Dispatch("Excel.Application")
wb = excel.Workbooks(r'C:\Users\<username>\Documents\<more file path>\test.xls').Ope... | [
"I think your problem comes from:\nwb = excel.Workbooks(r'C:\\Users\\<username>\\Documents\\<more file path>\\test.xls').Open()\n\nThe path to your file should be in Open() such as:\nwb = excel.Workbooks.Open(r'C:\\Users\\<username>\\Documents\\<more file path>\\test.xls')\n\nNote also that there is no () after Wor... | [
1,
0
] | [] | [] | [
"excel",
"python",
"pywin",
"win32com"
] | stackoverflow_0049621501_excel_python_pywin_win32com.txt |
Q:
Clicking a button to go to the next page with Python
I'm trying to click on a button on a webpage without using Selenium's .click function, so that I can scrape the contents of the next page. The button can be seen below.
I've seen other questions where a .post is used for that, but I can't seem to figure it out ... | Clicking a button to go to the next page with Python | I'm trying to click on a button on a webpage without using Selenium's .click function, so that I can scrape the contents of the next page. The button can be seen below.
I've seen other questions where a .post is used for that, but I can't seem to figure it out exactly.
| [
"Why wouldn't you use the .click function? For example:\ndriver.find_element(By.CLASS_NAME, \"class name\").click()\n"
] | [
0
] | [] | [] | [
"post",
"python",
"selenium"
] | stackoverflow_0074349397_post_python_selenium.txt |
Q:
While trying to start Celery, I am faced with incompatible demands from celery and flask while importing modules. What do I do?
I am trying to start Celery in a Flask app. My goal is to run the Flask app with Celery accepting workers simultaneously. To do this, I need to figure out how to satisfy the demands of bo... | While trying to start Celery, I am faced with incompatible demands from celery and flask while importing modules. What do I do? | I am trying to start Celery in a Flask app. My goal is to run the Flask app with Celery accepting workers simultaneously. To do this, I need to figure out how to satisfy the demands of both Celery and Flask.
To run Celery, I run: celery -A rentCanada worker --loglevel=debug
and I get the wall of beautiful blue text tel... | [
"someone on Discord fixed it for me. The solution was to put all my python code in a directory named after my root directory, and then run celery like celery -A canadaAps.rentCanada worker --loglevel=debug when the entrypoint file is now in a directory like\n/canadaAps\n /canadaAps\n rentCanada.py\n\nnow... | [
1
] | [] | [] | [
"celery",
"flask",
"python"
] | stackoverflow_0074341641_celery_flask_python.txt |
Q:
How to detect the date format? (python)
I have a Dataframe in python, with the data coming from a csv.
In the column "Date" I have a date (:)) but I don't know the date format. How can I detect it?
e.g.: I can have 05/05/2022. this can be M/D/Y or D/M/Y. I can manually understand it by looking at other entries, bu... | How to detect the date format? (python) | I have a Dataframe in python, with the data coming from a csv.
In the column "Date" I have a date (:)) but I don't know the date format. How can I detect it?
e.g.: I can have 05/05/2022. this can be M/D/Y or D/M/Y. I can manually understand it by looking at other entries, but I wish I can do it automatically.
Is there ... | [
"You can try the dateutil library.\nTo deal with dates and also with the diversity of timezones people often use external libraries such as pytz or dateutil.\ndateutil has a very powerful parser.\nfrom dateutil.parser import parse\n\nparse('05/05/2022') # datetime.datetime(2022, 5, 5, 0, 0)\nparse('2022-05-05') #... | [
1,
0
] | [] | [] | [
"automation",
"date",
"python"
] | stackoverflow_0074348707_automation_date_python.txt |
Q:
How to use dictionaries while creating a cookbook
I am learning Python and have thought of a project in which the user should be able to create a recipes, give the recipe a name and add the ingredients. It should be possible to create a small cookbook, so to speak.
At the moment I've this with a dictionary for eac... | How to use dictionaries while creating a cookbook | I am learning Python and have thought of a project in which the user should be able to create a recipes, give the recipe a name and add the ingredients. It should be possible to create a small cookbook, so to speak.
At the moment I've this with a dictionary for each recipe, in which each ingredient is linked to a quant... | [
"You can use Python f-strings to get what you want. I guess that you are using dictionary like this:\nd = {\n \"ingrediante1 (string)\": amount (int),\n \"ingrediante2 (string)\": amount (int)\n}\n\nYou can replace the amount integer with f-string that will contain both amount and unit of measure like this: f... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074349362_dictionary_python.txt |
Q:
Python OS module stalls after new processes starts
I am trying to write a Raspberry Pi Python-3 script that turns on an IR receiver using a call to os.system() with mode2 as the argument.
When this line of code executes, the mode2 process starts and runs properly (I can see it working in the open terminal) but the... | Python OS module stalls after new processes starts | I am trying to write a Raspberry Pi Python-3 script that turns on an IR receiver using a call to os.system() with mode2 as the argument.
When this line of code executes, the mode2 process starts and runs properly (I can see it working in the open terminal) but the rest of the program stalls. There is additional code th... | [
"Here is a minimal way to approach this:\nA bash script my_process.sh sleeps for 10 seconds, then writes the string \"Hello\" into a world.txt file:\n#!/usr/bin/env bash\n\nsleep 10; echo 'Hello' > world.txt\n\nA python script starts my_process.sh, and prints \"Done from Python\" when finished.\n# File: sample_scri... | [
0
] | [] | [] | [
"linux",
"os.system",
"python",
"python_3.x"
] | stackoverflow_0074308552_linux_os.system_python_python_3.x.txt |
Q:
How to split values of a Python dictionary
I have a dictionary like this:
data = {
key1: [ <A><B> ]
key2: [ <C><D> ]
key3: [ <A><F> ]
...
}
Goal to achieve:
I want to have instead something like this:
new_dict = {
key1: [ <A>, <B> ]
key2: [ <C>, <D> ]
key3: [ <A>, <F> ]
...
}
And then extract only the keys with ... | How to split values of a Python dictionary | I have a dictionary like this:
data = {
key1: [ <A><B> ]
key2: [ <C><D> ]
key3: [ <A><F> ]
...
}
Goal to achieve:
I want to have instead something like this:
new_dict = {
key1: [ <A>, <B> ]
key2: [ <C>, <D> ]
key3: [ <A>, <F> ]
...
}
And then extract only the keys with "< A>" as first value and save them in a list. S... | [
"User regular expression to findall the substrings matching the pattern <\\w> where \\w basically means a word character, then filter out the keys for the resulting list of values.\nimport re\npattern=re.compile('<\\w>')\nout={k:pattern.findall(v[0]) for k,v in data.items()} # data is your dict\n# out\n# {'key1': [... | [
1
] | [] | [] | [
"dictionary",
"key_value",
"list",
"python",
"python_3.x"
] | stackoverflow_0074349478_dictionary_key_value_list_python_python_3.x.txt |
Q:
How to get a true or false value based on a random list
I currently have a "for fun" program idea that I'm undertaking. Essentially, the program spits out a quote and the user has to say if it's real or made up (1 and 2 as the input). My current code is
`
#the point of the code is to select a random quote from eit... | How to get a true or false value based on a random list | I currently have a "for fun" program idea that I'm undertaking. Essentially, the program spits out a quote and the user has to say if it's real or made up (1 and 2 as the input). My current code is
`
#the point of the code is to select a random quote from either t or f and use user input to see if they think it's real ... | [
"You have some errors in your code:-\nline no.7 it's while fact==0\nyou are checking a condition here. so you need to put two equals.\nline no.9 module 'random' has no attribute randchoice it is choice only.\nYou need to put the argument as list or some other iteratives.\nAtlast you didn't even call the main() func... | [
0
] | [] | [] | [
"python",
"user_input"
] | stackoverflow_0074349296_python_user_input.txt |
Q:
Pandas - Count column categorical value based on another column categorical value
I'm new to python and pandas. I have a data set with the columns age, sex, bmi, children, smoker, region, charges. I want to write a query to count all the smokers that answered "yes" based on their region. the regions can only be no... | Pandas - Count column categorical value based on another column categorical value | I'm new to python and pandas. I have a data set with the columns age, sex, bmi, children, smoker, region, charges. I want to write a query to count all the smokers that answered "yes" based on their region. the regions can only be northwest, northeast, southwest, southeast.
I have tried several groupby and series comma... | [
"One easy way is to first convert the Smoker column to a boolean:\ndata['Smoker'].str.contains('y')\n\nAnd to chain this to a groupby.sum:\ndata['Smoker'].str.contains('y').groupby(data['Region']).sum()\n\nEnsure to use a Series as grouper (not just the column name).\nAn alternative would be to use a custom functio... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"string"
] | stackoverflow_0074349519_pandas_python_string.txt |
Q:
How do i paste my code in the python terminal using pyautogui?
coin = input("coin: ")
pyautogui.click(button='right')
pyautogui.press('enter')
print(coin)
after the input came out, pyautogui cant run the next line which is right click to paste the code in terminal. Is there any other solution to paste my code and... | How do i paste my code in the python terminal using pyautogui? | coin = input("coin: ")
pyautogui.click(button='right')
pyautogui.press('enter')
print(coin)
after the input came out, pyautogui cant run the next line which is right click to paste the code in terminal. Is there any other solution to paste my code and save it in a var?
| [
"First of all, you would be better of using the shortcut \"ctrl + v\" to paste it, like so:\npyautogui.hotkey('ctrl', 'v')\n\nHowever if your end goal is too get what is in your clipboard into a variable you could use this:\nimport win32clipboard\n\ndef getclipdata():\n win32clipboard.OpenClipboard()\n data =... | [
0
] | [] | [] | [
"input",
"pyautogui",
"python",
"variables"
] | stackoverflow_0074349453_input_pyautogui_python_variables.txt |
Q:
buildroot how to skip downloading step
I'm using Buildroot to add a python package python-xxx, but it always show time out or 404 error,
make: *** [package/pkg-generic.mk:189: /home/buildroot/output/build/python-xxx/.stamp_downloaded] Error 1
so I downloaded the package python-xxx.tar.gz somewhere else and put it... | buildroot how to skip downloading step | I'm using Buildroot to add a python package python-xxx, but it always show time out or 404 error,
make: *** [package/pkg-generic.mk:189: /home/buildroot/output/build/python-xxx/.stamp_downloaded] Error 1
so I downloaded the package python-xxx.tar.gz somewhere else and put it in the buildroot/dl/python-xxx directory to... | [
"You're not giving enough details to really help you. However, if you put the source code tarball in $(DL_DIR) with the correct name, Buildroot will definitely skip the download step and use this tarball.\nIf you want more help, provide more details, such as the .mk file of the package you're creating, as well as t... | [
1
] | [] | [] | [
"buildroot",
"embedded_linux",
"python",
"python_3.x",
"wget"
] | stackoverflow_0074328964_buildroot_embedded_linux_python_python_3.x_wget.txt |
Q:
I would like to download all images from this archive, what should i add to my code?
https://permalink.geldersarchief.nl/8A0A3B746F8147888ADF8FCA559F119B
this archive has 500 images i want to download and perform OCR on. I have already found this code online that downloads some images, but it doesn't find the 500 ... | I would like to download all images from this archive, what should i add to my code? | https://permalink.geldersarchief.nl/8A0A3B746F8147888ADF8FCA559F119B
this archive has 500 images i want to download and perform OCR on. I have already found this code online that downloads some images, but it doesn't find the 500 images of the book that i want for some reason. what should i add to the code? thanks in a... | [
"The website is loading images with JavaScript, so if you want to download those images you may have to use selenium or playwright instead of beautiful soup because beautiful soup library can fetch data from static web pages, but not from dynamic websites.\n",
"You could use the wget module and loop through the f... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"ocr",
"python"
] | stackoverflow_0074349110_beautifulsoup_ocr_python.txt |
Q:
How to find the x, y coordinate (or index) of values in a 2D array
I have a 2D array I created using this,
import numpy as np
arr = np.arange(4)
arr_2d = arr.reshape(2,2)
The array looks like this
print(arr_2d)
[[0, 1],
[2, 3]]
I am trying to get the location of each entry in arr_2d as an x, y coordinate, a... | How to find the x, y coordinate (or index) of values in a 2D array | I have a 2D array I created using this,
import numpy as np
arr = np.arange(4)
arr_2d = arr.reshape(2,2)
The array looks like this
print(arr_2d)
[[0, 1],
[2, 3]]
I am trying to get the location of each entry in arr_2d as an x, y coordinate, and eventually get an array that looks like this,
print(full_array)
[[0, ... | [
"You can use np.unravel_index():\nx = arr_2d.flatten()\nr = np.vstack((x,np.unravel_index(np.arange(arr_2d.size),arr_2d.shape))).T\n\n# r = array([[0, 0, 0],\n# [1, 0, 1],\n# [2, 1, 0],\n# [3, 1, 1]], dtype=int64)\n\nBoth flatten() and np.unravel_index() use by default a row-major orde... | [
1,
0
] | [] | [] | [
"arrays",
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074349333_arrays_numpy_python_python_3.x.txt |
Q:
Use calendar versioning for Python package
I prefer the calendar versioning scheme (see calver.org) over the semantic approach. But when I use calendar versioning in a Python package, PyPI removes the zero padding in the month. For example, in setup.py, if the version number is declared as version='19.03' then PyP... | Use calendar versioning for Python package | I prefer the calendar versioning scheme (see calver.org) over the semantic approach. But when I use calendar versioning in a Python package, PyPI removes the zero padding in the month. For example, in setup.py, if the version number is declared as version='19.03' then PyPI hosts the package as 19.3 (no zero padding).
I... | [
"Yes, it's possible. The issue isn't PyPI, it's the way setuptools normalizes the version number when building a distribution.\nTake this simple setup.py which defines a minimal package:\nfrom setuptools import setup\n\nsetup(\n name='calver-test',\n version='2019.03.29',\n packages=[],\n)\n\nIf you run py... | [
4,
0
] | [] | [] | [
"pip",
"pypi",
"python",
"python_3.x"
] | stackoverflow_0055409228_pip_pypi_python_python_3.x.txt |
Q:
Iterate through this json object
Hi I am trying to iterate through this json obtect I have tried all and it does not work
{
"results": [
{
"added_date": "Mon, 07 Nov 2022 14:42:14 GMT",
"born_date": "Mon, 07 Nov 2022 14:42:14 GMT",
"cellphone": "93545887778",
... | Iterate through this json object | Hi I am trying to iterate through this json obtect I have tried all and it does not work
{
"results": [
{
"added_date": "Mon, 07 Nov 2022 14:42:14 GMT",
"born_date": "Mon, 07 Nov 2022 14:42:14 GMT",
"cellphone": "93545887778",
"father_lastname": "Mendez",
... | [
"Your question is weird like you are iterating through employees and you didn't mention what employees are. I am assuming employees are the results.\nyour_json = {\n \"results\": [\n {\n \"added_date\": \"Mon, 07 Nov 2022 14:42:14 GMT\",\n \"born_date\": \"Mon, 07 Nov 2022 14:42:14 G... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074349343_python.txt |
Q:
'error : can only concatenate str/tuple(not "tuple/str) to str/tuple' error in adding fields to UserCreationForm
i tried to add new fields to UserCreationForm with using CustomUserCreationForm but i get this error
TypeError:can only concatenate str(not"tuple") to str
and when i change the field to str i got the... | 'error : can only concatenate str/tuple(not "tuple/str) to str/tuple' error in adding fields to UserCreationForm | i tried to add new fields to UserCreationForm with using CustomUserCreationForm but i get this error
TypeError:can only concatenate str(not"tuple") to str
and when i change the field to str i got the other one,
here is my code:
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreatio... | [
"The UserChangeForm defaults to including all fields, which uses the shortcut fields = '__all__'\nWhen you try to do UserChangeForm.Meta.fields +('age',) you are doing '__all__' + ('age',) which is what the error you're getting says.\nUsually an error as such in Python will include a stack trace that also include t... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074349580_django_django_models_python.txt |
Q:
Why random.randint() is much slower than random.getrandbits()
A made a test which compares random.randint() and random.getrandbits() in Python. The result shows that getrandbits is way faster than randint.
from random import randint, getrandbits, seed
from datetime import datetime
def ts():
return datetime.no... | Why random.randint() is much slower than random.getrandbits() | A made a test which compares random.randint() and random.getrandbits() in Python. The result shows that getrandbits is way faster than randint.
from random import randint, getrandbits, seed
from datetime import datetime
def ts():
return datetime.now().timestamp()
def diff(st, en):
print(f'{round((en - st) * 1... | [
"randint uses randrange which uses _randbelow which is _randbelow_with_get_randbits (if it is present) which uses getrandbits. However, randrange includes overhead on top of the underlying call to getrandbits because it must check for the start and step arguments. Even though there are fast paths for these checks,... | [
5,
3,
1,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0067957598_python_random.txt |
Q:
Pandas : add sub rows sum in multi-columns pivot
I've got a dataframe build fromRecordsa django queryset, that I pivot by 2 columns to get a dashboard view of it.
I manage to have the global sums byr row and column of the whole table, but I'm trying to get the sum by the first pivot columns (a sub total by row for... | Pandas : add sub rows sum in multi-columns pivot | I've got a dataframe build fromRecordsa django queryset, that I pivot by 2 columns to get a dashboard view of it.
I manage to have the global sums byr row and column of the whole table, but I'm trying to get the sum by the first pivot columns (a sub total by row for the first column of each group).
I know absolutely no... | [
"You can do normal pivot and then compute/append the total sum:\n# do a normal pivot\ndf = df.pivot_table(\n index=\"type\",\n columns=[\"fund\", \"source\"],\n values=\"amount\",\n aggfunc=\"sum\",\n)\n\n# compute \"sum\" dataframes\ndfs = []\nfor c in df.columns.get_level_values(0).unique():\n s = ... | [
0
] | [] | [] | [
"pandas",
"pivot",
"python",
"subtotal"
] | stackoverflow_0074349234_pandas_pivot_python_subtotal.txt |
Q:
How can I put the value of this three variables out of the function with the value inside the function?
Where is the code, I want to take the WarriorTurnOrder, PriestTurnOrder and enemy_turnOrder, with the value inside the function.
def initiative_phase(): #Function for setting the turn order
WarriorTurnOrder ... | How can I put the value of this three variables out of the function with the value inside the function? | Where is the code, I want to take the WarriorTurnOrder, PriestTurnOrder and enemy_turnOrder, with the value inside the function.
def initiative_phase(): #Function for setting the turn order
WarriorTurnOrder = 0
PriestTurnOrder = 0
enemy_turnOrder = 0
WarriorTurnOrder = WarriorTurnOrder + random.ran... | [
"METHOD 1:\nAll these variables that you declare in a function are local variables.\nUse global variable in your functions. For example: global WarriorTurnOrder. Do this for all 3 variables and it should work as you want.\ndef initiative_phase(): #Function for setting the turn order\n global WarriorTurnOrder\n ... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074349697_python_python_3.x.txt |
Q:
Behavior change in py.exe on recent versions of Python for Windows?
In my Python scripts I use the shebang syntax at the beginning of the script:
#!/usr/bin/env python3
I noticed that this mostly stopped working recently (on Windows with Python 3.11 and I believe also with 3.10.8) - like there were some changes t... | Behavior change in py.exe on recent versions of Python for Windows? | In my Python scripts I use the shebang syntax at the beginning of the script:
#!/usr/bin/env python3
I noticed that this mostly stopped working recently (on Windows with Python 3.11 and I believe also with 3.10.8) - like there were some changes to py.exe. When I run a script nothing happens:
# Nothing happens
myscrip... | [
"As per my knowledge, Windows have no proper shebang line. Shebang line normally used to say where executable is present/installed.\nAs per my observation\npython3 - Linux \npython - Windows or (python installed in linux <2.7)\n\n\nThis may be because Linux thought to keep different acronyms for differnt versions ... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074349036_python_python_3.x.txt |
Q:
Python XML parsing missing element: 'None' vs None
I am parsing an XML file and trying to find some XML tags. I'm looking for the tag personalDataRelated and when running it depending on XML file, I either get one of the two values below :
<Element 'personalDataRelated' at 0x0000020417C86AC0>
None
What I do next ... | Python XML parsing missing element: 'None' vs None | I am parsing an XML file and trying to find some XML tags. I'm looking for the tag personalDataRelated and when running it depending on XML file, I either get one of the two values below :
<Element 'personalDataRelated' at 0x0000020417C86AC0>
None
What I do next is depending on the value I get previously my variable d... | [
"You're testing against the 'None' string when you should be testing against the None keyword.\n"
] | [
0
] | [] | [] | [
"elementtree",
"parsing",
"python",
"xml",
"xml_parsing"
] | stackoverflow_0074349558_elementtree_parsing_python_xml_xml_parsing.txt |
Q:
Using python pandas data frame, how do you delete all rows that contain a '-'?
I am importing a .csv file that someone else made, and they filled in some rows with a '-' character wherever there was missing data. The data frame looks something like this:
Data1 Data2
0 99 1
1 99 2... | Using python pandas data frame, how do you delete all rows that contain a '-'? | I am importing a .csv file that someone else made, and they filled in some rows with a '-' character wherever there was missing data. The data frame looks something like this:
Data1 Data2
0 99 1
1 99 2
2 - 3
3 98 4
4 97 5
5 - -
6 ... | [
"The easiest is to use boolean indexing to keep the rows that are not (ne) - in all columns per row:\nout = df[df.ne('-').all(axis=1)]\n\nIf for some reason you want to drop (e.g. to update in place), you can use:\nm = df.eq('-').any(axis=1)\ndf.drop(df.index[m], inplace=True)\n\noutput:\n Data1 Data2\n0 99 ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074349765_dataframe_pandas_python.txt |
Q:
Exception Value: Field 'id' expected a number but got 'create-room'
I am stuck with this error and cant' seem to figure out the solution. I was following a YouTube course on channel called "Traversy Media" and it's title is "Python Django 7 hour course" and this part is around 01:39 min into the video "CRUD" sec... | Exception Value: Field 'id' expected a number but got 'create-room' | I am stuck with this error and cant' seem to figure out the solution. I was following a YouTube course on channel called "Traversy Media" and it's title is "Python Django 7 hour course" and this part is around 01:39 min into the video "CRUD" section.
this is the home.html file
{% extends 'main.html'%} {% block conten... | [
"Change <str:pk>/ to <int:pk>/ so:\nurlpatterns = [\n #...\n path('room/<int:pk>/', views.room, name='room')\n #...\n]\n\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_urls",
"python"
] | stackoverflow_0074349512_django_django_models_django_templates_django_urls_python.txt |
Q:
Import local module in a databricks notebook
I have created two new python notebooks for databricks in /workspace/Shared/Notebooks.
I would share some functions between the both notebooks. I have created a python file containing a few generic functions.
It exists a way to import my functions into my both notebooks... | Import local module in a databricks notebook | I have created two new python notebooks for databricks in /workspace/Shared/Notebooks.
I would share some functions between the both notebooks. I have created a python file containing a few generic functions.
It exists a way to import my functions into my both notebooks ?
Thanks for your help.
| [
"It is really easy, when it comes to sharing python code between .ipynb files.\nSay, you have following files:\nsource.py\ndest_1.ipynb\ndest_2.ipynb\n\nWith following contents:\n\nsource.py\n\na = \"hello from source\"\n\n\ndest_1.ipynb and dest_2.ipynb\n\nimport source\n\nprint(source.a)\n\nAnd you can simply run... | [
0,
0
] | [] | [] | [
"azure_databricks",
"databricks",
"python"
] | stackoverflow_0074347209_azure_databricks_databricks_python.txt |
Q:
How to extract the pixels of a shadow in an image in order to calculate the length?
I'm taking a picture every minute of a sundial. I want to create a python program which calculates the altitude of the sun based on the length of the shadows captured in the image. Below is such an image.
I tried to obtain the sh... | How to extract the pixels of a shadow in an image in order to calculate the length? | I'm taking a picture every minute of a sundial. I want to create a python program which calculates the altitude of the sun based on the length of the shadows captured in the image. Below is such an image.
I tried to obtain the shadows by using multi-otsu thresholding on the V-channel of the image (I determined this c... | [
"Wouldn't it be easier using only 1 pole? You could then just radially spin a pointer at a certain distance around the center of your pole.\nFor example along a straight line:\nthe graph shows the intensity of pixels along the red segment\n(the colors are inverted i have no idea why)\nThen figure out at what angle ... | [
0
] | [] | [] | [
"computer_vision",
"feature_extraction",
"image_processing",
"python"
] | stackoverflow_0061717458_computer_vision_feature_extraction_image_processing_python.txt |
Q:
How to split dataframe column by row
I have dataset which contains 6.2M records. When iam splitting it by grouping, it looses about 1.2M records. This is fraction of data set:
VendorID | tpep_pickup_datetime | tpep_dropoff_datetime | passenger_count |
1 | 2020-01-01 00:28:15 | 2020-01-01 00:33:03 | 1.0 ... | How to split dataframe column by row | I have dataset which contains 6.2M records. When iam splitting it by grouping, it looses about 1.2M records. This is fraction of data set:
VendorID | tpep_pickup_datetime | tpep_dropoff_datetime | passenger_count |
1 | 2020-01-01 00:28:15 | 2020-01-01 00:33:03 | 1.0
1 | 2020-01-01 00:35:39 | 2020-0... | [
"you could try this, though I believe it might not be the best way around (Pandas might have a better way for doing this).\nimport pandas as pd\ncols = [\"VendorID\", \"tpep_pickup_datetime\", \"tpep_dropoff_datetime\", \"passenger_count\"]\ndf = pd.DataFrame(\n [[1, \"2020-01-01 00:28:15\", \"2020-01-01 00:33:0... | [
1
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074348157_csv_dataframe_pandas_python.txt |
Q:
Python - Construct DF From XML API Response
I'm receiving the below XML response from an API call and am looking to iterate through the "Results" and store all of the data points as a pandas dataframe.
I was successfully able to grab my data points of interest by chaining .find() methods shown below, but don't kno... | Python - Construct DF From XML API Response | I'm receiving the below XML response from an API call and am looking to iterate through the "Results" and store all of the data points as a pandas dataframe.
I was successfully able to grab my data points of interest by chaining .find() methods shown below, but don't know how to loop through all of the Results block wi... | [
"You're super close, you need to find all of the Results tags, then iterate over them, last grabbing the elements you want:\nfor el in soup.find_all('Results'):\n objectid_field = el.find('ObjectID').text\n customerkey_field = el.find('CustomerKey').text\n name_field = el.find('Name').text\n issendable_... | [
1,
1
] | [] | [] | [
"pandas",
"python",
"python_3.x",
"xml"
] | stackoverflow_0074347869_pandas_python_python_3.x_xml.txt |
Q:
Not getting complete data using selenium
I am not getting all links there are 403 links in these page I am getting only 68 links I also used the scroll down method they move to end of page but not give all links is any thing I am doing wrong kindly guide us these is page link https://www.ocado.com/search?entry=fro... | Not getting complete data using selenium | I am not getting all links there are 403 links in these page I am getting only 68 links I also used the scroll down method they move to end of page but not give all links is any thing I am doing wrong kindly guide us these is page link https://www.ocado.com/search?entry=frozen
from selenium import webdriver
import time... | [
"With this should be enough:\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\n\n# We create the driver\ndriver = webdriver.Chrome()\n\n#... | [
1
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074349320_python_selenium_web_scraping.txt |
Q:
Failed to set 'pythonPath'. Error: Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again
I was trying to run and debug my very first program in Python, so my Visual Studio asks me to define a Python interpreter. I selected one, and my VS Code comes with th... | Failed to set 'pythonPath'. Error: Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again | I was trying to run and debug my very first program in Python, so my Visual Studio asks me to define a Python interpreter. I selected one, and my VS Code comes with this error. It might be in settings.json, but I don't' know how to solve it. Please help! I put the errors of settings.json and defaultsettings.json here, ... | [
"I just fixed the same issue on my computer. It was a missing curly brace in the settings.json file. Open your settings and click on the open settings.json in the top right corner. Once you open it you should see the red error at the last curly brace. Insert another curly brace before it and save, that should fix t... | [
4,
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0065170695_python_visual_studio_code.txt |
Q:
Can Scipy SmoothBivariateSpline deal with unknown/large numbers of knots (kx, ky)?
I am getting some strange behaviour when running scipy.interpolate.SmoothBivariateSpline. When running this with any smoothing factor apart from None the code seems to stall without an error message. I have run it on a server for ar... | Can Scipy SmoothBivariateSpline deal with unknown/large numbers of knots (kx, ky)? | I am getting some strange behaviour when running scipy.interpolate.SmoothBivariateSpline. When running this with any smoothing factor apart from None the code seems to stall without an error message. I have run it on a server for around 3 days and it appears that I have got no outputs - could it actually just be taking... | [
"kx=ky=3 are not knot numbers, these are spline degrees: i.e., you are using cubic splines.\nChanging SmoothBivariateSpline to bisplrep (same underlying Fortran code, a different wrapper) with an updated 850x850 example triggers the MemoryError on my machine, so it is an integer overflow indeed.\nTo your questions:... | [
1
] | [] | [] | [
"interpolation",
"python",
"scipy",
"smoothing",
"spline"
] | stackoverflow_0074261519_interpolation_python_scipy_smoothing_spline.txt |
Q:
Selenium driver is not finding elements within the scope of parent element
I am trying to find a specific element inside a certain parent element "table_list". However, the webdriver finds all the occurence of my required element on the web page.
def value():
table_list = driver.find_element(By.ID,"table_list"... | Selenium driver is not finding elements within the scope of parent element | I am trying to find a specific element inside a certain parent element "table_list". However, the webdriver finds all the occurence of my required element on the web page.
def value():
table_list = driver.find_element(By.ID,"table_list")
print(table_list.text)
value_informal = table_list.find_elements(By.XP... | [
"Change this line of code\nvalue_informal = table_list.find_elements(By.XPATH,\"//tr[contains(@id,'informal')]\")\n\nto this\n value_informal = table_list.find_elements(By.XPATH,\".//tr[contains(@id,'informal')]\")\n\n. means intermediate child of the parent element.\n",
"As soon as you start your path from / or... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"web_scraping",
"webdriver",
"xpath"
] | stackoverflow_0074347384_python_selenium_web_scraping_webdriver_xpath.txt |
Q:
I got this error 'DataFrame.dtypes for data must be int, float, bool or categorical' - xgboost XGBRFRegressor
I'm going to train this as an xgboost model (XGBRFRegressor).
But this kind of error occurred and I've never seen like this before.
ValueError: DataFrame.dtypes for data must be int, float, bool or categ... | I got this error 'DataFrame.dtypes for data must be int, float, bool or categorical' - xgboost XGBRFRegressor | I'm going to train this as an xgboost model (XGBRFRegressor).
But this kind of error occurred and I've never seen like this before.
ValueError: DataFrame.dtypes for data must be int, float, bool or category. When
categorical type is supplied, DMatrix parameter `enable_categorical` must
be set to `True`. Invalid colu... | [] | [] | [
"transform the field you got to int, then checks if the failure which column is relating to that field.\ntransform it\n"
] | [
-1
] | [
"python",
"python_3.x",
"xgboost"
] | stackoverflow_0074210194_python_python_3.x_xgboost.txt |
Q:
How do you reset index of Series in Pandas?
After using value_counts in Pandas
I want to reset the index
but the first column's name is replace with 'index'
and every columns' name got pushed to the right
df = df[df['type']=='food']['fruit'].value_counts()
df = df.reset_index()
df
index fruit
0 apple 120
1 gr... | How do you reset index of Series in Pandas? | After using value_counts in Pandas
I want to reset the index
but the first column's name is replace with 'index'
and every columns' name got pushed to the right
df = df[df['type']=='food']['fruit'].value_counts()
df = df.reset_index()
df
index fruit
0 apple 120
1 grape 110
2 orange 30
maybe I can use df.column... | [
"You can use rename_axis to rename the index and the name parameter of reset_index:\n(df[df['type']=='food']['fruit'].value_counts()\n .rename_axis('fruit')\n .reset_index(name='number'))\n\nOther option, use groupby.agg:\n(df[df['type']=='food']\n .groupby('fruit', as_index=False)\n .agg(number=('fruit', 'count'))... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074349913_pandas_python.txt |
Q:
Mask unwanted triangles of tricontour matplotlib
I am using tricontour to reproduce water content data and I would like to mask the triangles that are interpolated but are not part of the geometry of the surface.
I tried to plot only traingles with a maximum of radius = 2 (from another previous post):
fig, (ax2) =... | Mask unwanted triangles of tricontour matplotlib | I am using tricontour to reproduce water content data and I would like to mask the triangles that are interpolated but are not part of the geometry of the surface.
I tried to plot only traingles with a maximum of radius = 2 (from another previous post):
fig, (ax2) = plt.subplots(nrows=1)
triang = tri.Triangulation(x, ... | [
"# meshing with delaunay triangulation \ntriang = tri.Triangulation(x, y)\n\n# mask out invalid data \nmask = TriAnalyzer(triang).get_flat_tri_mask(min_circle_ratio=0.17, rescale=True) \ntriang.set_mask(mask)\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074345760_matplotlib_python.txt |
Q:
Subtract the highest value within row containing a pattern against the highest value of row not containing that pattern in Pandas
I have a dataframe such as:
Groups Name Value
G1 BLOC_Homo_sapiens 100
G1 BLOC_Chimpenzee 99
G1 BLOC_Bonobo 80
G1 Canis_lupus 20
G1 D... | Subtract the highest value within row containing a pattern against the highest value of row not containing that pattern in Pandas | I have a dataframe such as:
Groups Name Value
G1 BLOC_Homo_sapiens 100
G1 BLOC_Chimpenzee 99
G1 BLOC_Bonobo 80
G1 Canis_lupus 20
G1 Danio_rerio 10
G2 BLOC_Homo_sapiens 30
G2 BLOC_Bonobo 29
G2 Mus_musculus 28
G2 Cules_pupiens 2... | [
"You can use:\nm = df['Name'].str.contains('BLOC')\n\ndf['diff_length'] = (df.groupby('Groups')['Value']\n .transform(lambda d: d.where(m).max() - d.mask(m).max())\n )\n\nNB. this assumes unique indices.\nOutput:\n Groups Name Value diff_length\n0 G1 ... | [
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074349846_pandas_python.txt |
Q:
Python Selemiun find_element(By.CSS_SELECTOR
I'm trying to hit the button but it doesn't work
driver.find_element(By.CSS_SELECTOR, "input[type='submit']").click()
A:
Ty by xpath:
driver.find_element(By.XPATH, "//button[@type='submit']").click()
Or
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").cl... | Python Selemiun find_element(By.CSS_SELECTOR |
I'm trying to hit the button but it doesn't work
driver.find_element(By.CSS_SELECTOR, "input[type='submit']").click()
| [
"Ty by xpath:\ndriver.find_element(By.XPATH, \"//button[@type='submit']\").click()\n\nOr\ndriver.find_element(By.CSS_SELECTOR, \"button[type='submit']\").click()\n\n"
] | [
1
] | [] | [] | [
"css_selectors",
"python",
"selenium"
] | stackoverflow_0074350026_css_selectors_python_selenium.txt |
Q:
How to print n numbers from text file containg n numbers without repeating them?
Lets say I have text file containing n integers :
1
1
2
3
2
4
3
1
5
6
3
5
2
6
How to program a function to print those integers without repeating them?
My output should be :
1
2
3
4
5
6
Note : Output should not be a text file.
Note2... | How to print n numbers from text file containg n numbers without repeating them? | Lets say I have text file containing n integers :
1
1
2
3
2
4
3
1
5
6
3
5
2
6
How to program a function to print those integers without repeating them?
My output should be :
1
2
3
4
5
6
Note : Output should not be a text file.
Note2 : File contains n integers.
| [
"assuming that your integers live in a file named numbers.txt, you could do as follows:\nwith open('numbers.txt') as f: ... | [
2,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074349844_file_python.txt |
Q:
Setting a 2D PixelArray
pixel_array[:2,:2] = [[(0, 0, 0), (255, 0, 0)], [(0, 255, 0), (0, 0, 255)]]
ValueError: invalid color argument
Explanation:
I am trying to set a the pixels of a 2D slice of a PixelArray. In the example above, I want to set the top left four pixels. What am I doing wrong?
I've tried pygame... | Setting a 2D PixelArray | pixel_array[:2,:2] = [[(0, 0, 0), (255, 0, 0)], [(0, 255, 0), (0, 0, 255)]]
ValueError: invalid color argument
Explanation:
I am trying to set a the pixels of a 2D slice of a PixelArray. In the example above, I want to set the top left four pixels. What am I doing wrong?
I've tried pygame.Color instead of tuples, f... | [
"From Pygame issues - Setting a 2D PixelArray #3542\n\n\nYou are trying to set a 2D array to a 3D array\n\nNot really in this case. You can't set a 2D array of colours.\nDoing:\nmy_sub_array = my_array[:2, :2]\nprint(\"my_sub_array:\", my_sub_array)\n\nwill produce a 2x2 PixelArray of integer colours from a larger ... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074334655_pygame_python.txt |
Q:
How to pass the structure of a dictionary into a function
I am trying to pass a dictionary that was created automatically into a function that defines the scheme of a JSON.
This is my function:
def split_line_items(df_transactions):
for row in df_transactions.itertuples():
yield {
"... | How to pass the structure of a dictionary into a function | I am trying to pass a dictionary that was created automatically into a function that defines the scheme of a JSON.
This is my function:
def split_line_items(df_transactions):
for row in df_transactions.itertuples():
yield {
"count_0": row.count_0,
"count_1": row.count_1,... | [
"I guess you mean something like this, however the question is not very clear.\n# considering this is your tf_transactions \ntransactions = namedtuple('r',['count_0', 'count_1', 'count_2', 'total_count'])\ntf_transactions = [transactions(1,2,3,4), transactions(1,2,3,4)]\n\nfor row in tf_transactions:\n yield {... | [
1
] | [] | [] | [
"dictionary",
"function",
"json",
"python"
] | stackoverflow_0074349679_dictionary_function_json_python.txt |
Q:
Pandas DataFrame: Merge rows and keep only unique values from multiple rows as a list
I´m looking to merge rows by some id but the problem is that I want to keep the unique values from multiple rows as a list while only keeping the duplicates from multiple rows as a single element.
The raw data would look like som... | Pandas DataFrame: Merge rows and keep only unique values from multiple rows as a list | I´m looking to merge rows by some id but the problem is that I want to keep the unique values from multiple rows as a list while only keeping the duplicates from multiple rows as a single element.
The raw data would look like something like this:
| id | info1 | info2 | info3| info4|
| -- | ---- | ------| -----| -----|... | [
"Try this:\ndf.groupby('id').agg(pd.unique).applymap(lambda x: x[0] if len(x)==1 else x)\n\n info1 info2 info3\nid \n1 ['a', 'b'] xxx yyy\n2 'c' mmm nnn\n3 ['d', 'e'] uuu ooo\n\nUPDATE\nIn case of missing values, we need some little changes and more conditions... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074349298_python.txt |
Q:
TypeError: argument of type 'float' is not iterable (Python)
I would like to correct values in a df column based on results from another one.
This first line gives me the correct version of km based on another df named 'correction'.
df['km_correct'] = df['task_object'].map(correction.set_index('task_object')['km_c... | TypeError: argument of type 'float' is not iterable (Python) | I would like to correct values in a df column based on results from another one.
This first line gives me the correct version of km based on another df named 'correction'.
df['km_correct'] = df['task_object'].map(correction.set_index('task_object')['km_correct'])
Then I want to replace the current value of "km" with t... | [
"Are you applying correction_km on whole dataset?\ndf['km'] = df.apply(correction_km, axis=1)\n\nOr you just have to apply it into only km series like\ndf['km'] = df['km'].apply(correction_km, axis=1)\n\nSorry, I got this type of error before as well. I didn't have the dataset right now, so I am assuming maybe this... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074349908_dataframe_pandas_python.txt |
Q:
Python scrapy change csv cloumn name
Scrapy is indeed powerful. But it lakes a basic feature. When exporting to csv there is not way to change column name. By default it outputs the field name defined in Item. The item name should be python variables.
However, at times we need to output with human readable cloumn ... | Python scrapy change csv cloumn name | Scrapy is indeed powerful. But it lakes a basic feature. When exporting to csv there is not way to change column name. By default it outputs the field name defined in Item. The item name should be python variables.
However, at times we need to output with human readable cloumn names like person_name to Person Name
Is t... | [
"When using items, the field names have to adhere to python variable names syntax, but you can define the fields as well by overwriting the fields list in the constructor of the item class as below i.e. this will allow you to define field names containing characters such as spaces, full stops etc. which are not val... | [
1
] | [] | [] | [
"python",
"scrapy",
"scrapy_pipeline"
] | stackoverflow_0074346570_python_scrapy_scrapy_pipeline.txt |
Q:
Blender Python String manipulation
How do you remove all characters except the array of float values and sepparators(,)?
<Color (r=0.65, g=0.54, b=0.43)>
Into this: 0.65, 0.54, 0.43
A:
using regexps:
import re
nre = re.compile(r'*.(0\.\d\d).*(0\.\d\d).*(0\.\d\d)')
m = nre.match('<Color (r=0.65, g=0.54, b=0.43)>'... | Blender Python String manipulation | How do you remove all characters except the array of float values and sepparators(,)?
<Color (r=0.65, g=0.54, b=0.43)>
Into this: 0.65, 0.54, 0.43
| [
"using regexps:\nimport re\nnre = re.compile(r'*.(0\\.\\d\\d).*(0\\.\\d\\d).*(0\\.\\d\\d)')\nm = nre.match('<Color (r=0.65, g=0.54, b=0.43)>')\nprint(' ,'.join(m.groups()))\n==> 0.65 ,0.54 ,0.43\n\n",
"You can use regex like re.findall to extract all float numbers from the string then use str.join to add ', ' bet... | [
1,
0
] | [] | [] | [
"blender",
"python",
"string"
] | stackoverflow_0074350059_blender_python_string.txt |
Q:
How is SQLAlchemy's column documentation (Column.doc) actually used?
When creating a Column object with SQLAlchemy, you can specify a documentation string. Once set, how can this documentation be accessed in Python?
In addition, is using doc a good practise for documenting SQL Columns, or would it be better to use... | How is SQLAlchemy's column documentation (Column.doc) actually used? | When creating a Column object with SQLAlchemy, you can specify a documentation string. Once set, how can this documentation be accessed in Python?
In addition, is using doc a good practise for documenting SQL Columns, or would it be better to use comment or perhaps Sphinx's standard for documenting general instance var... | [
"The doc parameter creates python docstrings for classes and fields of your ORM (see also the PEP 257). You can access them through the __doc__ attribute or through the built-in help() function. Probably some IDEs will use them for hints as well.\nSee this answer for some examples.\n"
] | [
2
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0053626191_python_sqlalchemy.txt |
Q:
loop while and look of the program in python
I am writing a program rock-paper-scissors and I have a problem with a loop while which I solved with another loop if but I still wonder why it doesn't work(line 19, 71, 104; or just in functions game, game2, game3). I also want to ask if I can write this program better... | loop while and look of the program in python | I am writing a program rock-paper-scissors and I have a problem with a loop while which I solved with another loop if but I still wonder why it doesn't work(line 19, 71, 104; or just in functions game, game2, game3). I also want to ask if I can write this program better or use something more advance to write it shorter... | [
"Generally you are not making functions that are flexible enough to change. You should think about how you can re-use components to reduce repetition. On that note, you are also not making enough functions and repeating a lot of logic.\nFor example, to count down from a number you could write:\ndef print_countdown(... | [
3
] | [
"Here is how I would do a rock paper scissors game:\nimport random\n\noptions = [\"rock\", \"paper\", \"scissors\"]\nyour_score = 0\ncomputer_score = 0\nmax_score = 3\nplaying = True\n\nwhile playing:\n your_option = input(f\"Options:\\n - {options[0]}\\n - {options[1]}\\n - {options[2]}\\nYour option: \")\n ... | [
-1
] | [
"loops",
"python",
"while_loop"
] | stackoverflow_0074349792_loops_python_while_loop.txt |
Q:
How do you create a boolean mask for a tensor in Keras?
I am building a custom metric to measure the accuracy of one class in my multi-class dataset during training. I am having trouble selecting the class.
The targets are one hot (e.g: the class 0 label is [1 0 0 0 0]):
from keras import backend as K
def single... | How do you create a boolean mask for a tensor in Keras? | I am building a custom metric to measure the accuracy of one class in my multi-class dataset during training. I am having trouble selecting the class.
The targets are one hot (e.g: the class 0 label is [1 0 0 0 0]):
from keras import backend as K
def single_class_accuracy(y_true, y_pred):
idx = bool(y_true[:, 0])... | [
"Note that when talking about the accuracy of one class one may refer to either of the following (not equivalent) two amounts:\n\nThe recall, which, for class C, is the ratio of examples labelled with class C that are predicted to have class C.\nThe precision, which, for class C, is the ratio of examples predicted ... | [
23,
0
] | [] | [] | [
"keras",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0041458859_keras_neural_network_python_tensorflow.txt |
Q:
Spark/Python Dataframe - Transpose rows to columns
I have a sample data as shown below
ProductionDate
CostCenterKey
AEMainCategoryKey
AELossMagnitude
1/1/2022
100030
OAE
84.94871412
1/1/2022
100030
Overdeclared
-0.010897228
1/1/2022
100030
UL
15.06218311
1/1/2022
100040
OAE
49.99603575
1/1/2022
100040
UL
50.... | Spark/Python Dataframe - Transpose rows to columns | I have a sample data as shown below
ProductionDate
CostCenterKey
AEMainCategoryKey
AELossMagnitude
1/1/2022
100030
OAE
84.94871412
1/1/2022
100030
Overdeclared
-0.010897228
1/1/2022
100030
UL
15.06218311
1/1/2022
100040
OAE
49.99603575
1/1/2022
100040
UL
50.00001425
1/1/2022
100040
Undeclared
0.00395... | [
"From original format\n ProductionDate CostCenterKey AEMainCategoryKey AELossMagnitude\n0 1/1/22 100030 OAE 84.948714\n1 1/1/22 100030 Overdeclared -0.010897\n2 1/1/22 100030 UL 15.062183\n3 1/1/22 ... | [
0
] | [] | [] | [
"apache_spark_sql",
"python",
"sql_server"
] | stackoverflow_0074349418_apache_spark_sql_python_sql_server.txt |
Q:
Pandera columns joint uniqueness
I need to check a data frame for joint uniqueness of similar columns.
In the documentation I have found this code snippet but it is applicable only to DataFrameSchema.
import pandas as pd
import pandera as pa
schema = pa.DataFrameSchema(
columns={col: pa.Column(int) for col in... | Pandera columns joint uniqueness | I need to check a data frame for joint uniqueness of similar columns.
In the documentation I have found this code snippet but it is applicable only to DataFrameSchema.
import pandas as pd
import pandera as pa
schema = pa.DataFrameSchema(
columns={col: pa.Column(int) for col in ["a", "b", "c"]},
unique=["a", "c... | [
"I believe the unique keyword is what you're looking for, but the example in the docs is not particularly helpful in pointing out the difference between the schema-level and column-level check.\nSecondly, DataFrameSchema's are for this use-case interchangeable with a SchemaModel. The example below uses your example... | [
0
] | [] | [] | [
"pandas",
"pandera",
"python",
"validation"
] | stackoverflow_0074226965_pandas_pandera_python_validation.txt |
Q:
Comma and Tab separated file into a dictionary in python
I have this data set, I need to have put it in a dictionary that gives me like this {'1: xx, xx', '2:xx, xx'} etc what can i possibly do to achieve that as i need to remove the word bag, weight and value, Thanks in advance an i appreciate the help.
bag 1:
... | Comma and Tab separated file into a dictionary in python | I have this data set, I need to have put it in a dictionary that gives me like this {'1: xx, xx', '2:xx, xx'} etc what can i possibly do to achieve that as i need to remove the word bag, weight and value, Thanks in advance an i appreciate the help.
bag 1:
weight: 9.4
value: 57
bag 2:
weight: 7.4
value: 94
bag... | [
"I think this should do,\ndata = {}\n\nwith open('data.txt', 'r') as f:\n recentDict = {}\n recentindex = 0\n for line in f.readlines():\n if 'bag ' in line:\n recentindex = line.split('bag ')[1].split(\":\")[0]\n if 'weight' in line:\n weight = line.split(\"weight: \")[... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074348900_dictionary_python.txt |
Q:
Pandas: start a new group on every non-NA value
I am looking for a method to create an array of numbers to label groups, based on the value of the 'number' column. If it's possible?
With this abbreviated example DF:
number = [nan,nan,1,nan,nan,nan,2,nan,nan,3,nan,nan,nan,nan,nan,4,nan,nan]
df = pd.DataFrame(column... | Pandas: start a new group on every non-NA value | I am looking for a method to create an array of numbers to label groups, based on the value of the 'number' column. If it's possible?
With this abbreviated example DF:
number = [nan,nan,1,nan,nan,nan,2,nan,nan,3,nan,nan,nan,nan,nan,4,nan,nan]
df = pd.DataFrame(columns=['number'])
df = pd.DataFrame.assign(df, number=num... | [
"You can use notna combined with cumsum:\ndf['group'] = df['number'].notna().cumsum()\n\nNB. if you had zeros: df['group'] = df['number'].ne(0).cumsum().\noutput:\n number group\n0 NaN 0\n1 NaN 0\n2 1.0 1\n3 NaN 1\n4 NaN 1\n5 NaN 1\n6 2.0 2\n... | [
1,
1
] | [] | [] | [
"group",
"pandas",
"python"
] | stackoverflow_0074350066_group_pandas_python.txt |
Q:
count (how to find all letters, and count them)
How to make = 2(there are two "the")
import re
text = "there are a lot of the cats"
o = re.findall("the", text)
print(o)
def text(word):
count = 0
for word in text:
if "ou" in text:
count += 1
return count
print(count)
print(i)
thi... | count (how to find all letters, and count them) | How to make = 2(there are two "the")
import re
text = "there are a lot of the cats"
o = re.findall("the", text)
print(o)
def text(word):
count = 0
for word in text:
if "ou" in text:
count += 1
return count
print(count)
print(i)
this code should return 2 (because there are 2 "the")
| [
"@chris is is right. You are successfully doing it on line 3 and 4, but line 4 returns it in an array ['the', 'the']. In python you can get the 'length' of an array/list (how many things are in it) with len(yourArrayHere).\nSo if you want to just see the count you can do:\nprint(len(o))\n\nif you want to save it to... | [
0
] | [
"If you want to get all words and count them here is the code:\ntext = input(\"Your text: \")\nwords_in_text = {}\nfor word in text.lower().split(\" \"):\n if word in words_in_text.keys():\n words_in_text[word] += 1\n else:\n words_in_text[word] = 1\n\nTo get a number of words simply use:\nword_... | [
-1
] | [
"count",
"python"
] | stackoverflow_0074350079_count_python.txt |
Q:
A function that opens a file and when it finds a certain string it returns a dictionary x next values after that
Im trying to build a program that does stock-analys.
I have a file that contains a string (the company name) followed by a lot of values.
I want my function to open the txt file and read trough it until... | A function that opens a file and when it finds a certain string it returns a dictionary x next values after that | Im trying to build a program that does stock-analys.
I have a file that contains a string (the company name) followed by a lot of values.
I want my function to open the txt file and read trough it until it find the given variable name e.x "Apple", and then it should return a dictonary of the 30 next values after.
E.g i... | [
"create a variable that indicates if you've reached the company name - found (value False) then go through the lines of the file, if line == company_name change the value of found to True\nonce the company name is reached, (you will move to elif Found) now you will check if the row starts with a date (format year-... | [
0,
0
] | [] | [] | [
"dictionary",
"file",
"python",
"sorting"
] | stackoverflow_0074349552_dictionary_file_python_sorting.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.