content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to use two variable types in a pydantic.BaseModel with typing.Union? I need my model to accept either a bytes type variable or a string type variable and to raise an exception if any other type was passed. from typing import Union from pydantic import BaseModel class MyModel(BaseModel): a: Union[bytes, s...
How to use two variable types in a pydantic.BaseModel with typing.Union?
I need my model to accept either a bytes type variable or a string type variable and to raise an exception if any other type was passed. from typing import Union from pydantic import BaseModel class MyModel(BaseModel): a: Union[bytes, str] m1 = MyModel(a='123') m2 = MyModel(a=b'123') print(type(m1.a)) print(t...
[ "The problem you are facing is that the str type does some automatic conversions (here in the docs):\n\nstrings are accepted as-is, int float and Decimal are coerced using str(v), bytes and bytearray are converted using v.decode(), enums inheriting from str are converted using v.value, and all other types cause an ...
[ 2 ]
[]
[]
[ "pydantic", "python", "python_typing" ]
stackoverflow_0074460495_pydantic_python_python_typing.txt
Q: django migrations - workflow with multiple dev branches I'm curious how other django developers manage multiple code branches (in git for instance) with migrations. My problem is as follows: - we have multiple feature branches in git, some of them with django migrations (some of them altering fields, or removing t...
django migrations - workflow with multiple dev branches
I'm curious how other django developers manage multiple code branches (in git for instance) with migrations. My problem is as follows: - we have multiple feature branches in git, some of them with django migrations (some of them altering fields, or removing them altogether) - when I switch branches (with git checkout s...
[ "Migrations rollback are possible and usually handled automatically by django.\nConsidering the following model:\nclass MyModel(models.Model):\n pass\n \n\nIf you run python manage.py makemigrations myapp, it will generate the initial migration script.\nYou can then run python manage.py migrate myapp 0001 to ...
[ 25, 10, 1, 1 ]
[]
[]
[ "django", "git", "migration", "python" ]
stackoverflow_0032682293_django_git_migration_python.txt
Q: how to set query for show followed posts in home page I want to make query to show all followed posts in the main page, could you help me in doing this? Here's my file models.py: class Relation(models.Model): from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') to_user = m...
how to set query for show followed posts in home page
I want to make query to show all followed posts in the main page, could you help me in doing this? Here's my file models.py: class Relation(models.Model): from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_na...
[ "checkout this code:\nfollowed_people = Relation.objects.filter(from_user=request.user).values('to_user')\n posts = Post.objects.filter(\n user__in=followed_people\n ) | Post.objects.filter(user=request.user)\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0074460496_django_django_models_django_views_python.txt
Q: get data from multiple csv file and print Highest, Lowest day weather with Humid from any year and also print month name and day in python Hi everyone. I have multiple CSV files I am creating a weatherman app in python. I am getting data from CSV files and here is the code import os import csv lst_temp = [] lst_h...
get data from multiple csv file and print Highest, Lowest day weather with Humid from any year and also print month name and day in python
Hi everyone. I have multiple CSV files I am creating a weatherman app in python. I am getting data from CSV files and here is the code import os import csv lst_temp = [] lst_hum = [] dates = [] class Weather: def main(self): path = r'C:\Users\someone\PycharmProjects\untitled\weatherfiles\\' os....
[ "You might want to use pandas to parse data files.\nAssuming the column names are the same throughout your .txt files:\nimport pandas as pd\n\ndata = pd.read_csv(filepath, sep=',', parse_dates=['PKT'])\n\nAfter that, you can retrieve the index of the max temperature using .idxmax() like so:\nmax_i = df['Max Tempera...
[ 0 ]
[]
[]
[ "csv", "extract", "python", "python_3.x" ]
stackoverflow_0074460315_csv_extract_python_python_3.x.txt
Q: SQLAlchemy add_all() inserting not working I have my Flask API endpoint that doesn't to be saving all the information from for loop The endpoint uploads multiple images. All is working fine, i.e the images are being uploaded however when it comes to inserting the names to the database, no record(file name/url) is ...
SQLAlchemy add_all() inserting not working
I have my Flask API endpoint that doesn't to be saving all the information from for loop The endpoint uploads multiple images. All is working fine, i.e the images are being uploaded however when it comes to inserting the names to the database, no record(file name/url) is being inserted. Endpoint: def upload_images(args...
[ "For those looking at this for a solution, here is my final edit. The code needed some indenting of the functions for it to work well.\nfiles = request.files.getlist('image_name')\n for file in files:\n if file and allowed_file(file.filename):\n image_id = str(uuid.uuid4())\n filenam...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074155101_python_sqlalchemy.txt
Q: Python, ThreadPoolExecutor, pool execution doesnt terminate I have got I simple code modelling a more complicated problem I am to solve. Here I have 3 funcs- worker, task submitter (seek tasks and put it to queue once it gets new ones) and function creating a pool and adding new tasks to this pool. But the code ...
Python, ThreadPoolExecutor, pool execution doesnt terminate
I have got I simple code modelling a more complicated problem I am to solve. Here I have 3 funcs- worker, task submitter (seek tasks and put it to queue once it gets new ones) and function creating a pool and adding new tasks to this pool. But the code doesnt happen to finish the run after queue gets empty and all th...
[ "It doesn't terminate because you are trying to remove an item from an empty queue. The problem is here:\nwhile not execution_finished: \n if not all([task.done() for task in tasks]):\n print(' still in progress .....................')\n tasks.append(executor....
[ 0 ]
[]
[]
[ "concurrency", "multithreading", "python", "python_multithreading", "threadpoolexecutor" ]
stackoverflow_0074456840_concurrency_multithreading_python_python_multithreading_threadpoolexecutor.txt
Q: Ursina engine not rendering mesh properly? i am creating a small game using Ursina and i have code which generates a terrain mesh using perlin noise. the mesh itself renders but i can't put textures on it properly and shaders do not work on it, it just renders as a solid colour. screenshot of the game - terrain is...
Ursina engine not rendering mesh properly?
i am creating a small game using Ursina and i have code which generates a terrain mesh using perlin noise. the mesh itself renders but i can't put textures on it properly and shaders do not work on it, it just renders as a solid colour. screenshot of the game - terrain is all one colour and not shaded here's my code ` ...
[ "How should the texture map to the model? You have to define this by giving it uvs.\n\nUVs are two-dimensional texture coordinates that correspond with the\nvertex information for your geometry. UVs are vital because they\nprovide the link between a surface mesh and how an image texture gets\napplied onto that surf...
[ 0 ]
[]
[]
[ "game_development", "python", "rendering", "ursina" ]
stackoverflow_0074460669_game_development_python_rendering_ursina.txt
Q: get the miniumum value in pandas vectorization I'm creating a column which is based on 2 other columns but also has an extra condition: df['C'] = min((df['B'] - df['A']) , 0) The new column is the subtraction of A and B, but if the value is negative it has to be 0. The above function does not work unfortunately. C...
get the miniumum value in pandas vectorization
I'm creating a column which is based on 2 other columns but also has an extra condition: df['C'] = min((df['B'] - df['A']) , 0) The new column is the subtraction of A and B, but if the value is negative it has to be 0. The above function does not work unfortunately. Can anyone help?
[ "You could use df.clip to set a lower bound for the data (i.e. any data below 0 to show as 0):\ndf['C'] = (df['B'] - df['A']).clip(lower=0)\n\nNote: If you don't want any negatives, your original idea should use max rather than min. A negative would be < 0, it would keep the negative. You'd end up replacing all pos...
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074460758_pandas_python.txt
Q: how to create a tags in azure disk using python? I want to add or create a new tag in Azure Disk using python but not able to do anyone please help me with python sdk/code for this. for disk in compute_client.disks.list(): if disk.as_dict()["name"] == "test_disk_rohit": tags = target_disk.tags["DetachedTi...
how to create a tags in azure disk using python?
I want to add or create a new tag in Azure Disk using python but not able to do anyone please help me with python sdk/code for this. for disk in compute_client.disks.list(): if disk.as_dict()["name"] == "test_disk_rohit": tags = target_disk.tags["DetachedTime"] = datetime.now() compute_client.disks.begin...
[ "Instead of using begin_create_or_update you can use create_or_update.\nI have followed the below code snippet I can be able to create/update the tags in desk\nAZURE_TENANT_ID= '<Tenent ID>'\nAZURE_CLIENT_ID='<Client ID>'\nAZURE_CLIENT_SECRET='<Client Secret>'\nAZURE_SUBSCRIPTION_ID='<Sub_ID>'\n\ncredentials = Serv...
[ 0 ]
[]
[]
[ "azure", "python" ]
stackoverflow_0074440190_azure_python.txt
Q: Error using simoid activation function in the last dense layer of a LSTN Trying to use sigmoid as an activation function for the last dense layer of an LSTN, I get this error ValueError: `logits` and `labels` must have the same shape, received ((None, 60, 1) vs (None,)). The code is this scaler = StandardScaler()...
Error using simoid activation function in the last dense layer of a LSTN
Trying to use sigmoid as an activation function for the last dense layer of an LSTN, I get this error ValueError: `logits` and `labels` must have the same shape, received ((None, 60, 1) vs (None,)). The code is this scaler = StandardScaler() X_train_s = scaler.fit_transform(X_train) #scaled_train X_test_s = scaler.tr...
[ "Found the cause of the trouble after several attempts, as Dr. Snoopy said in a previous remark, it was in the layer before the last one: it shall have no \"return_sequences=True\" set, that is for all the layers before if the last one is a dense layer for binary classification using sigmoid as activation function....
[ 0 ]
[]
[]
[ "neural_network", "numpy", "pandas", "python" ]
stackoverflow_0074445524_neural_network_numpy_pandas_python.txt
Q: Combining Restapi and Websockets I have a rest api server which makes call to some other Apis,I am accessing the data I get from the server on a react js frontend,But for certain usecases I need to fetch real time data from backed,is there any way do this together,below is my code from flask import Flask,request f...
Combining Restapi and Websockets
I have a rest api server which makes call to some other Apis,I am accessing the data I get from the server on a react js frontend,But for certain usecases I need to fetch real time data from backed,is there any way do this together,below is my code from flask import Flask,request from flask_cors import CORS from tuya_c...
[ "Websockets endpoints are exactly what you're looking for. If that is not too late, I'd recommend switching to FastAPI which supports WebSockets \"natively\" (out-of-the-box) - https://fastapi.tiangolo.com/advanced/websockets\nIf you need to keep using Flask, there are a few packages that allow you to add WebSocket...
[ 0 ]
[]
[]
[ "flask", "python", "websocket" ]
stackoverflow_0074450622_flask_python_websocket.txt
Q: Pyomo cannot find ipopt in Linux even though it's installed I'm using Kali Linux and I needed to install ipopt to use with pyomo in Python which I'm currently learning. I have tried several things and none of them have worked with trying to run ipopt in pyomo. First, following their official website's instructions...
Pyomo cannot find ipopt in Linux even though it's installed
I'm using Kali Linux and I needed to install ipopt to use with pyomo in Python which I'm currently learning. I have tried several things and none of them have worked with trying to run ipopt in pyomo. First, following their official website's instructions did not work (https://coin-or.github.io/Ipopt/INSTALL.html) for ...
[ "Hey I also faced this problem. I was running my script in remote HPC with Linux system.\nHowever, when I use command to execute the file, it works and solve the model very well. When I use pycharm run the script, it doesn't work, showing that the solver can not be located.\nThats super strange\n" ]
[ 0 ]
[]
[]
[ "ipopt", "optimization", "pyomo", "python" ]
stackoverflow_0071454400_ipopt_optimization_pyomo_python.txt
Q: Searching for keyword combinations in pandas dataframe for classification This is a follow up question to Searching for certain keywords in pandas dataframe for classification. I have a list of keywords based on which I want to categorize the job description. Here are input file, example keywords and code job_desc...
Searching for keyword combinations in pandas dataframe for classification
This is a follow up question to Searching for certain keywords in pandas dataframe for classification. I have a list of keywords based on which I want to categorize the job description. Here are input file, example keywords and code job_description Managing engineer is responsible for This job entails assisting to Engi...
[ "I think you are missing a comma in your cat_dict dictionary. I tried your example:\nimport pandas as pd\n\ncat_dict = {\n \"manager\": [\"manager\", \"president\", \"management\", \"managing\"],\n \"assistant\": [\"assistant\", \"assisting\", \"customer specialist\"],\n \"engineer\": [\"engineer\", \"engi...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074460677_pandas_python.txt
Q: select_set() method of Listbox tkinter widget in Python enables multiple selections even selectionmode is set to BROWSE I am working with Python 3.10.5 64bit and a strange behavior regarding the listboy widget of the tkinter modul. Look at the following code: import tkinter as tk root = tk.Tk() cities = ['New Yo...
select_set() method of Listbox tkinter widget in Python enables multiple selections even selectionmode is set to BROWSE
I am working with Python 3.10.5 64bit and a strange behavior regarding the listboy widget of the tkinter modul. Look at the following code: import tkinter as tk root = tk.Tk() cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico'] list_source = tk.StringVar(value=cities) lst_cities = tk.Listbox( master=ro...
[ "According to the help on selection_set():\nselection_set(self, first, last=None)\n Set the selection from FIRST to LAST (included) without\n changing the currently selected elements.\n\ncurrently selected elements are not affected.\nSo you need to clear current selections using selection_clear() (or select_c...
[ 1, 0 ]
[]
[]
[ "listbox", "python", "tkinter" ]
stackoverflow_0074457532_listbox_python_tkinter.txt
Q: I'm receiving a NetworkX related error on Memgraph startup When I start Memgraph I can't access query modules. Right after the startup, I get ImportError for the NetworkX module. I've checked and I can see that I have NetworkX installed. I've also tried to reinstall Mmegraph but I had no luck. The error is still t...
I'm receiving a NetworkX related error on Memgraph startup
When I start Memgraph I can't access query modules. Right after the startup, I get ImportError for the NetworkX module. I've checked and I can see that I have NetworkX installed. I've also tried to reinstall Mmegraph but I had no luck. The error is still there.
[ "This is most likely due to the Python version. Memgraph is using the default system Python.\nCheck the Python version with python --version. If you don't run Python 3, upgrade it. With python3 there shouldn't be such problems.\n" ]
[ 0 ]
[]
[]
[ "memgraphdb", "networkx", "python" ]
stackoverflow_0074461034_memgraphdb_networkx_python.txt
Q: AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK' So recently I had to reinstall python due to corrupt executable. This made one of our python scripts bomb with the following error: AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK' The line of code that caused i...
AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK'
So recently I had to reinstall python due to corrupt executable. This made one of our python scripts bomb with the following error: AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK' The line of code that caused it to bomb was: from apiclient.discovery import build I tried pip uninstalling an...
[ "Edit the crypto.py file and remove the offending line by commenting it out with a #\nThen upgrade latest version of PyOpenSSL.\npip install pip --upgrade\npip install pyopenssl --upgrade\n\nNow you can re-add the commented line again and it should be working\n", "on my ubuntu \"20.04.5\" I manage solving the err...
[ 39, 4, 2, 2, 0, 0, 0 ]
[]
[]
[ "google_analytics_api", "python" ]
stackoverflow_0073830524_google_analytics_api_python.txt
Q: Delete dictionary from JSON based on condition in Value - Python I have JSON as follows dict =[ {'name':'Test01-Serial01' }, {'name':'Tests04-Serial04' } ] First I wanted to separate the name with - and then with the index 0 that is Test01 I wanted to delete the dictionary which don't follow the rule in name Rule...
Delete dictionary from JSON based on condition in Value - Python
I have JSON as follows dict =[ {'name':'Test01-Serial01' }, {'name':'Tests04-Serial04' } ] First I wanted to separate the name with - and then with the index 0 that is Test01 I wanted to delete the dictionary which don't follow the rule in name Rule: 4 Digit Word 2 Digit Number Here Tests04 doesn't follow 4 Digit Word...
[ "Write a function that validates the value according to your rules. Reconstruct the original list with a list comprehension.\nfrom string import ascii_letters, digits\n\n\ndef isvalid(s):\n return len(s) == 6 and all(c in ascii_letters for c in s[:4]) and all(c in digits for c in s[4:])\n\n\n_list = [\n {'nam...
[ 1, 1 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0074460676_dictionary_json_python.txt
Q: how do I insert a row for under a specific cell value I have a dataframe below and I want to insert a new row under shop with values, how do I do that ? values = 0.2, park, false df1 = number variable values 1 NaN bank True 2 3.0 shop False 3 0.5 market True 4 NaN g...
how do I insert a row for under a specific cell value
I have a dataframe below and I want to insert a new row under shop with values, how do I do that ? values = 0.2, park, false df1 = number variable values 1 NaN bank True 2 3.0 shop False 3 0.5 market True 4 NaN government True 5 1.0 hotel true
[ "You can try:\nimport pandas as pd\n\ndf = pd.DataFrame({'number': [float('NaN'), 3.0, 0.5, float('NaN'), 1.0], 'variable':['bank','shop','market','government','hotel'], 'values':[True, False, True, True, True]})\nprint(\"----- ORIGINAL ------\")\nprint(df)\nshop_index = df.reset_index()['variable'].tolist().index(...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074459369_pandas_python.txt
Q: Pytorch How do you implement Hadamard (element-wise) products within nn.Module, safely? I need to write an nn.Module class with layers that feed into one another. I need to perform an element-wise product on some of the results of my layers, but (emphasis) I do not need a parametrized layer that does that. I ne...
Pytorch How do you implement Hadamard (element-wise) products within nn.Module, safely?
I need to write an nn.Module class with layers that feed into one another. I need to perform an element-wise product on some of the results of my layers, but (emphasis) I do not need a parametrized layer that does that. I need to place it somehow between several parametrized layers. How can I implement an element-...
[ "Have you checked out the torch.mul function (https://pytorch.org/docs/stable/generated/torch.mul.html)? This will perform the hadamard product for two inputs of equal size (for unequal sizes broadcasting will be used).\nAs per usual, executing this function on tensors for whom requires_grad=True, gradients will be...
[ 0 ]
[]
[]
[ "machine_learning", "python", "pytorch" ]
stackoverflow_0074243005_machine_learning_python_pytorch.txt
Q: _tkinter.TclError: bad window path name when closing window I've made a tk.Toplevel class to get a date from the user. After the user clicked the date, the window is closing and the date should return to the mainprocess. When the tk.Toplevel is closed I've got the date, but also an error: \_tkinter.TclError: bad w...
_tkinter.TclError: bad window path name when closing window
I've made a tk.Toplevel class to get a date from the user. After the user clicked the date, the window is closing and the date should return to the mainprocess. When the tk.Toplevel is closed I've got the date, but also an error: \_tkinter.TclError: bad window path name ".!kalender.!dateentry.!toplevel" What did I do w...
[ "It is because when the user has selected a date in the pop-up calendar, the bind function self.close_window() will be executed and the toplevel is destroyed (so is the DateEntry widget). Then DateEntry widget closes the pop-up calendar which raises the exception.\nTo fix this, you can delay the execution of self.c...
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074459096_python_tkinter.txt
Q: Context manager: Error handling inside __init__ method A bit of context I am working with a package that allows you to calculate several things about planets (such as their speed, or position), using information stored in files. The package includes methods to load, and unload files, so its basic usage would look ...
Context manager: Error handling inside __init__ method
A bit of context I am working with a package that allows you to calculate several things about planets (such as their speed, or position), using information stored in files. The package includes methods to load, and unload files, so its basic usage would look like this: load(["File_1", "File_2"]) try: function() ...
[ "You can wrap your original code using contextlib.contextmanager.\nfrom contextlib import contextmanager\n\n@contextmanager\ndef file_manager(file_list):\n try:\n load(file_list)\n yield None # after this the code inside the with block is executed \n finally:\n # this is called when the ...
[ 4 ]
[]
[]
[ "contextmanager", "python" ]
stackoverflow_0074460663_contextmanager_python.txt
Q: Socket Connection Refused [Errno 111] I am trying to implement a simple ftp with sockets using C (server side) and Python (client side). When the server code is compiled and run, the user enters a port number. The client then enters "localhost " when compiling. For some reason I am getting [Errno 111] on the clien...
Socket Connection Refused [Errno 111]
I am trying to implement a simple ftp with sockets using C (server side) and Python (client side). When the server code is compiled and run, the user enters a port number. The client then enters "localhost " when compiling. For some reason I am getting [Errno 111] on the client side when I run the code. It is saying th...
[ "Sometimes localhost isn't working on host\nChange this\nserverName = 127.0.0.1\n\n" ]
[ 0 ]
[ "Try to change the serverName variable to 127.0.0.1.\n" ]
[ -1 ]
[ "python", "sockets" ]
stackoverflow_0035817295_python_sockets.txt
Q: Fill oceans in high resolution to hide low resolution contours in basemap When plotting low-resolution contours over a high-resolution coastline I get the following result I would like to fill the area outside of the coastlines (caused by the low resolution of the underlining filled contour plot) with the ocean c...
Fill oceans in high resolution to hide low resolution contours in basemap
When plotting low-resolution contours over a high-resolution coastline I get the following result I would like to fill the area outside of the coastlines (caused by the low resolution of the underlining filled contour plot) with the ocean color at high resolution. I tried to use the land-sea mask option without colori...
[ "I ended up using the solution posted in Fill oceans in basemap adapted to my needs. Note that, in order to retain the lakes, I had to do multiple passes of fillcontinents, so that's how I did\n# extents contain the projection extents as [lon1, lon2, lat1, lat2]\nm = Basemap(projection='merc',\n llcr...
[ 2 ]
[]
[]
[ "matplotlib_basemap", "python", "shapefile" ]
stackoverflow_0074433797_matplotlib_basemap_python_shapefile.txt
Q: binary_crossentrophy vs categorical_crossentropy I have a dataset with 10 categorical features and one output feature with class 0 and 1. X_train follows a 3D array so I have done label encoding beforehand on the dataset. I have applied categorical_crossentrophy but I am getting 26% accuracy with activation functi...
binary_crossentrophy vs categorical_crossentropy
I have a dataset with 10 categorical features and one output feature with class 0 and 1. X_train follows a 3D array so I have done label encoding beforehand on the dataset. I have applied categorical_crossentrophy but I am getting 26% accuracy with activation function sigmoid. When I apply binary_crossentrophy, the acc...
[ "If you want to predict 10 different classes, you will need to use the categorical_crossentropy. The final output layer must have 10 units with the softmax activation function. The binary_crossentrophy is for binary classification like cat and dog, or yes or no.\n" ]
[ 0 ]
[]
[]
[ "cross_entropy", "python" ]
stackoverflow_0071275268_cross_entropy_python.txt
Q: Cannot set a Categorical with another, without identical categories. Replace almost identical categories I have the following dataframe np.random.seed(3) s = pd.DataFrame((np.random.choice(['Feijão','feijão'],size=[3,2])),dtype='category') print(s[0].cat.categories) print(s[1].cat.categories) As you can see the...
Cannot set a Categorical with another, without identical categories. Replace almost identical categories
I have the following dataframe np.random.seed(3) s = pd.DataFrame((np.random.choice(['Feijão','feijão'],size=[3,2])),dtype='category') print(s[0].cat.categories) print(s[1].cat.categories) As you can see the dataframe is basically two similar strings with one letter in uppercase. What I am trying to do is replace t...
[ "Use DataFrame.update:\ns.update( s.loc[s[0].isin(['feijão']),1].replace({'feijão':'Feijão'}))\nprint (s)\n 0 1\n0 Feijão Feijão\n1 feijão Feijão\n2 Feijão Feijão\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074461116_pandas_python.txt
Q: intersection and union set between two lists base on data frame a = {'A' : [1,2,3,4], 'B' : [[1,4,5,6],[2,3,6],[4,5,6]], 'C' : [[1,4,6],[3,5],[4,10],[10]] } Base on dataframes: How to find the intersection and union set between column B and C? the output like that: A B C intersect ...
intersection and union set between two lists base on data frame
a = {'A' : [1,2,3,4], 'B' : [[1,4,5,6],[2,3,6],[4,5,6]], 'C' : [[1,4,6],[3,5],[4,10],[10]] } Base on dataframes: How to find the intersection and union set between column B and C? the output like that: A B C intersect union 0 1 [1,4,5,6] [1,4,6] [1,4,6] [1,4,5,6] 1 ...
[ "You can define a custom function that returns two values at a time and apply that function rowwise.\ndef func(row):\n inters = list(set(row['B']).intersection(row['C']))\n uni = list(set(row['B']).union(row['C']))\n return inters, uni\n\na[['intersect', 'union']] = a.apply(func, axis=1, result_type='expan...
[ 1 ]
[]
[]
[ "dataframe", "intersection", "list", "python" ]
stackoverflow_0074461000_dataframe_intersection_list_python.txt
Q: Faster method of copying bounding box content onto canvas with numpy I have an image with several detections with bounding boxes that overlap. I want to be able to extract different combinations of overlapping boxes onto a blank canvas, then save it as an image. To visualise, if there are detections like this: I ...
Faster method of copying bounding box content onto canvas with numpy
I have an image with several detections with bounding boxes that overlap. I want to be able to extract different combinations of overlapping boxes onto a blank canvas, then save it as an image. To visualise, if there are detections like this: I want to be able to test boxes 1+2, 1+3, 2+3 with the box not included set ...
[ "Loop time is dominated by the np.full (~500 ms) and the .copy() (100 ms).\nThe actual calculations cost four orders of magnitude less time.\nYou introduced the .copy() operation purely for the time measurement, so your measurement method disturbed the thing you tried to measure.\nYou also included constant setup c...
[ 2 ]
[]
[]
[ "numpy", "optimization", "profiling", "python" ]
stackoverflow_0074459739_numpy_optimization_profiling_python.txt
Q: Regex to find multiline comments in Python that contain a certain word How can I define a regex to find multiline comments in python that contain the word "xyz". Example for a string that should match: """ blah blah blah xyz blah blah """ I tried this regex: """((.|\n)(?!"""))*?xyz(.|\n)*?""" (grep -i -Pz '"""((....
Regex to find multiline comments in Python that contain a certain word
How can I define a regex to find multiline comments in python that contain the word "xyz". Example for a string that should match: """ blah blah blah xyz blah blah """ I tried this regex: """((.|\n)(?!"""))*?xyz(.|\n)*?""" (grep -i -Pz '"""((.|\n)(?!"""))?xyz(.|\n)?"""') but it was not good enough. for example, for th...
[ "The main challenge is keeping the \"\"\" ... \"\"\" balance of inside and outside a comment.\nHere an idea with PCRE (e.g. PyPI regex with Python) or grep -Pz (like in your example).\n(?ims)^\"\"\"(?:(?:[^\"]|\"(?!\"\"))*?(xyz))?.*?^\"\"\"(?(1)|(*SKIP)(*F))\n\nSee this demo at regex101 (used with i ignorecase, m m...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074459864_python_regex.txt
Q: Visual C++ redist not detected by command line When trying to install discord.py, I keep getting this error: error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ Even though I have Visual C++, I installed the ...
Visual C++ redist not detected by command line
When trying to install discord.py, I keep getting this error: error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ Even though I have Visual C++, I installed the things in build tools, and I added C:\Program Files ...
[ "I previously had this issue, to solve it you need to head to the link provided. Afterwards, open up the file (should be called vs_BuildTools) that was given to you. You should see a menu appear with multiple options (see image).\nThe solution is to click the Desktop development with C++ as checked and install (bot...
[ 0 ]
[]
[]
[ "discord.py", "python", "visual_c++", "windows" ]
stackoverflow_0074454466_discord.py_python_visual_c++_windows.txt
Q: Telethon Telegram workers are too busy to respond immediately (caused by SendMultiMediaRequest) warning I'm getting this warning every time when my reposter sends a post from one channel to another and this post contains more than 8 media files. If it has more than 8, it will divide my post: first post - 8 media f...
Telethon Telegram workers are too busy to respond immediately (caused by SendMultiMediaRequest)
warning I'm getting this warning every time when my reposter sends a post from one channel to another and this post contains more than 8 media files. If it has more than 8, it will divide my post: first post - 8 media files and second one - 1-2 media files without text(it is left in the first part) sending message How ...
[ "As the error states, \"Telegram is having internal issues\". This means the issue is outside of your control and can't really \"fix\" it.\nThe library automatically retries a few times by default. You can turn this off if you want to handle the error yourself. You can also check logging's documentation to learn ho...
[ 0 ]
[]
[]
[ "python", "telethon" ]
stackoverflow_0074457741_python_telethon.txt
Q: Get tags of a commit Given an object of GitPython Commit, how can I get the tags related to this commit? I'd enjoy having something like: next(repo.iter_commits()).tags A: The problem is that tags point to commits, not the other way around. To get this information would require a linear scan of all tags to find...
Get tags of a commit
Given an object of GitPython Commit, how can I get the tags related to this commit? I'd enjoy having something like: next(repo.iter_commits()).tags
[ "The problem is that tags point to commits, not the other way around. To get this information would require a linear scan of all tags to find out which ones point to the given commit. You could probably write something yourself that would do it. The following would get you a commit-to-tags dictionary:\ntagmap = ...
[ 7, 0 ]
[]
[]
[ "commit", "git", "git_tag", "gitpython", "python" ]
stackoverflow_0034932306_commit_git_git_tag_gitpython_python.txt
Q: Training a RNN/LSTM model got KeyError equal to the val of the length Trying to train this model scaler = StandardScaler() X_train_s = scaler.fit_transform(X_train) X_test_s = scaler.transform(X_test) length = 60 n_features = X_train_s.shape[1] batch_size = 1 early_stop = EarlyStopping(monitor = 'val_accuracy', ...
Training a RNN/LSTM model got KeyError equal to the val of the length
Trying to train this model scaler = StandardScaler() X_train_s = scaler.fit_transform(X_train) X_test_s = scaler.transform(X_test) length = 60 n_features = X_train_s.shape[1] batch_size = 1 early_stop = EarlyStopping(monitor = 'val_accuracy', mode = 'max', verbose = 1, patience = 5) generator = TimeseriesGenerator(d...
[ "It was exhausting to find the cause due to the poor and misleading error message. Anyway, the trouble was on the target data set form, the TimeseriesGenerator does not accept panda dataframes, just np.arrays. Therefore this\n generator = TimeseriesGenerator(data = X_train_s, \n targe...
[ 0 ]
[]
[]
[ "lstm", "pandas", "python", "recurrent_neural_network" ]
stackoverflow_0074432853_lstm_pandas_python_recurrent_neural_network.txt
Q: Python | How do I swap two unknown words in an unknown string? I cannot find how to swap two words in a string using Python, without using any external/imported functions. What I have is a string that I get from a text document. For example the string is: line = "Welcome to your personal dashboard, where you can ...
Python | How do I swap two unknown words in an unknown string?
I cannot find how to swap two words in a string using Python, without using any external/imported functions. What I have is a string that I get from a text document. For example the string is: line = "Welcome to your personal dashboard, where you can find an introduction to how GitHub works, tools to help you build so...
[ "You're going to need to split the text into each word and find the min/max words by their size. Afterwards, iterate through the split words and check if it's equal to either the min/max word. If it is, then you need to replace it with the proper word.\nimport string #to check for punctuation\n\nline = \"Welcome to...
[ 1, 0 ]
[]
[]
[ "python", "replace", "string", "swap" ]
stackoverflow_0074460956_python_replace_string_swap.txt
Q: how to convert array to float insind a list hi i'm new to python and i was working on a mini project but i have this problem with some of my list output where i and array instead of float in my list tried to convert it using astype(float) but still nothing changed here is my code : import numpy as np import scip...
how to convert array to float insind a list
hi i'm new to python and i was working on a mini project but i have this problem with some of my list output where i and array instead of float in my list tried to convert it using astype(float) but still nothing changed here is my code : import numpy as np import scipy.stats as st import numpy.random as rd from IPy...
[ "If I understand correctly, you want to perform an operation with each item of a standard Python list. For that you can either use list comprehension (eager evaluation) or map function (lazy evaluation).\n# input list\nl = [1.1, 2.2, 3.3]\n\n# list comprehension, evaluated immediately (eager)\nl1 = [round(i) for i ...
[ 0, 0 ]
[]
[]
[ "arrays", "list", "numpy", "python", "random" ]
stackoverflow_0074459338_arrays_list_numpy_python_random.txt
Q: Running FastAPI in docker with uvicorn and gunicorn nginx I am trying to build a FastAPI application with ubuntu 22.04 docker image, gunicorn and uvicorn and nginx as webserver. Gunicorn and uvicorn services are started using supervisord. python is installed in a virtual environment located in /opt/venv Dockerfile...
Running FastAPI in docker with uvicorn and gunicorn nginx
I am trying to build a FastAPI application with ubuntu 22.04 docker image, gunicorn and uvicorn and nginx as webserver. Gunicorn and uvicorn services are started using supervisord. python is installed in a virtual environment located in /opt/venv Dockerfile FROM ubuntu:22.04 LABEL maintainer="test" ENV GROUP_ID=1000 \ ...
[ "In the mentioned Dockerfile, I don't see any command for running the server.\nSomething like this should work:\nCMD [\"python\", \"<path-to>/main.py\"]\n\nAlso, to make it discoverable within the docker network, I had to run the application on '0.0.0.0' instead of localhost.\n(It might be an issue specifically on ...
[ 1 ]
[]
[]
[ "docker", "docker_compose", "fastapi", "nginx", "python" ]
stackoverflow_0074451135_docker_docker_compose_fastapi_nginx_python.txt
Q: Pandas read_json converts string to decimal (though it has double quotes enclosing the data) I have a JSON file with a field which is supposed to be a string that represents an NPI Number. The JSON file looks like this: [{ ... "npi_109":"1234567891", ... }, { ...more records }] I use pandas to read it in like...
Pandas read_json converts string to decimal (though it has double quotes enclosing the data)
I have a JSON file with a field which is supposed to be a string that represents an NPI Number. The JSON file looks like this: [{ ... "npi_109":"1234567891", ... }, { ...more records }] I use pandas to read it in like this: import pandas as pd df = pd.read_json("temp/" + file.orig_filename, encoding = 'unicode_esc...
[ "How about:\ndf['npi_109'] = df['npi_109'].astype(int).astype(str)\n\nOr, if you don't need pandas to infer types when reading the json:\ndf = pd.read_json(filename, encoding = 'unicode_escape', dtype=False)\n\nOr, force it to be a string column\ndf = pd.read_json(filename, encoding = 'unicode_escape', dtype={colum...
[ 2 ]
[]
[]
[ "pandas", "pyarrow", "python" ]
stackoverflow_0074461241_pandas_pyarrow_python.txt
Q: Slice pandas series for each list in a list without using list comprehension I have a pandas Series which I want to slice based of list of slice-indices. It's fairly easy using list comprehension like slizes = [[0,1,2],[4,5,6],[7,8,9]] series = pd.Series(["a","b","c","d","e","f","g","h","i"]) [series.iloc[slize] f...
Slice pandas series for each list in a list without using list comprehension
I have a pandas Series which I want to slice based of list of slice-indices. It's fairly easy using list comprehension like slizes = [[0,1,2],[4,5,6],[7,8,9]] series = pd.Series(["a","b","c","d","e","f","g","h","i"]) [series.iloc[slize] for slize in slizes] #[["a","b","c"],["d","e","f"],...] But since I have 1.5 mio r...
[ "This is straightforward with numpy if you have always the same size of sublists, just slice:\na = series.to_numpy()\nout = a[slizes]\n\nOutput:\narray([['a', 'b', 'c'],\n ['e', 'f', 'g'],\n ['h', 'i', 'j']], dtype=object)\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074461309_pandas_python.txt
Q: From a numpy array of coordinates[x,y], remove other coordinates with a same x-value to keep the coordinate which has the maximum for y Suppose I have a Numpy array of a bunch of coordinates [x, y]. I want to filter this array. For all coordinates in the array with a same x-value, I want to keep only one coordin...
From a numpy array of coordinates[x,y], remove other coordinates with a same x-value to keep the coordinate which has the maximum for y
Suppose I have a Numpy array of a bunch of coordinates [x, y]. I want to filter this array. For all coordinates in the array with a same x-value, I want to keep only one coordinate: The coordinate with the maximum for the y. What is the most efficient or Pythonic way to do this. I will explain with an example below. ...
[ "if your array in small you can just do it one line:\nnp.array([[x, max(coord[coord[:,0] == x][:,1])] for x in set(coord[:,0])])\n\nhowever that is not correct complexity, if array is big and you care about correct complexity , do like this:\nd = {}\nfor x, y in coord:\n d[x] = max(d.get(x, float('-Inf')), y)\...
[ 2, 0 ]
[]
[]
[ "arrays", "coordinates", "filter", "numpy", "python" ]
stackoverflow_0074459169_arrays_coordinates_filter_numpy_python.txt
Q: unable a install pyspellcheck module on Linux(Raspbian) so I am working on Linux(Raspbian) and I am unable to install the pyspellcheck module. so previously I managed to install it by just pip install pyspellcheck but recently I had to factory reset my machine and I am not able to install pyspellcheck anymore. I ...
unable a install pyspellcheck module on Linux(Raspbian)
so I am working on Linux(Raspbian) and I am unable to install the pyspellcheck module. so previously I managed to install it by just pip install pyspellcheck but recently I had to factory reset my machine and I am not able to install pyspellcheck anymore. I get the following error: ERROR: Could not find a version that...
[ "There is no such a package at PyPI: https://pypi.org/project/pyspellcheck/ — error 404. What are you trying to install? Do you want pyspellchecker?\npip install pyspellchecker\n\n" ]
[ 0 ]
[]
[]
[ "linux", "pip", "pyspellchecker", "python", "raspbian" ]
stackoverflow_0074461305_linux_pip_pyspellchecker_python_raspbian.txt
Q: Levenstein distance substring Is there a good way to use levenstein distance to match one particular string to any region within a second longer string? Example: str1='aaaaa' str2='bbbbbbaabaabbbb' if str1 in str2 with a distance < 2: return True So in the above example part of string 2 is aabaa and distance...
Levenstein distance substring
Is there a good way to use levenstein distance to match one particular string to any region within a second longer string? Example: str1='aaaaa' str2='bbbbbbaabaabbbb' if str1 in str2 with a distance < 2: return True So in the above example part of string 2 is aabaa and distance(str1,str2) < 2 so the statement sh...
[ "You might have a look at the regex module that supports fuzzy matching:\n>>> import regex\n>>> regex.search(\"(aaaaa){s<2}\", 'bbbbbbaabaabbbb')\n<regex.Match object; span=(6, 11), match='aabaa', fuzzy_counts=(1, 0, 0)>\n\nSince you are looking are strings of equal length, you can also do a a Hamming distance whic...
[ 5, 3, 0, 0 ]
[]
[]
[ "levenshtein_distance", "python" ]
stackoverflow_0044398027_levenshtein_distance_python.txt
Q: return the maximum value of each row with cluster name in dataframe I I have a pandas dataframe, (df) that has three columns (user, values, and group name), the values column with multiple comma-separated values in each row. df = pd.DataFrame({'user': ['user_1', 'user_2', 'user_3', 'user_4', 'user_5', 'user_6'], ...
return the maximum value of each row with cluster name in dataframe
I I have a pandas dataframe, (df) that has three columns (user, values, and group name), the values column with multiple comma-separated values in each row. df = pd.DataFrame({'user': ['user_1', 'user_2', 'user_3', 'user_4', 'user_5', 'user_6'], 'values': [[1, 0, 2, 0], [1, 8, 0, 2],[6, 2, 0, 0], [5...
[ "You can use apply to extract max values with their indexes\nand then use basic string manipulations:\ndf['distance_values'] = [[5.0, 3.8439042651970405, 5.744562646538029],\n[4.58257569495584, 6.004631545732011, 8.06225774829855],\n[4.242640687119285, 2.9112883745860696, 0.0],\n[4.58257569495584, 3.668187563361503...
[ 2, 2, 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074460679_dataframe_group_by_pandas_python.txt
Q: How to put data into a tempfile and post as CSV on SFTP Goal is Create a temporary SCP file filled with data and upload it to an sftp. The data to fill is TheList and is from class list. What I am able to achieve Create the connection to the SFTP Push a file to the SFTP What happens with the code below There is ...
How to put data into a tempfile and post as CSV on SFTP
Goal is Create a temporary SCP file filled with data and upload it to an sftp. The data to fill is TheList and is from class list. What I am able to achieve Create the connection to the SFTP Push a file to the SFTP What happens with the code below There is a file created/put to the SFTP, but the file is empty and has...
[ "You do not need to create a temporary file. You can use csv.writer to write the rows directly to the SFTP with use of file-like object opened using SFTPClient.open:\nwith sftp.open(SftpPath + \"anewfile.csv\", mode='w', bufsize=32768) as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n filewriter.wri...
[ 1 ]
[]
[]
[ "csv", "paramiko", "python", "sftp", "temporary_files" ]
stackoverflow_0074461295_csv_paramiko_python_sftp_temporary_files.txt
Q: reformat my repetitive code into a while or for loop for minesweeper game in python using oop So for the game mine sweeper when you click a box with 0 surrounding mines not only is that cell revealed but all surrounding cells. I want to make my code so that if there is then another 0 that was revealed all cells ar...
reformat my repetitive code into a while or for loop for minesweeper game in python using oop
So for the game mine sweeper when you click a box with 0 surrounding mines not only is that cell revealed but all surrounding cells. I want to make my code so that if there is then another 0 that was revealed all cells around that 0 are also revealed. ie if there are 2 0s together (side by side say) when clicked not ju...
[ "Here's a recursive solution. You might need to tweak it to suit your needs.\nimport random\n\n# 10x10 mine field\n# \"-\" = not clicked, \" \" = cleared, \"m\" = mine\ngame = [['-'] * 10 for _ in range(10)]\n\n# Returns r,c of every space around row,col\ndef get_surrounding_spaces(row, col):\n spaces = []\n ...
[ 0 ]
[]
[]
[ "for_loop", "oop", "python", "python_3.x", "while_loop" ]
stackoverflow_0074452700_for_loop_oop_python_python_3.x_while_loop.txt
Q: Check if string starts with any of two (sub) strings I'm trying to pass a number of options for a bolean function and I wrote it like this: s = 'https://www.youtube.com/watch?v=nVNG8jjZN7k' s.startswith('http://') or s.startswith('https://') But I was wondering if there's a more efficient way to write it, somethi...
Check if string starts with any of two (sub) strings
I'm trying to pass a number of options for a bolean function and I wrote it like this: s = 'https://www.youtube.com/watch?v=nVNG8jjZN7k' s.startswith('http://') or s.startswith('https://') But I was wondering if there's a more efficient way to write it, something like: s.startswith('http://' or 'https://')
[ "str.startswith can take a tuple of strings as an argument. It will return true if the string starts with any of them.\ns.startswith(('http://', 'https://'))\n\nHowever, it might be simpler to use a regular expression to capture the idea of the s being optional:\nbool(re.match('https?://', s))\n\nIf the match succe...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074460317_python.txt
Q: AttributeError: 'module' object has no attribute 'set_start_method' That code below starts fine in pycharm. But by starting with the command line: "python field_basket_design_uwr.py" it gives error: Traceback (most recent call last): File "field_basket_design_uwr.py", line 677, in <module> mp.set_start_m...
AttributeError: 'module' object has no attribute 'set_start_method'
That code below starts fine in pycharm. But by starting with the command line: "python field_basket_design_uwr.py" it gives error: Traceback (most recent call last): File "field_basket_design_uwr.py", line 677, in <module> mp.set_start_method('spawn') AttributeError: 'module' object has no attribute 'set_star...
[ "The set_start_method in multiprocessing was introduced in Python version 3.4\nThe error you are facing is due to the fact that you are using an older version of Python. Upgrading to Python 3.4 and above will fix the error.\nFor more information, refer to -\nhttps://docs.python.org/3/library/multiprocessing.html#mu...
[ 3, 0 ]
[]
[]
[ "matplotlib", "multiprocessing", "python" ]
stackoverflow_0049597563_matplotlib_multiprocessing_python.txt
Q: Install old spaCy release in a MAC computer I would like to install spaCy V3.2.1 in my virtual environment (MacBook Air, Apple M1 processor, MACOs Ventura 13.0). The commands I run, inspired by the spaCy widget and the specific information for Apple computers, are: # Create and activate virtual environment python ...
Install old spaCy release in a MAC computer
I would like to install spaCy V3.2.1 in my virtual environment (MacBook Air, Apple M1 processor, MACOs Ventura 13.0). The commands I run, inspired by the spaCy widget and the specific information for Apple computers, are: # Create and activate virtual environment python -m venv venv source venv/bin/activate # Install ...
[ "As suggested in the comment section, the error got solved after upgrading OS to macOS Ventura 13, which implicitely upgraded Xcode to version 14.1.\n" ]
[ 0 ]
[]
[]
[ "pip", "python", "spacy_3" ]
stackoverflow_0074185326_pip_python_spacy_3.txt
Q: python cut row in pandas df I have dataframe 0 г. Санкт-Петербург, ул. Карпинского, 1 г. Челябинск, проспект Комсомольский, 2 г. Екатеринбург, ул. Щербакова, 3 г. Санкт-Петербург, ул. Латышских Стрелков, 4 г. Москва, вн.тер.г. муниципал...
python cut row in pandas df
I have dataframe 0 г. Санкт-Петербург, ул. Карпинского, 1 г. Челябинск, проспект Комсомольский, 2 г. Екатеринбург, ул. Щербакова, 3 г. Санкт-Петербург, ул. Латышских Стрелков, 4 г. Москва, вн.тер.г. муниципальный округ Измай... I want all b...
[ "You can use str.extract with:\ndata['col'] = data['address'].str.extract(r'г. *([^,]+),', expand=False)\n\noutput:\n address col\n0 г. Санкт-Петербург, ул. Карпинского, Санкт-Петербург\n1 г. Челябинск, проспект Комсомольский, ...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074461445_pandas_python.txt
Q: Apply function to each element of list and rename I would like to run two separate loops on df. In the first step, I would like to filter the df by sex (male, female) and year (yrs 2008:2013) and save these dataframes in a list. In the second step, I would like to do some kind of analysis to each element of the li...
Apply function to each element of list and rename
I would like to run two separate loops on df. In the first step, I would like to filter the df by sex (male, female) and year (yrs 2008:2013) and save these dataframes in a list. In the second step, I would like to do some kind of analysis to each element of the list and name the output based on which sex & year combin...
[ "IIUC you could filter plot and save the data like this. Since I don't know the actual data I don't know why you need to do it in 2 steps, here is how you could do it with a few changes.\n# Input data\ndf_toy = pd.DataFrame({\n 'value' : np.random.randint(low=1, high=1000, size=100000),\n 'age' : np.random.ch...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074461006_list_python.txt
Q: How to terminate / stop a for loop I am making a survey in Spyder. I need to make it so the output does not allow for anyone under 18 to complete the survey.... I can get it to print the error message but the survey still continues... As you can probably tell, I am a beginner. excluded_ages= '17''16''15''14''13''1...
How to terminate / stop a for loop
I am making a survey in Spyder. I need to make it so the output does not allow for anyone under 18 to complete the survey.... I can get it to print the error message but the survey still continues... As you can probably tell, I am a beginner. excluded_ages= '17''16''15''14''13''12''11''10''9''8''7''6''5''4''3''2''1''0'...
[ "First there is no loop to break from so the break statement does nothing. Let me suggest a way to simplify this. My example will simply exit the program.\nimport sys\n\nage = int(input('Enter your age: '))\nif age < 18:\n print('You may not proceed with this survey')\n sys.exit()\n\nwithout using packages yo...
[ 0, 0 ]
[]
[]
[ "loops", "python", "survey", "terminate" ]
stackoverflow_0074461398_loops_python_survey_terminate.txt
Q: Shift each row of pandas dataframe independently I have a dataframe df1 = pd.DataFrame({ 'uid': [11, 22], 1: [0.001, 0.005], 2: [0.004, 0.006], }).set_index(') and another df that specifies the left shift we need to make for each uid s_df = pd.DataFrame({ 'uid': [11...
Shift each row of pandas dataframe independently
I have a dataframe df1 = pd.DataFrame({ 'uid': [11, 22], 1: [0.001, 0.005], 2: [0.004, 0.006], }).set_index(') and another df that specifies the left shift we need to make for each uid s_df = pd.DataFrame({ 'uid': [11, 22], 'shift_val': [0, 1], ...
[ "shift doesn't support multiple periods, so you have to loop.\nYou can use:\ndf1.apply(lambda s: s.shift(-s_df['shift_val'].get(s.name, 0)), axis=1)\n\nOr, with concat:\npd.concat([df1.loc[x].shift(-s_df['shift_val'].get(x, 0))\n for x in df1.index], axis=1).T\n\nOutput:\n 1 2\nuid ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074461515_pandas_python.txt
Q: Using eval to create datestamp Trying to get eval to work on a dictionary that comprises a datetime field. I'm attempting to do the following: from datetime import datetime as datetime print(eval("{'datestamp': datetime.today()}", {}, {})) gives the following: NameError: name 'datetime' is not defined' I want to...
Using eval to create datestamp
Trying to get eval to work on a dictionary that comprises a datetime field. I'm attempting to do the following: from datetime import datetime as datetime print(eval("{'datestamp': datetime.today()}", {}, {})) gives the following: NameError: name 'datetime' is not defined' I want to return a string with a date compute...
[ "Pass the copy of datetime you imported as a global, rather than telling eval to pass empty sets of both locals and globals, when you want that copy of datetime to be accessible within the eval'd code:\nfrom datetime import datetime\nprint(eval(\"{'datestamp': datetime.today()}\", {'datetime': datetime}))\n\nAltern...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074461580_python.txt
Q: Regex to match a float after a particular expression I'm trying to extract, in my python script, from a long documents all the floats that follow a particular expression, that is >250 After ">250" there are a certain number of spaces and the float can be in the form 12.34 or 12 An example is: word word 150 175...
Regex to match a float after a particular expression
I'm trying to extract, in my python script, from a long documents all the floats that follow a particular expression, that is >250 After ">250" there are a certain number of spaces and the float can be in the form 12.34 or 12 An example is: word word 150 175 200 225 >250 12.3 word word and 12.3 should be matched I...
[ "Try:\n>250\\s+(-?\\d+\\.?\\d*)\n\nRegex demo.\n>250 - match >250\n\\s+ - match 1 or more number of spaces\n(-?\\d+\\.?\\d*) - match a int/float into a capturing group\n" ]
[ 1 ]
[]
[]
[ "match", "python", "regex" ]
stackoverflow_0074461498_match_python_regex.txt
Q: Convert a list to a matrix I want to convert a list with numbers to a matrix. This is my code: def converttomtx(mylist, rows, columns): mtx = [] for r in range(rows): lrow = [] for c in range(columns): lrow.append(mylist[rows * r + c]) mtx.append(lro...
Convert a list to a matrix
I want to convert a list with numbers to a matrix. This is my code: def converttomtx(mylist, rows, columns): mtx = [] for r in range(rows): lrow = [] for c in range(columns): lrow.append(mylist[rows * r + c]) mtx.append(lrow) return mtx Assuming I...
[ "You can try the robust numpy library for any type of list reshaping, for example:\n>>> import numpy as np\n>>> li = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> li = np.array(li) # convert to an ndarray\n\n>>> li.reshape(2, 6)\narray([[ 0, 1, 2, 3, 4, 5],\n [ 6, 7, 8, 9, 10, 11]])\n\n>>> li.reshape(6,...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074461185_python.txt
Q: How to check if an object has an attribute? How do I check if an object has some attribute? For example: >>> a = SomeClass() >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' How do I tell if a has the attribute p...
How to check if an object has an attribute?
How do I check if an object has some attribute? For example: >>> a = SomeClass() >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' How do I tell if a has the attribute property before using it?
[ "Try hasattr():\nif hasattr(a, 'property'):\n a.property\n\nSee zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!\nThe general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception prop...
[ 3204, 796, 630, 53, 40, 34, 20, 20, 20, 17, 16, 15, 3, 2, 1, 0 ]
[]
[]
[ "attributes", "class_attributes", "object", "python", "python_3.x" ]
stackoverflow_0000610883_attributes_class_attributes_object_python_python_3.x.txt
Q: VS Code: ModuleNotFoundError: No module named 'pandas' Tried to import pandas in VS Code with import pandas and got Traceback (most recent call last): File "c:\Users\xxxx\hello\sqltest.py", line 2, in <module> import pandas ModuleNotFoundError: No module named 'pandas' Tried to install pandas with pip inst...
VS Code: ModuleNotFoundError: No module named 'pandas'
Tried to import pandas in VS Code with import pandas and got Traceback (most recent call last): File "c:\Users\xxxx\hello\sqltest.py", line 2, in <module> import pandas ModuleNotFoundError: No module named 'pandas' Tried to install pandas with pip install pandas pip3 install pandas python -m pip install panda...
[ "It's easier than we imagine:\n\nThis image explains how to solve this problem.\n", "\nDownload anaconda interpreter from this link\nAfter installation, open anaconda prompt (anaconda3) and execute this code conda install ipykernel. It will install all necessary packages.\nRestart vs code and change interpreter t...
[ 20, 5, 2, 2, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0063388135_python_visual_studio_code.txt
Q: How to load custom model in pytorch I'm trying to load my pretrained model (yolov5n) and test it with the following code in PyTorch: import os import torch model = torch.load(os.getcwd()+'/weights/last.pt') # Images imgs = ['https://example.com/img.jpg'] # Inference results = model(imgs) # Results result...
How to load custom model in pytorch
I'm trying to load my pretrained model (yolov5n) and test it with the following code in PyTorch: import os import torch model = torch.load(os.getcwd()+'/weights/last.pt') # Images imgs = ['https://example.com/img.jpg'] # Inference results = model(imgs) # Results results.print() results.save() # or .show() r...
[ "You should be able to find the weights in this directory: yolov5/runs/train/exp/weights/last.pt\nThen you load the weights with a line like this:\nmodel = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5/runs/train/exp/weights/last.pt', force_reload=True) \n\nI have an example of a notebook that loads c...
[ 8, 1, 0 ]
[]
[]
[ "python", "pytorch", "yolo", "yolov5" ]
stackoverflow_0070167811_python_pytorch_yolo_yolov5.txt
Q: Finding element from Inspet Chrome SO basically Im trying to find how many brooches are on this site: https://www.swarovski.com/en-RO/c-0107/Categories/Jewelry/Brooches/ and my code is this: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_c...
Finding element from Inspet Chrome
SO basically Im trying to find how many brooches are on this site: https://www.swarovski.com/en-RO/c-0107/Categories/Jewelry/Brooches/ and my code is this: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver....
[ "find_elements method returns a list of web elements.\nYour mistake is with this line:\nproduct_name = product.find_elements(By.XPATH, '/html/body/main/div[2]/section[2]/div[2]/div/div/div/div[1]/div/a/div[2]/p/span[1]')\n\nYou need to use find_element method here, not find_elements.\nThe following code will not gi...
[ 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_chromedriver", "web_scraping" ]
stackoverflow_0074461620_python_python_3.x_selenium_selenium_chromedriver_web_scraping.txt
Q: Do a specific search for dicts in a list in Python I am getting traffic network from a website. I want to getting the json file of a location on google maps because of that i need to take a json website link from traffic network. This traffic network I receive is recorded as a list. This list contains words. And e...
Do a specific search for dicts in a list in Python
I am getting traffic network from a website. I want to getting the json file of a location on google maps because of that i need to take a json website link from traffic network. This traffic network I receive is recorded as a list. This list contains words. And every time I refresh the web page, the places in the list...
[ "Since timings is a list we can simply iterate over it to find the desired element in the list and the to extract the rest of the link as following:\nfor item in timings:\n if 'https://maps.googleapis.com/maps/api/js/GeoPhotoService.GetMetadata' in item:\n the_rest_of_the_link = item.split(\"https://maps....
[ 0, 0 ]
[]
[]
[ "network_traffic", "python", "selenium" ]
stackoverflow_0074460051_network_traffic_python_selenium.txt
Q: Getting each from of a dataframe without column values I'm trying to add a column to each row of a dataframe which includes a hash value of the row values. I originally tried this: df['hash'] = pd.Series((hash(tuple(row)) for _, row in df_to_hash.iterrows())) However, when I ran this on two different DataFrames, ...
Getting each from of a dataframe without column values
I'm trying to add a column to each row of a dataframe which includes a hash value of the row values. I originally tried this: df['hash'] = pd.Series((hash(tuple(row)) for _, row in df_to_hash.iterrows())) However, when I ran this on two different DataFrames, I was encountering an issue when the column names didn't exa...
[ "What about using the underlying numpy array:\npd.Series((hash(tuple(row)) for row in df_to_hash.to_numpy()))\n\nOutput:\n0 2606281096150585092\n1 -1842928179554038127\ndtype: int64\n\nYou can also use pandas.util.hash_pandas_object with index=False:\npd.util.hash_pandas_object(df_to_hash, index=False)\n\nOutp...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074461681_pandas_python.txt
Q: Access denied error installing MySql Python connector 64-bit on Windows 10 via .msi I have successfully installed most of MySql on Windows 10, and have a working database. The only part that will not install is the 64-bit Python connector. I am successfully using the connector via pip --install, but it is unclear...
Access denied error installing MySql Python connector 64-bit on Windows 10 via .msi
I have successfully installed most of MySql on Windows 10, and have a working database. The only part that will not install is the 64-bit Python connector. I am successfully using the connector via pip --install, but it is unclear if I have a 64-bit or 32-bit version (as I am having issues with the int64 python type)....
[ "I had the same problem with this, but I was able to fix it!\nIt turns out the problem is the Python version from windows Store, that has a restricted folder with no access to modify it, due to windows restrictions to prevent piracy.\nThe WindowsApps folder is one of the few that doesn't allow modification from use...
[ 2, 0, 0 ]
[]
[]
[ "installation", "mysql", "python", "windows_10" ]
stackoverflow_0066925897_installation_mysql_python_windows_10.txt
Q: How to efficiently create an index-like Polars DataFrame from multiple sparse series? I would like to create a DataFrame that has an "index" (integer) from a number of (sparse) Series, where the index (or primary key) is NOT necessarily consecutive integers. Each Series is like a vector of (index, value) tuple or ...
How to efficiently create an index-like Polars DataFrame from multiple sparse series?
I would like to create a DataFrame that has an "index" (integer) from a number of (sparse) Series, where the index (or primary key) is NOT necessarily consecutive integers. Each Series is like a vector of (index, value) tuple or {index: value} mapping. (1) A small example In Pandas, this is very easy as we can create a...
[ "Following your example, but only informing polars on the fact that the \"index\" column is sorted (polars will use fast paths if data is sorted).\nYou can use align_frames together with functools.reduce to get what you want.\nThis is your data creation snippet:\nimport functools\nimport polars as pl\n\nN, C = 3000...
[ 1, 0 ]
[]
[]
[ "dataframe", "python", "python_polars", "rust_polars" ]
stackoverflow_0074450537_dataframe_python_python_polars_rust_polars.txt
Q: How to combine every 4 lines in a txt file? I have a txt.file that looks like this: data1 data2 data3 data4 data5 data6 data7 data8 data9 data10 data11 data12 data13 data14 data15 data16 data17 data18 data19 data20 data21 data22 data23 data24 . . . and I want to rearrange my txt file so that from ...
How to combine every 4 lines in a txt file?
I have a txt.file that looks like this: data1 data2 data3 data4 data5 data6 data7 data8 data9 data10 data11 data12 data13 data14 data15 data16 data17 data18 data19 data20 data21 data22 data23 data24 . . . and I want to rearrange my txt file so that from data1 to data12 will be 1 line, and data13 to dat...
[ "You could try something like this:\nwith open(\"text.txt\" \"r\") as f: # load data\n lines = f.readlines()\n\nnewlines = []\nfor i in range(0, len(lines), 4): # step through in blocks of four\n newline = lines[i].strip() + \" \" + lines[i+1].strip() + \" \" + lines[i+2].strip() + \" \" + lines[i+3].strip(...
[ 1, 0, 0 ]
[]
[]
[ "pandas", "python", "txt" ]
stackoverflow_0074461272_pandas_python_txt.txt
Q: how to parse mysql database name from database_url DATABASE_URL- MYSQL://username:password@host:port/database_name Error: database_name has no attributes. if 'DATABASE_URL' in os.environ: url = urlparse(os.getenv['DATABASE_URL']) g['db'] = mysql.connector.connect(user=url.username,password=url.password, hos...
how to parse mysql database name from database_url
DATABASE_URL- MYSQL://username:password@host:port/database_name Error: database_name has no attributes. if 'DATABASE_URL' in os.environ: url = urlparse(os.getenv['DATABASE_URL']) g['db'] = mysql.connector.connect(user=url.username,password=url.password, host=url.hostname ,port=url.port,path=url.path[1:])
[ "First of all, url.host would result into:\n\nAttributeError: 'ParseResult' object has no attribute 'host'\n\nuse url.hostname instead.\nTo get the database_name out of the provided URL, use path:\nurl.path[1:]\n\n\nAn alternative \"Don't reinvent the wheel\" way to approach the problem would be to use sqlalachemy'...
[ 23, 11, 1, 0 ]
[]
[]
[ "database_connection", "mysql", "python", "urlparse" ]
stackoverflow_0031036453_database_connection_mysql_python_urlparse.txt
Q: I need to retrieve historical information from the http://service.iris.edu/fdsnws/dataselect/docs/1/builder/ API I need to retrieve historical for the earthquakes in Japan and Chile, and I know this websites has an API. Nevertheless, I cannot seem how to used correctly. Help will be trully appreciated it. A: You...
I need to retrieve historical information from the http://service.iris.edu/fdsnws/dataselect/docs/1/builder/ API
I need to retrieve historical for the earthquakes in Japan and Chile, and I know this websites has an API. Nevertheless, I cannot seem how to used correctly. Help will be trully appreciated it.
[ "You can use the URL builder that i on the page you posted. Than you make GET request in you python code to the generated url.\nThis is tutorial how to make GET request in Python: https://www.geeksforgeeks.org/get-post-requests-using-python/\nThen you will recieve response with desired data.\n" ]
[ 0 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074461685_api_python.txt
Q: How do I get my python code that I transferred to pc to work? I have a problem with my python, I have copied and pasted every thing from raspberry pi to pc and downloaded visual studio code to run it, and downloaded python and guizero to my pc via command terminal but even then, when I run my code, it opens up a w...
How do I get my python code that I transferred to pc to work?
I have a problem with my python, I have copied and pasted every thing from raspberry pi to pc and downloaded visual studio code to run it, and downloaded python and guizero to my pc via command terminal but even then, when I run my code, it opens up a window of it for about 1 second without loading and then immediately...
[ "You're missing the open close brackets at the end of app.display() :)\n" ]
[ 1 ]
[]
[]
[ "guizero", "python", "windows" ]
stackoverflow_0074430459_guizero_python_windows.txt
Q: Tkinter - Use characters/bytes offset as index for text widget I want to delete part of a text widget's content, using only character offset (or bytes if possible). I know how to do it for lines, words, etc. Looked around a lot of documentations: https://www.tcl.tk/man/tcl8.6/TkCmd/text.html#M24 https://tkdocs.co...
Tkinter - Use characters/bytes offset as index for text widget
I want to delete part of a text widget's content, using only character offset (or bytes if possible). I know how to do it for lines, words, etc. Looked around a lot of documentations: https://www.tcl.tk/man/tcl8.6/TkCmd/text.html#M24 https://tkdocs.com/tutorial/text.html https://anzeljg.github.io/rin2/book2/2405/docs/...
[ "TL;DR\nYou can use a relative index similar to f.tell() by giving a starting index and then add or remove lines or characters. For example, text.delete(\"1.0\", \"1.0+11c\") (\"1.0\" plus 11 characters)\nThe canonical documentation for text widget indexes is in the tcl/tk man pages in a section named Indices.\n\n\...
[ 5, 2, 1 ]
[]
[]
[ "offset", "python", "text", "tkinter" ]
stackoverflow_0074447766_offset_python_text_tkinter.txt
Q: Python: How to search for multiple items in a list So i have a list with number values such as my_num = [1,2,2,3,4,5] What i want is a code that will check if 1, 2 and 3 are in the list. What i had in mind was: if 1 and 2 and 3 in my_num: do something but the problem is if 1 and 3 are in the list the do something...
Python: How to search for multiple items in a list
So i have a list with number values such as my_num = [1,2,2,3,4,5] What i want is a code that will check if 1, 2 and 3 are in the list. What i had in mind was: if 1 and 2 and 3 in my_num: do something but the problem is if 1 and 3 are in the list the do something code executes anyways even without the 2 being there.
[ "Check out the standard library functions any and all. You can write this:\nif any(a in my_num for a in (1, 2, 3)):\n # do something if one of the numbers is in the list\nif all(a in my_num for a in (1, 2, 3)):\n # do something if all of them are in the list\n\n", "Try this:\nnums = [1,2,3,4]\n>>> if (1 in...
[ 5, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0046985602_python.txt
Q: Why define constants in a metaclass? I've recently inherited some code. It has a class called SystemConfig that acts as a grab-bag of constants that are used across the code base. But while a few of the constants are defined directly on that class, a big pile of them are defined as properties of a metaclass of t...
Why define constants in a metaclass?
I've recently inherited some code. It has a class called SystemConfig that acts as a grab-bag of constants that are used across the code base. But while a few of the constants are defined directly on that class, a big pile of them are defined as properties of a metaclass of that class. Like this: class _MetaSystemCo...
[ "So I figured out why it was done this way. These properties were defined as properties because a number of them depended on each other - one for a directory, another for a subdirectory of that directory, several for files spread across the directories and so forth.\nBut @property doesn't work on classmethods. Py...
[ 1, 0 ]
[]
[]
[ "pytest", "pytest_mock", "python", "python_3.x", "python_unittest" ]
stackoverflow_0074445635_pytest_pytest_mock_python_python_3.x_python_unittest.txt
Q: pywhatkit opening the same youtube video When trying to get pywhatkit to open a youtube video, it works, except it opens the same youtube video every time. one that i did not request if 'play' in command: song = command.replace('play', '') talk('playing' + song) pywhatkit.playonyt('song') ...
pywhatkit opening the same youtube video
When trying to get pywhatkit to open a youtube video, it works, except it opens the same youtube video every time. one that i did not request if 'play' in command: song = command.replace('play', '') talk('playing' + song) pywhatkit.playonyt('song') It keeps opening this link https://www.youtub...
[ "Remove the quotes around song:\npywhatkit.playonyt(song)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0069992718_python.txt
Q: How do I get time of a Python program's execution? I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running. I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program. A: The simplest...
How do I get time of a Python program's execution?
I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running. I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program.
[ "The simplest way in Python:\nimport time\nstart_time = time.time()\nmain()\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\nThis assumes that your program takes at least a tenth of second to run.\nPrints:\n--- 0.764891862869 seconds ---\n\n", "In Linux or Unix:\n$ time python yourprogram.py\n\nIn W...
[ 2728, 254, 248, 131, 112, 82, 76, 51, 41, 29, 26, 20, 17, 16, 12, 11, 10, 9, 9, 9, 8, 8, 6, 6, 6, 6, 5, 4, 3, 3, 3, 3, 1, 1, 0, 0, 0 ]
[ "I define the following Python decorator:\ndef profile(fct):\n def wrapper(*args, **kw):\n start_time = time.time()\n ret = fct(*args, **kw)\n print(\"{} {} {} return {} in {} seconds\".format(args[0].__class__.__name__,\n args[0].__class__.__module__,\n ...
[ -2 ]
[ "execution_time", "python", "time" ]
stackoverflow_0001557571_execution_time_python_time.txt
Q: Is the python XOR bitwise operator not just a regular operator? Other questions on this site suggest that python has no XOR operator, only a bitwise operator ^. But when I try this operator on booleans the result is also a boolean (Python 3.9.12) True ^ False >> True If it was a bitwise operator I would expect it...
Is the python XOR bitwise operator not just a regular operator?
Other questions on this site suggest that python has no XOR operator, only a bitwise operator ^. But when I try this operator on booleans the result is also a boolean (Python 3.9.12) True ^ False >> True If it was a bitwise operator I would expect it to first cast the inputs to integers, resulting in an integer as out...
[ "Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in ...
[ 0 ]
[]
[]
[ "bitwise_xor", "operators", "python" ]
stackoverflow_0074461775_bitwise_xor_operators_python.txt
Q: Unable to successfully patch functions of Azure ContainerClient I have been trying to patch the list_blobs() function of ContainerClient, have not been able to do this successfully, this code outputs a MagicMock() function - but the function isn't patched as I would expect it to be (Trying to patch with a list ['B...
Unable to successfully patch functions of Azure ContainerClient
I have been trying to patch the list_blobs() function of ContainerClient, have not been able to do this successfully, this code outputs a MagicMock() function - but the function isn't patched as I would expect it to be (Trying to patch with a list ['Blob1', 'Blob2']. #################Script File import sys from datetim...
[ "I'm not able to execute your code in this moment, but I have tried to simulate it. To do this I have created the following 3 files in the path: /<path-to>/pkg/sub_pkg1 (where pkg and sub_pkg1 are packages).\nFile ContainerClient.py\ndef list_blobs(self):\n return \"blob1\"\n\nFile DeleteOldBlobs.py\nfrom pkg.su...
[ 0 ]
[]
[]
[ "azure", "mocking", "python", "python_unittest" ]
stackoverflow_0074447151_azure_mocking_python_python_unittest.txt
Q: Break long lines of python code programmatically What is a/the way to auto-format an existing (potentially large) Python codebase to conform to a given max line length? Autoformatters like black, yapf and autopep8 do change too much as they also change other things. A: This seems like a thing that can be easily ...
Break long lines of python code programmatically
What is a/the way to auto-format an existing (potentially large) Python codebase to conform to a given max line length? Autoformatters like black, yapf and autopep8 do change too much as they also change other things.
[ "This seems like a thing that can be easily solved using an .editorconfig file. I don't know what IDE/Code editor you use, but from my experience, pyCharm supports it very well. The config should look something like this:\nroot = true\n\n[*.py]\nmax_line_length = 88\n\nFor more info, check https://editorconfig.org/...
[ 0 ]
[]
[]
[ "autoformatting", "python" ]
stackoverflow_0074461544_autoformatting_python.txt
Q: Variable input from lists for find_element selenium function Hi StackOverflow gurus, I am new to coding and Python but very enthusiastic about it. Your support and option will be huge addition do my development. I am trying to write a Python code, where using Selenium find_element(By.LINK_TEXT,"") I need to identi...
Variable input from lists for find_element selenium function
Hi StackOverflow gurus, I am new to coding and Python but very enthusiastic about it. Your support and option will be huge addition do my development. I am trying to write a Python code, where using Selenium find_element(By.LINK_TEXT,"") I need to identify company names and click on it. This action should be repetitive...
[ "You're using the entire company list as your text. Use the index you created in the for loop to grab only one element in the list:\nfor i in range (len(company)):\n driver.find_element(By.LINK_TEXT,company[i]).click()\n\n" ]
[ 0 ]
[]
[]
[ "dynamic", "findelement", "list", "python", "selenium" ]
stackoverflow_0074460747_dynamic_findelement_list_python_selenium.txt
Q: Can't access specific element using xpath with selenium Python I am trying to parse the wind direction using selenium and I think using xpath is the easiest way to get this info. There is a table with all the information and the xpath of the elements within this table follow the same structure, hence my following ...
Can't access specific element using xpath with selenium Python
I am trying to parse the wind direction using selenium and I think using xpath is the easiest way to get this info. There is a table with all the information and the xpath of the elements within this table follow the same structure, hence my following code: wind_directions = [browser.find_element_by_xpath(f'//*[@id="ar...
[ "svg g etc. are special tag names.\nTo locate such nodes with XPath you can change your XPath expression as following:\n'//*[@id=\"archive_results\"]/table/tbody/tr/td/table/tbody/tr[3]/td[{i}]/*[name()=\"svg\"]/*[name()=\"g\"]'\n\n" ]
[ 1 ]
[]
[]
[ "html", "python", "selenium", "xpath" ]
stackoverflow_0074461752_html_python_selenium_xpath.txt
Q: difference of summary between sklearn and statsmodels OLS The goal is to detect and fix why the report between my sklearn "summary" implementation is not matching with the results of OLS statsmodels. The only thing is matching, is the beta coefficients. import pandas as pd import numpy as np from statsmodels.regre...
difference of summary between sklearn and statsmodels OLS
The goal is to detect and fix why the report between my sklearn "summary" implementation is not matching with the results of OLS statsmodels. The only thing is matching, is the beta coefficients. import pandas as pd import numpy as np from statsmodels.regression.linear_model import OLS from sklearn import linear_model ...
[ "Here you have a class that you can use in order to obtain a LinearRegression model summary using Scikit-learn:\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import t\nfrom sklearn import linear_model\n\nclass LinearRegression(linear_model.LinearRegression):\n\n def __init__(self, *args, **kwargs):\...
[ 2 ]
[]
[]
[ "least_squares", "p_value", "python", "scikit_learn", "statsmodels" ]
stackoverflow_0074412143_least_squares_p_value_python_scikit_learn_statsmodels.txt
Q: can you make a regular python class frozen? It's useful to be able to create frozen dataclasses. I'm wondering if there is a way to do something similar for regular python classes (ones with an __init__ function with complex logic possibly). It would be good to prevent modification after construction in some kind ...
can you make a regular python class frozen?
It's useful to be able to create frozen dataclasses. I'm wondering if there is a way to do something similar for regular python classes (ones with an __init__ function with complex logic possibly). It would be good to prevent modification after construction in some kind of elegant way, like frozen dataclasses.
[ "yes.\nAll attribute access in Python is highly customizable, and this is just a feature dataclasses make use of.\nThe easiest way to control attribute setting is to create a custom __setattr__ method in your class - if you want to be able to create attributes during __init__ one of the ways is to have an specific ...
[ 0 ]
[]
[]
[ "python", "python_dataclasses" ]
stackoverflow_0074312939_python_python_dataclasses.txt
Q: Spyder IDE with python 3.10 seems freezing when click run button, but it works fine if run a single line beforehand running the entire script I have truble with last version of Spyder 5.4.0 with last version of Python 3.10.6. Spyder version: 5.4.0 (conda) Python version: 3.10.6 64-bit Qt version: 5.15.2 PyQt5 ve...
Spyder IDE with python 3.10 seems freezing when click run button, but it works fine if run a single line beforehand running the entire script
I have truble with last version of Spyder 5.4.0 with last version of Python 3.10.6. Spyder version: 5.4.0 (conda) Python version: 3.10.6 64-bit Qt version: 5.15.2 PyQt5 version: 5.15.7 Operating System: Windows 10 Even if running a script like print('Hello world') when I click on the play green button, the IPython ...
[ "After many trials, I noticed that there is something strange with IPython console. I noticed that when it hangs after running a code, if I delete all user variables, it worked fine.\nThen I tryed to delete all variables before execution, and it work fine.\nTherefore I discovered that a solution that worked for me ...
[ 0 ]
[]
[]
[ "anaconda", "ide", "miniconda", "python", "spyder" ]
stackoverflow_0074459113_anaconda_ide_miniconda_python_spyder.txt
Q: Python: Detect most similar list from list of lists I want to detect the most similar list from list of lists in the fastest way. My searching list: [1,2,3,4] The list of lists: [[1],[2],[1,2],[1,2,3,4,5,6],[1,2,3],[1,2,3,4,5]] Most simillar result: [1,2,3] I was trying to find that with some common operators i...
Python: Detect most similar list from list of lists
I want to detect the most similar list from list of lists in the fastest way. My searching list: [1,2,3,4] The list of lists: [[1],[2],[1,2],[1,2,3,4,5,6],[1,2,3],[1,2,3,4,5]] Most simillar result: [1,2,3] I was trying to find that with some common operators in python but it's too slow in my data. I have about 2 mil...
[ "The following fonction returns the most similar lists according to the length\ndef most_similar_acc_length(my_list, range_of_lists, length_range):\n \"\"\"most similar series according to length\n Parameters\n ----------\n my_list : The list of interest\n range_of_lists: List of lists where we...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074461893_python.txt
Q: pandas groupby.apply is slow, even on small DataSets I want to aggregate a pandas DataFrame by two group variables and do calculations on each group. As I want to mix columns, I use dataframe.groupby.apply The following code works but is inexplicably slow. 3 seconds to aggregate 4000 rows. When I change the code t...
pandas groupby.apply is slow, even on small DataSets
I want to aggregate a pandas DataFrame by two group variables and do calculations on each group. As I want to mix columns, I use dataframe.groupby.apply The following code works but is inexplicably slow. 3 seconds to aggregate 4000 rows. When I change the code to one group variable, it is just half the time, maybe a li...
[ "You'll get better performance if you restrict yourself to only those functions provided by pandas.\nFor instance...\ndef totime():\n df['c*d'] = df['c']*df['d']\n d = df.groupby(['group','grupp'])['c*d'].sum().rename('c_d_prodsum')\n\n%timeit totime()\n\nshows 842 µs ± 3.67 µs per loop (mean ± std. dev. of 7...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074455854_dataframe_pandas_python.txt
Q: How to convert nested object to nested dictionary in python I have an object Entry with following fields as id, scene_info and rating. As can be seen, the object has attributes that are types to other classes Scene and Item. I want to convert this object to dictionary. Entry(id=None, scene_info=Scene(Recipes=[Item...
How to convert nested object to nested dictionary in python
I have an object Entry with following fields as id, scene_info and rating. As can be seen, the object has attributes that are types to other classes Scene and Item. I want to convert this object to dictionary. Entry(id=None, scene_info=Scene(Recipes=[Item(ID='rec.chicky-nuggies', SpawnerIdx=0), Item(ID='rec.impossible-...
[ "I usually do it this way:\nclass Bar:\n # child class\n # some init code...\n\n def encode(self):\n return vars(self)\n\nclass Foo:\n # parent class\n # some init code...\n\n def encode(self):\n return vars(self)\n\n def to_json(self, indent=None):\n return json.dumps(self...
[ 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "pydantic", "python" ]
stackoverflow_0063893843_dictionary_pydantic_python.txt
Q: how i can skip Please enter your phone (or bot token)? I have several telegram accounts, and at startup, some are asked to enter data. How can I skip this input so that the script continues to run? my example is not working for f in glob.iglob("*.session"): # generator, search immediate subdirectories print...
how i can skip Please enter your phone (or bot token)?
I have several telegram accounts, and at startup, some are asked to enter data. How can I skip this input so that the script continues to run? my example is not working for f in glob.iglob("*.session"): # generator, search immediate subdirectories print(f.rsplit('.', 1)[0]) name_file = f.rsplit('.', 1)[0] ...
[ "Done\ntry:\n\nclient = TelegramClient(session=name_file, api_id=api_id, api_hash=api_hash)\nawait client.connect()\nif not await client.is_user_authorized():\n print(\"Error authorisation\")\n continue\n await send_mes_to_users(client)\nexcept errors.rpcerrorlist.PhoneNumberInvalidError:\n print('fail ...
[ 0 ]
[]
[]
[ "python", "telegram", "telethon" ]
stackoverflow_0074461392_python_telegram_telethon.txt
Q: Python list of tuples: increase number of tuple members I have a list of tuples with the pattern "id", "text", "language" like this: a = [('1', 'hello', 'en'), ...] I would like to increase number of tuple members to "id", "text", "language", "color": b = [('1', 'hello', 'en', 'red'), ...] What is the correct wa...
Python list of tuples: increase number of tuple members
I have a list of tuples with the pattern "id", "text", "language" like this: a = [('1', 'hello', 'en'), ...] I would like to increase number of tuple members to "id", "text", "language", "color": b = [('1', 'hello', 'en', 'red'), ...] What is the correct way of doing this? Thank you.
[ "Since a tuple is immutable you have to create new tuples. I assume you want to add this additional value to every tuple in the list.\na = [('1', 'hello', 'en'), ('2', 'hi', 'en')]\ncolor = 'red'\n\na = [(x + (color,)) for x in a]\nprint(a)\n\nThe result is [('1', 'hello', 'en', 'red'), ('2', 'hi', 'en', 'red')].\n...
[ 2, 1, 1 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074462061_list_python_tuples.txt
Q: Pygame ball bounce left to right of screen my Python code has a circle which moves from the right of the screen to the left but it stops. I would like it to bounce off the left edge and continue moving to the right and then bounce off the right edge to the left and so on. I think I'm missing a line. I have tried s...
Pygame ball bounce left to right of screen
my Python code has a circle which moves from the right of the screen to the left but it stops. I would like it to bounce off the left edge and continue moving to the right and then bounce off the right edge to the left and so on. I think I'm missing a line. I have tried several things but it doesn't seem to be working....
[ "you could define a veriable xSpeed which is initially positive.\nevery frame you would add xSpeed to the current x Position.\nwhen ever the ball hits the right or left wall xSpeed's sign should get flipped.\n", "You need to change your move method a bit, you need to remove the else blocks as they mess up ball's ...
[ 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074462066_pygame_python.txt
Q: Grey box appearing instead of image in Tkinter I am trying to add a small icon next to one of my buttons for my app, however when I import the image and place it in the window it is just a grey box. The image I am adding is not transparent and in a jpg format, I have tried a png format also, ideally I would want i...
Grey box appearing instead of image in Tkinter
I am trying to add a small icon next to one of my buttons for my app, however when I import the image and place it in the window it is just a grey box. The image I am adding is not transparent and in a jpg format, I have tried a png format also, ideally I would want it to accept a transparent png. My window has 2 frame...
[]
[]
[ "You are probably making a bad reference to the path of the image file.\nI bet this image is on the same folder of the .py file but that's not how python works.\nYou will need to get OS. PATH and make a reference to your source folder.\n" ]
[ -1 ]
[ "image", "python", "tkinter" ]
stackoverflow_0074462156_image_python_tkinter.txt
Q: Removing decimals from strings I'm having an introductory course in python right now and i get into some troubles with the task. I have two strings in format: a b c d e f g h i l I need to get this strings from .txt file,convert them as matrix to vertical format like this: a f b g c h d i e l and put into anot...
Removing decimals from strings
I'm having an introductory course in python right now and i get into some troubles with the task. I have two strings in format: a b c d e f g h i l I need to get this strings from .txt file,convert them as matrix to vertical format like this: a f b g c h d i e l and put into another .txt file, without using the num...
[ "Change float to int. float contains decimals. int does not.\n", "Here is the solution as much as I understand your problem\nwith open('input.txt') as f:\n cols = []\n for row in f.readlines():\n col = [int(float(i)) for i in row.split()]\n cols.append(col)\nnew_rows = []\nfor i in range(len(c...
[ 0, 0 ]
[]
[]
[ "decimal", "matrix", "python", "string" ]
stackoverflow_0074461301_decimal_matrix_python_string.txt
Q: Single log line As a developer, I want a single log line with OpenTelemetry Logs. Using the following example I am able to use Otel _logs, but they are emitted on several lines, which makes correlating difficult. common.py import logging from opentelemetry.sdk._logs import ( LogEmitterProvider, LoggingHa...
Single log line
As a developer, I want a single log line with OpenTelemetry Logs. Using the following example I am able to use Otel _logs, but they are emitted on several lines, which makes correlating difficult. common.py import logging from opentelemetry.sdk._logs import ( LogEmitterProvider, LoggingHandler, set_log_em...
[ "I had a similar issue with the ConsoleSpanExporter and solved this by writing a custom formatter:\nfrom os import linesep\n\nfrom opentelemetry.sdk.trace import ReadableSpan, TracerProvider\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter\n\ndef log_formatter_oneline(span: Readab...
[ 0 ]
[ "You can use a combination of stringifying and replacing your log, like so!\nlog_as_str = str(log)\nprint(log_as_str.replace(\"\\n\", \"\"))\n\nIf your log is a dict(), it should work fine. In case, you can use json.dumps(log)\n" ]
[ -1 ]
[ "open_telemetry", "python" ]
stackoverflow_0072968235_open_telemetry_python.txt
Q: the user created in the admin panel cannot log in to the admin panel I have a custom user model: class CustomUser(AbstractUser): ACCESS_LEVELS = ( ('user', 'Авторизованный пользователь'), ('admin', 'Администратор') ) email = models.EmailField( max_length=254, unique=True...
the user created in the admin panel cannot log in to the admin panel
I have a custom user model: class CustomUser(AbstractUser): ACCESS_LEVELS = ( ('user', 'Авторизованный пользователь'), ('admin', 'Администратор') ) email = models.EmailField( max_length=254, unique=True, verbose_name='Эл. почта' ) access_level = models.CharFie...
[ "Use UserAdmin[Django-GitHub] to register UserModel. It will provide the functionality to hash the password when you enter the password in admin panel so:\nfrom django.contrib.auth.admin import UserAdmin\nfrom .models import CustomUser\n\nclass CustomUserAdmin(UserAdmin):\n pass\n\nadmin.site.register(CustomUser...
[ 2 ]
[]
[]
[ "django", "django_4.1", "django_admin", "python" ]
stackoverflow_0074461881_django_django_4.1_django_admin_python.txt
Q: Python Selenium driver.get() not working within a for loop The code below logs into a YouTube account, and once logged in, it should visit a few YouTube videos. The issue is: If I do a simple direct link like here, it works driver.get('https://www.youtube.com/watch?v=FFDDN1C1MEQ') If I do a loop to visit multipl...
Python Selenium driver.get() not working within a for loop
The code below logs into a YouTube account, and once logged in, it should visit a few YouTube videos. The issue is: If I do a simple direct link like here, it works driver.get('https://www.youtube.com/watch?v=FFDDN1C1MEQ') If I do a loop to visit multiple links i get an error: raise exception_class(message, screen, s...
[ "I think you have bad URL format in urls.txt\nTry to debug URL like this:\nfrom selenium.common.exceptions import InvalidArgumentException\n\nfor url in urls:\n try: \n driver.get(url)\n except InvalidArgumentException:\n print(url)\n\n" ]
[ 1 ]
[ "I solved this with import time, time.sleep(0.5) before driver.get().\n" ]
[ -1 ]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0053032043_python_selenium_selenium_webdriver.txt
Q: Colors not displaying properly matplotlib bar chart I am trying to create a bar chart with one colour per bar. Dataset: Dataset Link When I use the color parameter in a matplotlib bar chart, the colours do not assign one to each bar. They randomly distribute throughout all the bars, with no explicit pattern. This ...
Colors not displaying properly matplotlib bar chart
I am trying to create a bar chart with one colour per bar. Dataset: Dataset Link When I use the color parameter in a matplotlib bar chart, the colours do not assign one to each bar. They randomly distribute throughout all the bars, with no explicit pattern. This is the code: import numpy as np import pandas as pd impor...
[ "Because it will depict the value of your df.price and df.owner in color randomly. I don't know what you're plotting to represent but what if you need to assign a color to each bar. Simply use .set_color for each bar as below example\n graph = plt.bar([1,2,3,4], [10,11,12,13])\n graph[0].set_color('red')\n graph[1]...
[ 1 ]
[]
[]
[ "bar_chart", "matplotlib", "python" ]
stackoverflow_0074461007_bar_chart_matplotlib_python.txt
Q: Python matplotlib barbs/quiver map colors to different sets of values I am trying to create a barb vector plot in matplotlib and map some colors to specific magnitudes: for example, to have vectors with magnitudes between 10 and 20 plotted as blue, and between 20 and 30 as rgb(0,15,40), and so on. The documentatio...
Python matplotlib barbs/quiver map colors to different sets of values
I am trying to create a barb vector plot in matplotlib and map some colors to specific magnitudes: for example, to have vectors with magnitudes between 10 and 20 plotted as blue, and between 20 and 30 as rgb(0,15,40), and so on. The documentation for the barbs and quiver functions (they are similar) mentions the C inpu...
[ "You can get it by discretizing the map.\nimport matplotlib as mpl \nimport pyplot as plt\nfrom numpy import arange,meshgrid,sqrt\n\nu,v = arange(-50,51,10),arange(-50,51,10)\nu,v = meshgrid(u,v)\nx,y = u,v\nC = sqrt(u**2 + v**2)\ncmap=plt.cm.jet\nbounds = [10, 20, 40, 60]\nnorm = mpl.colors.BoundaryNorm(bounds, cm...
[ 3, 0 ]
[]
[]
[ "colors", "matplotlib", "python", "vector" ]
stackoverflow_0011476752_colors_matplotlib_python_vector.txt
Q: Computing log-likelihood on a validation / test set Regression results from Python's statsmodels library include the value llf, which is, I recon, the log-likelihood obtained during fitting. I am, however, interested in log-likelihood on new data, those I use in predict(). Is there a function (even if undocumented...
Computing log-likelihood on a validation / test set
Regression results from Python's statsmodels library include the value llf, which is, I recon, the log-likelihood obtained during fitting. I am, however, interested in log-likelihood on new data, those I use in predict(). Is there a function (even if undocumented) I can call to obtain it? In particular, I am interested...
[ "Computing loglikelihood on new data is not directly possible in statsmodels.\n(see for example https://github.com/statsmodels/statsmodels/issues/7947 )\nThe model loglike method always uses the data, endog, exog and other model specific arrays, that is attached to the model as attributes.\nSeveral models like GLM ...
[ 1 ]
[]
[]
[ "python", "statsmodels" ]
stackoverflow_0074459317_python_statsmodels.txt
Q: Cannot load file containing pickled data - Python .npy I/O I am trying to save a dataframe and a matrix as .npy files with np.save() and then read them using np.load() but I get the following error: File "/Users/sofiafarina/opt/anaconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 457, in load rais...
Cannot load file containing pickled data - Python .npy I/O
I am trying to save a dataframe and a matrix as .npy files with np.save() and then read them using np.load() but I get the following error: File "/Users/sofiafarina/opt/anaconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 457, in load raise ValueError("Cannot load file containing pickled data " ValueE...
[ "I used the syntax below to load the .npy file and it worked.\nnp.load(\"finaldf_p_85_12.npy\",allow_pickle=True)\n\nI think you need to add allow_pickle=True parameter.\n", "TLDR;\nAfter hundreds of search and hours of debugging I found out that the issue was with git-lfs, my files did not get pulled using git-l...
[ 10, 9, 2, 1, 1, 0, 0, 0 ]
[ "Just make sure the file isn't corrupted.\n" ]
[ -2 ]
[ "io", "numpy", "python" ]
stackoverflow_0060191681_io_numpy_python.txt
Q: Getting different Values when using groupby(column)["id"].nunique and trying to add a column using transform I'm trying to count the individual values per group in a dataset and add them as a new column to a table. The first one works, the second one produces wrong values. When I use the following code unique_id_p...
Getting different Values when using groupby(column)["id"].nunique and trying to add a column using transform
I'm trying to count the individual values per group in a dataset and add them as a new column to a table. The first one works, the second one produces wrong values. When I use the following code unique_id_per_column = source_table.groupby("disease").some_id.nunique() I'll get | | disease | some_id | ...
[ "Solution with Series.map if need create column in another DataFrame:\ns = source_table.groupby(\"disease\").some_id.nunique()\n\ntable[\"unique_ids\"] = table[\"disease\"].map(s) \n\n" ]
[ 1 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074462377_group_by_pandas_python.txt
Q: Create columns from strings that are in a list I am trying to create a set of columns from a list taking a string from another column. I have found a temporary solution in this post but it only creates one column if, for example, I have in String1 "I have a dog and a cat". In [7]: df["animal"] = df["String1"].map(...
Create columns from strings that are in a list
I am trying to create a set of columns from a list taking a string from another column. I have found a temporary solution in this post but it only creates one column if, for example, I have in String1 "I have a dog and a cat". In [7]: df["animal"] = df["String1"].map(lambda s: next((animal for animal in search_list if ...
[ "You can use:\nanimals = ['dog', 'cat']\nregex = '|'.join(animals)\n\nout = (df.join(\n df['String1'].str.extractall(fr'\\b({regex})\\b')[0].unstack()\n .rename(columns=lambda x: f'animal_{x+1}')\n )\n .fillna({'animal_1': 'other'})\n )\n\nOutput:\n weight St...
[ 1, 1 ]
[]
[]
[ "list", "pandas", "python", "text_extraction" ]
stackoverflow_0074459380_list_pandas_python_text_extraction.txt
Q: How can I generate my own Fernet key in Python? I've tried something like this but it doesn't seem to be working: from cryptography.fernet import Fernet from base64 import urlsafe_b64encode as b64e bytes_gen = b64e(PASSWORD.encode()) if len(bytes_gen) < 32: bytes_gen += b'=' * (32 - len(bytes_gen))...
How can I generate my own Fernet key in Python?
I've tried something like this but it doesn't seem to be working: from cryptography.fernet import Fernet from base64 import urlsafe_b64encode as b64e bytes_gen = b64e(PASSWORD.encode()) if len(bytes_gen) < 32: bytes_gen += b'=' * (32 - len(bytes_gen)) elif len(bytes_gen) > 32: bytes_gen = by...
[ "You are reading it wrong. The key is a cryptographic keys, which are usually 16, 24 or 32 bytes in size. So the phrase \"Fernet key must be 32 url-safe base64-encoded bytes.\" doesn't mean that the encoding needs to be 32 characters in size, it means that there are 32 bytes that need to be encoded.\nYou seem to wa...
[ 1 ]
[]
[]
[ "byte", "cryptography", "fernet", "python", "valueerror" ]
stackoverflow_0074461900_byte_cryptography_fernet_python_valueerror.txt
Q: Changing level of some columns in multi index I have a data frame that is looking like this (DATA is the year and month of the order) : CUSTOMER_ID NAME DATA COFFEE_SOLD(KG) WATER_SOLD(L) 10000 ALEX 2022 - 01 3 4 10000 ALEX 2022 - 01 5 6 10000 ALEX 2022 - 02 7 8 10001 JOE 2022 - 02 1 1 10001 JOE 2022 - 03 1 ...
Changing level of some columns in multi index
I have a data frame that is looking like this (DATA is the year and month of the order) : CUSTOMER_ID NAME DATA COFFEE_SOLD(KG) WATER_SOLD(L) 10000 ALEX 2022 - 01 3 4 10000 ALEX 2022 - 01 5 6 10000 ALEX 2022 - 02 7 8 10001 JOE 2022 - 02 1 1 10001 JOE 2022 - 03 1 0 I pivoted the df with : df_rap = df...
[ "A possible approach is to overwrite the column values:\ncols = [('', 'CUSTOMER_ID'), ('', 'NAME'),]\nfor t in df_rap.columns[2:]:\n cols.append(t)\n \ndf_rap.columns = pd.MultiIndex.from_tuples(cols)\n\nThis leads to a data frame without the word DATA in it. Which somehow makes sense, as DATA has lost some o...
[ 1 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074402448_dataframe_python.txt
Q: Match strings of different length in two lists of different length Say I have two flat lists of strings: a = ["today", "I", "want", "to", "eat", "some", "cake."] b = ["to", "da", "y", "I", "wa", "nt", "to", "ea", "t", "some", "ca", "ke", "."] Where in list b some strings (not all) of list a are split into multipl...
Match strings of different length in two lists of different length
Say I have two flat lists of strings: a = ["today", "I", "want", "to", "eat", "some", "cake."] b = ["to", "da", "y", "I", "wa", "nt", "to", "ea", "t", "some", "ca", "ke", "."] Where in list b some strings (not all) of list a are split into multiple substrings. Note that the substrings in b that correspond to the strin...
[ "a = [\"today\", \"I\", \"want\", \"to\", \"eat\", \"some\", \"cake.\"]\nb = [\"to\", \"da\", \"y\", \"I\", \"wa\", \"nt\", \"to\", \"ea\", \"t\", \"some\", \"ca\", \"ke\", \".\"]\nc = []\n\nfor element in a:\n temp_list = []\n while \"\".join(temp_list) != element:\n temp_list.append(b.pop(0))\n c....
[ 2, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074458282_list_python_string.txt
Q: Fill pandas dataframe with dictionary elements I have a dataframe df structured as well: Name Surname Nationality Joe Tippy Italian Adam Wesker American I would like to create a new record based on a dictionary whose keys corresponds to the column names: new_record = {'Name': 'Jimmy',...
Fill pandas dataframe with dictionary elements
I have a dataframe df structured as well: Name Surname Nationality Joe Tippy Italian Adam Wesker American I would like to create a new record based on a dictionary whose keys corresponds to the column names: new_record = {'Name': 'Jimmy', 'Surname': 'Turner', 'Nationality': 'Australian'} ...
[ "IIUC replace missing values in next step:\nnew_record = {'Surname': 'Turner', 'Nationality': 'Australian'}\ndf = pd.concat([df, pd.DataFrame([new_record])], ignore_index=True).fillna('')\n\nprint (df)\n Name Surname Nationality\n0 Joe Tippy Italian\n1 Adam Wesker American\n2 Turner Australia...
[ 2, 1 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074462398_dataframe_dictionary_pandas_python.txt
Q: TypeError: unhashable type: 'numpy.ndarray' when trying to append to a dictionary I'm trying to append values to my dictionary, but I can't solve this error. This is my dictionary: groups = {'group1': array([450, 449.]), 'group2': array([490, 489.]), 'group3': array([568, 567.])} then I have a txt file (loaded u...
TypeError: unhashable type: 'numpy.ndarray' when trying to append to a dictionary
I'm trying to append values to my dictionary, but I can't solve this error. This is my dictionary: groups = {'group1': array([450, 449.]), 'group2': array([490, 489.]), 'group3': array([568, 567.])} then I have a txt file (loaded using np.loadtxt) with many data and I have to iterate over this file and if a certain c...
[ "The reason why you got this error is that you tried to use data of unhashable type numpy.ndarray as the key of a dictionary. The links below are useful for your question.\n\nMapping Types - dict\n\n\nA mapping object maps hashable values to arbitrary objects.\n\n\ndict.setdefault(key[, default]) - It invokes a has...
[ 0, 0 ]
[]
[]
[ "append", "dictionary", "numpy_ndarray", "python" ]
stackoverflow_0074447402_append_dictionary_numpy_ndarray_python.txt