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: Filling column based on conditions In the DataFrame below df = pd.DataFrame([('Ve_Paper', 'Buy', '-','Canada',np.NaN), ('Ve_Gasoline', 'Sell', 'Done','Britain',np.NaN), ('Ve_Water', 'Sell','-','Canada,np.NaN), ('Ve_Plant', 'Buy', 'Good','China',np.NaN), ...
Filling column based on conditions
In the DataFrame below df = pd.DataFrame([('Ve_Paper', 'Buy', '-','Canada',np.NaN), ('Ve_Gasoline', 'Sell', 'Done','Britain',np.NaN), ('Ve_Water', 'Sell','-','Canada,np.NaN), ('Ve_Plant', 'Buy', 'Good','China',np.NaN), ('Ve_Soda', 'Sell', 'Process'...
[ "You have two conditions ,we can do it with np.select\nconda = df.Action.eq('Sell')\ncondb = df.Status.eq('-')\ndf['value'] = np.select([conda&condb, conda&~condb],\n [df.Name.str.split('_').str[1],df.Country.str[:2]],\n default = np.nan)\ndf\nOut[343]: \n Name...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074257918_dataframe_pandas_python.txt
Q: Ordering Dictionary Values in Python How can I order the values for my dictionary? sorted_activities = sorted(activity_dicc.items(),reverse=True) for activity,duration in sorted_activities : print(activity,duration) activity_dicc is my dictionary, activity is the key an...
Ordering Dictionary Values in Python
How can I order the values for my dictionary? sorted_activities = sorted(activity_dicc.items(),reverse=True) for activity,duration in sorted_activities : print(activity,duration) activity_dicc is my dictionary, activity is the key and duration is the value. When I run my cod...
[]
[]
[ "You cannot sort dictionaries. By definition they are unsorted key-value pairs. You should create a sorted list with the dictionary keys and run a loop to print the dictionary values that match the keys.\nsorted_activities = sorted(activity_dicc.keys(), reverse=True)\nfor activity in sorted_activities:\n print(a...
[ -1 ]
[ "python" ]
stackoverflow_0074257995_python.txt
Q: Order limit backtesting I started to study "backtesting" and during testing I encountered one incomprehensible situation. class MyCandlesStrat(Strategy): def init(self): super().init() self.signal1 = self.I(SIGNAL) def next(self): super().next() if self.signal1==1: ...
Order limit backtesting
I started to study "backtesting" and during testing I encountered one incomprehensible situation. class MyCandlesStrat(Strategy): def init(self): super().init() self.signal1 = self.I(SIGNAL) def next(self): super().next() if self.signal1==1: self.buy() elif s...
[ "Try this, it would probably work for you:\nif len(self.trades) > 0:\n if self.trades[-1].is_long and <your logic>:\n self.trades[-1].close()\n elif self.trades[-1].is_short and <your logic>:\n self.trades[-1].close()\n\nPD: The index for self.trades doesn't have to be the last trade, it's your ...
[ 0 ]
[]
[]
[ "back_testing", "pandas", "python", "python_3.x" ]
stackoverflow_0073427195_back_testing_pandas_python_python_3.x.txt
Q: I get an error while installing ipykernel on vscode When I was running a jupyter note on vscode ` # Load the libraries to be used in the Analysis import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns impor wat warnings # Setup libraries settings and options ## Pandas setup ...
I get an error while installing ipykernel on vscode
When I was running a jupyter note on vscode ` # Load the libraries to be used in the Analysis import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns impor wat warnings # Setup libraries settings and options ## Pandas setup pd.set_option('display.max_columns', None) ## matplotlib...
[ "\n'c:/Users/Samir/AppData/Local/Programs/Python/Python311/python.exe -m\npip install ipykernel -U --user --force-reinstall'\n\nObviously, it has told you how to install.\nBut please note that this is an environmental issue, so make sure you choose the correct interpreter.\nYou can use the shortcut key Ctrl+Shift+ ...
[ 0 ]
[]
[]
[ "jupyter_notebook", "pip", "python", "visual_studio_code" ]
stackoverflow_0074231947_jupyter_notebook_pip_python_visual_studio_code.txt
Q: How to decrypt pgp armored string using PGPy when the armored string isn't from PGPy? I'm creating a script that communicates with a server that is using PGP encryption to encrypt it's responses. I can request the public key of the server, and use that key to encrypt my request via the PGPy library, and the server...
How to decrypt pgp armored string using PGPy when the armored string isn't from PGPy?
I'm creating a script that communicates with a server that is using PGP encryption to encrypt it's responses. I can request the public key of the server, and use that key to encrypt my request via the PGPy library, and the server is able to decrypt it and respond. The scripts encrypted request has it's public key in it...
[ "You should be able to create a PGPMessage object from the ascii armored string in memory by using pgpy.PGPMessage.from_blob()\ndef get_token_from_payload(encrypted_payload):\n print(\"Payload: \", encrypted_payload)\n privkey, _ = pgpy.PGPKey.from_file('private.key')\n message_blob = pgpy.PGPMessage.from_blob(e...
[ 0 ]
[]
[]
[ "encryption", "gnupg", "pgp", "python" ]
stackoverflow_0072744900_encryption_gnupg_pgp_python.txt
Q: Installed PyPy + NumPy, but I experienced no improvement in performance. Is this normal? OS: Ubuntu 14.04 CPU: i7 I Installed PyPy+Numpy: sudo add-apt-repository ppa:pypy/ppa sudo apt-get update sudo apt-get install pypy pypy-dev pip install git+https://bitbucket.org/pypy/numpy.git Ran following code with python...
Installed PyPy + NumPy, but I experienced no improvement in performance. Is this normal?
OS: Ubuntu 14.04 CPU: i7 I Installed PyPy+Numpy: sudo add-apt-repository ppa:pypy/ppa sudo apt-get update sudo apt-get install pypy pypy-dev pip install git+https://bitbucket.org/pypy/numpy.git Ran following code with python and pypy: import numpy as np import time start = time.clock() for i in range(5): vv = n...
[ "Per documentation of PyPy here, numpy under PyPy is slow:\n\nAt the moment of writing (October 2017) the main drawback of numpy is that cpyext is infamously slow\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "performance", "pypy", "python" ]
stackoverflow_0031322632_numpy_performance_pypy_python.txt
Q: How to merge audio and video in bytes using ffmpeg? I'm trying to merge a video with its seperate audio file in Python. I have both the video and the audio as bytes in memory and I would like to know how to allow ffmpeg-python to merge them. I have seen it done through ffmpeg.concat and by reading the files from d...
How to merge audio and video in bytes using ffmpeg?
I'm trying to merge a video with its seperate audio file in Python. I have both the video and the audio as bytes in memory and I would like to know how to allow ffmpeg-python to merge them. I have seen it done through ffmpeg.concat and by reading the files from disk using ffmpeg.input, but when my program downloads the...
[ "Yes it is possible to merge audio and video from memory using ffmpeg-python.\nYou need to tell FFmpeg to read the data from stdin, and redirect the output to stdout, here is the documentation: FFmpeg protocols pipe documentation.\nBut, in the documentation, they show examples written in shell. With shell specific ...
[ 2 ]
[]
[]
[ "ffmpeg", "python" ]
stackoverflow_0074256808_ffmpeg_python.txt
Q: How to make the discord bot add the user id to the code? I wanted a bot I wanted the bot when the user wrote the command /add_admin (here is the user id ) And the bot added it either to a separate file or to the code admin = [user id] and I don't know how to do it, I write the code in Replit python I haven't tried...
How to make the discord bot add the user id to the code?
I wanted a bot I wanted the bot when the user wrote the command /add_admin (here is the user id ) And the bot added it either to a separate file or to the code admin = [user id] and I don't know how to do it, I write the code in Replit python I haven't tried anything because I don't know how
[ "I would store it in a .json file.\nSay you created an admins.json in a separate /admins folder, this is how I would set it up:\nasync def add_admin(ctx, id):\n # If you want there to be only one admin\n dict = {\"Admin\": id}\n with open('./admins/admins.json', \"r+\") as f:\n json....
[ 0 ]
[]
[]
[ "bots", "discord.py", "python" ]
stackoverflow_0074257495_bots_discord.py_python.txt
Q: "Verifying transaction: failed" Error in updating anaconda form anaconda prompt I had been updating anaconda form "anaconda Prompt", i got following error i could not resolve the error can anyone please help me to resolve it Downloading and Extracting Packages libxslt-1.1.33 | 499 KB | ###################...
"Verifying transaction: failed" Error in updating anaconda form anaconda prompt
I had been updating anaconda form "anaconda Prompt", i got following error i could not resolve the error can anyone please help me to resolve it Downloading and Extracting Packages libxslt-1.1.33 | 499 KB | #################################### | 100% libtiff-4.1.0 | 997 KB | #########################...
[ "This error is about you can not update setuptools in conda env, so you should update conda dependency as fllow 'conda update --update-deps conda' first. This worked for me.\n", "After trying a number of way, I Could not resolve the issue. Finally, I uninstalled the anaconda, downloaded latest version form the an...
[ 2, 0 ]
[ "Have you tried the console run on administration mode? If not, verification would be failed due to the file writing authority absence.\n" ]
[ -1 ]
[ "anaconda", "anaconda3", "anaconda_cluster", "python", "spyder" ]
stackoverflow_0060605055_anaconda_anaconda3_anaconda_cluster_python_spyder.txt
Q: How can I find a word and print it along with his next word in Python I have the following list: pre = ["unable to", "would not", "was not", "did not", "there is not", "could not", "failed to"] From dataframe column I want to find texts that have the words of the list in order to generate a new column that can pr...
How can I find a word and print it along with his next word in Python
I have the following list: pre = ["unable to", "would not", "was not", "did not", "there is not", "could not", "failed to"] From dataframe column I want to find texts that have the words of the list in order to generate a new column that can print these words along with the next word, for example, in a column cell the...
[ "You can loop over every prefix in the list and check for the prefix using .find(). If it is found, you can change the prefix to the case of event and append the next word. Like this:\ndef matcher(event):\n pres = [\"unable to\", \"would not\", \"was not\", \"did not\", \"there is not\", \"could not\", \"failed ...
[ 0 ]
[]
[]
[ "loops", "multiple_columns", "pandas", "python", "string" ]
stackoverflow_0074258117_loops_multiple_columns_pandas_python_string.txt
Q: Can´t consume messages from topic I have the following code: from confluent_kafka.admin import AdminClient, NewTopic a = AdminClient({'bootstrap.servers': 'localhost:9092'}) new_topics = [NewTopic(topic, num_partitions=3, replication_factor=1) for topic in ["topic1", "topic2"]] fs = a.create_topics(new_topics) ...
Can´t consume messages from topic
I have the following code: from confluent_kafka.admin import AdminClient, NewTopic a = AdminClient({'bootstrap.servers': 'localhost:9092'}) new_topics = [NewTopic(topic, num_partitions=3, replication_factor=1) for topic in ["topic1", "topic2"]] fs = a.create_topics(new_topics) for topic, f in fs.items(): try: ...
[ "Your producer code is writing to mytopic topic. Which doesn't match your create script or what your consumer has subscribed to.\nAlso, if you don't want it to print None, then move the print statement inside the if statement since poll function can return None\nAs commented, you may also want to try further debugg...
[ 1 ]
[]
[]
[ "apache_kafka", "confluent_kafka_python", "python" ]
stackoverflow_0074256393_apache_kafka_confluent_kafka_python_python.txt
Q: VS Code and Jupyter notebook problems with the python interpreter Im currently doing a project in VS Code using Jupyter Notebook, however I have some problems with the python interpreter. The problem seem to do with VS Code using two different interpreters. I have chosen, what I think is the right interpreter, in ...
VS Code and Jupyter notebook problems with the python interpreter
Im currently doing a project in VS Code using Jupyter Notebook, however I have some problems with the python interpreter. The problem seem to do with VS Code using two different interpreters. I have chosen, what I think is the right interpreter, in the upper right corner, namely However, when I check what version of P...
[ "The vscode integrated terminal uses the built-in powershell or cmd of windows. If you type python in the terminal, it will open the interactive terminal of the python version pointed to by the system environment variable. What you choose in the upper right corner of jupyter is just the jupyter notebook kernel, not...
[ 0 ]
[]
[]
[ "interpreter", "jupyter_notebook", "python", "version", "visual_studio_code" ]
stackoverflow_0074237894_interpreter_jupyter_notebook_python_version_visual_studio_code.txt
Q: python align picture on same picture/file my purpose is using pi camera, capture picture of qr code (till here I already done), and align the picture on one platform to compare them are printed well. so far I can capture the picture and save it on rasberry destop environment: raspberrypi 4 Model B 32 bit, linux 5....
python align picture on same picture/file
my purpose is using pi camera, capture picture of qr code (till here I already done), and align the picture on one platform to compare them are printed well. so far I can capture the picture and save it on rasberry destop environment: raspberrypi 4 Model B 32 bit, linux 5.15.61-v8; execute python3 script; logitech USB ...
[ "This two not can be the hint to the solution\nCombine several images horizontally with Python\nPython Image Library: How to combine 4 images into a 2 x 2 grid?\n\nfrom picamera import PiCamera\nimport time\nfrom PIL import Image\n\ndef join_images(*rows, bg_color=(0, 0, 0, 0), alignment=(0.5, 0.5)):\n rows = [\...
[ 0 ]
[]
[]
[ "alignment", "python" ]
stackoverflow_0074234093_alignment_python.txt
Q: Group Dataframe using values of a column to group rows So I have a Dataset of Patients that would look like this (I'm using toy values here for simplicity). I wanted to sort the data frame by the discharge values and then group it according to Patients. Everything else in my preprocessing happens perfectly, and m...
Group Dataframe using values of a column to group rows
So I have a Dataset of Patients that would look like this (I'm using toy values here for simplicity). I wanted to sort the data frame by the discharge values and then group it according to Patients. Everything else in my preprocessing happens perfectly, and my it groups the way it is supposed to (gives me clusters of ...
[ "\nI wanted to sort the data frame by the discharge values and then group it according to Patients.\n\nIt doesn't sound like grouping will solve your problem. Usually grouping is used to get an average of each group, or reduce the amount of data. I think what you should do is sorting.\nYou could use sort_values() t...
[ 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python", "python_3.x" ]
stackoverflow_0074257897_dataframe_group_by_pandas_python_python_3.x.txt
Q: VSCode Terminal output - is not processed update: tried to solve this on a fresh start in a newly installed VSCode on EndeavourOS i installed too python and code-runner and wanted to do set the output of code to the terminal: according this video https://www.youtube.com/watch?v=9o4gDQvVkLU&list=PLIHcvkHKg_aNb0KS81...
VSCode Terminal output - is not processed
update: tried to solve this on a fresh start in a newly installed VSCode on EndeavourOS i installed too python and code-runner and wanted to do set the output of code to the terminal: according this video https://www.youtube.com/watch?v=9o4gDQvVkLU&list=PLIHcvkHKg_aNb0KS813WkPGhWtkNmnHJX&index=2 After installing python...
[ "Add the following code directly to settings.json:\n\"code-runner.runInTerminal\": true,\n\nThis line doesn't need to be in editor.codeActionsOnSave.\n\n" ]
[ 1 ]
[]
[]
[ "json", "linux", "python", "visual_studio_code" ]
stackoverflow_0074257280_json_linux_python_visual_studio_code.txt
Q: Python socket throwing the following error ConnectionResetError: [Errno 54] Connection reset by peer I have been trying to create a messaging service in python using sockets. I have written the code to host two connections and allow one to send messages to the other using username and host_addr. But every time I t...
Python socket throwing the following error ConnectionResetError: [Errno 54] Connection reset by peer
I have been trying to create a messaging service in python using sockets. I have written the code to host two connections and allow one to send messages to the other using username and host_addr. But every time I try to connect the second client and send a message from the first getting the following error. ConnectionR...
[ "Client is sending 2 messages and then receiving one.\nBut server just listen once and then send one or two packages.\nChronologically:\n\nClient sends a package, and server reads it.\nThen both client and server try to send a package. Both packages that won't meet a listening peer.\nThen client try to receive a pa...
[ 0 ]
[]
[]
[ "messaging", "python", "sockets" ]
stackoverflow_0074258168_messaging_python_sockets.txt
Q: Why is PyMongo 3 giving ServerSelectionTimeoutError? I'm using: Python 3.4.2 PyMongo 3.0.2 mongolab running mongod 2.6.9 uWSGI 2.0.10 CherryPy 3.7.0 nginx 1.6.2 uWSGI start params: --socket 127.0.0.1:8081 --daemonize --enable-threads --threads 2 --processes 2 I setup my MongoClient ONE time: self.mongo_client =...
Why is PyMongo 3 giving ServerSelectionTimeoutError?
I'm using: Python 3.4.2 PyMongo 3.0.2 mongolab running mongod 2.6.9 uWSGI 2.0.10 CherryPy 3.7.0 nginx 1.6.2 uWSGI start params: --socket 127.0.0.1:8081 --daemonize --enable-threads --threads 2 --processes 2 I setup my MongoClient ONE time: self.mongo_client = MongoClient('mongodb://user:pw@host.mongolab.com:port/myd...
[ "We're investigating this problem, tracked in PYTHON-961. You may be able to work around the issue by passing connect=False when creating instances of MongoClient. That defers background connection until the first database operation is attempted, avoiding what I suspect is a race condition between spin up of MongoC...
[ 70, 28, 15, 14, 7, 5, 3, 3, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "This has been fixed in PyMongo with this pull_request.\n", "This problem solved when I just toggled the MongoDB in the services to running which was stopped previously.\n", "\nFirst set up the MongoDB environment.\nRun this on CMD - \"C:\\Program Files\\MongoDB\\Server\\3.6\\bin\\mongod.exe\"\nOpen another CMD...
[ -1, -1, -2 ]
[ "mlab", "mongodb", "pymongo_3.x", "python", "uwsgi" ]
stackoverflow_0031030307_mlab_mongodb_pymongo_3.x_python_uwsgi.txt
Q: Python module not found even though its installed Does anyone else have this issue? For reference check this screenshot: PIP is also up to date and I already tried reinstalling it but it didn't work neither. I'm using VS Code. It also worked just fine yesterday but today it didn't anymore for some reason. A: Yo...
Python module not found even though its installed
Does anyone else have this issue? For reference check this screenshot: PIP is also up to date and I already tried reinstalling it but it didn't work neither. I'm using VS Code. It also worked just fine yesterday but today it didn't anymore for some reason.
[ "Your mss package is installed locally, but you are using a virtual environment to run code.\n\nTwo solutions:\n1. Switch the interpreter to the local interpreter, which is the c:\\Users\\Anwender\\AppData\\Local\\.... in your picture\n\nCtrl+Shift+P to open the command palette, search for and select Python:Select ...
[ 2, 0 ]
[ "If you are using multiple versions of python or use any python version in appdata, without venv, you can try running \"pip install mss\" from elevated (administrator) cmd instance within python install directory/scripts, shown on the console image above. If it is not the right python version used in the project, s...
[ -1, -2 ]
[ "python", "visual_studio_code" ]
stackoverflow_0074256342_python_visual_studio_code.txt
Q: PHP CGI script in Apache Thrift get error "CGI script exit status 0xff00" I'm reading the Learning Apache Thrift book by Krzysztof Rakowski. In chapter 3 (found [here]). The author explains how to execute the PHP script in server side with python CGI, but the book was using python2.7, so I did some modification to...
PHP CGI script in Apache Thrift get error "CGI script exit status 0xff00"
I'm reading the Learning Apache Thrift book by Krzysztof Rakowski. In chapter 3 (found [here]). The author explains how to execute the PHP script in server side with python CGI, but the book was using python2.7, so I did some modification to let it adapt to python3. I was using "python3 runserver.py" command to run the...
[ "Finally I found that it is due to the thrift class reference of \"ThriftClassLoader.php\".\nIn \"ThriftClassLoader.php\", it refers to '/Thrift/ClassLoader/ThriftClassLoader.php' with the following sentence:\nrequire_once THRIFT_PHP_LIB.'/Thrift/ClassLoader/ThriftClassLoader.php'; \n\nBut with the thrift package y...
[ 0 ]
[]
[]
[ "cgi", "php", "python", "thrift" ]
stackoverflow_0074250373_cgi_php_python_thrift.txt
Q: (Python) (python-imaging-library : pillow) after .join succfully to image, but .save isn't work python align picture as 2x2 and .show is success. But how can I save it? cause my .save isn't work the python script: from picamera import PiCamera import time from PIL import Image def join_images(*rows, bg_color=(0...
(Python) (python-imaging-library : pillow) after .join succfully to image, but .save isn't work
python align picture as 2x2 and .show is success. But how can I save it? cause my .save isn't work the python script: from picamera import PiCamera import time from PIL import Image def join_images(*rows, bg_color=(0, 0, 0, 0), alignment=(0.5, 0.5)): rows = [ [image.convert('RGBA') for image in row] ...
[]
[]
[ "don't use .show() and assign new value in the same time new_image = join_images\nbelow is how I corrected it\nfrom picamera import PiCamera\nimport time\nfrom PIL import Image\n\ndef join_images(*rows, bg_color=(0, 0, 0, 0), alignment=(0.5, 0.5)):\n rows = [\n [image.convert('RGBA') for image in row]\n ...
[ -1 ]
[ "python", "python_3.x", "python_imaging_library", "save" ]
stackoverflow_0074258224_python_python_3.x_python_imaging_library_save.txt
Q: Eliminate unigrams in char-level TF-IDF I would like to extract unique combinations of letters within words using the scikit-learn TF-IDF vectorizer for an NLP problem. However, I'm not interested in individual letters, but letter combinations, so that, e.g. "the" should produce "th" and "he" but not "t", "h" or "...
Eliminate unigrams in char-level TF-IDF
I would like to extract unique combinations of letters within words using the scikit-learn TF-IDF vectorizer for an NLP problem. However, I'm not interested in individual letters, but letter combinations, so that, e.g. "the" should produce "th" and "he" but not "t", "h" or "e". My understanding is I should be able to u...
[ "I constructed a callable to pass to analyzer. It is stolen from based on the function from the source code of TfidfVectorizer used when analyzer is set to 'char_wb':\ndef char_wb_ngrams(text_document, ngram_range):\n \"\"\"Callable for TfidfVectorizer analyzer, based on _char_wb_ngrams from TfidfVectorizer sour...
[ 0 ]
[]
[]
[ "feature_extraction", "python", "scikit_learn", "tf_idf" ]
stackoverflow_0074257904_feature_extraction_python_scikit_learn_tf_idf.txt
Q: Python time series graph not plotting y values correctly I have this data frame: Year production imports 2003 2,061,995 $55,812,008,171 2004 1,991,394 $78,277,321,635 2005 1,892,095 $107,478,346,132 2006 1,856,340 $131,528,352,871 2007 1,851,974 $147,375,398,002 I plotted both lines with this code: import p...
Python time series graph not plotting y values correctly
I have this data frame: Year production imports 2003 2,061,995 $55,812,008,171 2004 1,991,394 $78,277,321,635 2005 1,892,095 $107,478,346,132 2006 1,856,340 $131,528,352,871 2007 1,851,974 $147,375,398,002 I plotted both lines with this code: import pandas as pd import matplotlib.pyplot as plt df =...
[ "Please, include a minimal reproducible example. Including imports. And minimal data in the code. I did it for you so as an example of what it means: anybody can now just cut and past your code and see the problem by themselves, and then try to correct it (I had to work way more to reformat your question so that it...
[ 0 ]
[]
[]
[ "python", "time_series" ]
stackoverflow_0074258293_python_time_series.txt
Q: Updating column values based on multiple conditions In the DataFrame below df = pd.DataFrame([('Ve_Paper', 'Buy', '-','Canada',np.NaN), ('Ve_Gasoline', 'Sell', 'Done','Britain',np.NaN), ('Ve_Water', 'Sell','-','Canada,np.NaN), ('Ve_Plant', 'Buy', 'Good','China'...
Updating column values based on multiple conditions
In the DataFrame below df = pd.DataFrame([('Ve_Paper', 'Buy', '-','Canada',np.NaN), ('Ve_Gasoline', 'Sell', 'Done','Britain',np.NaN), ('Ve_Water', 'Sell','-','Canada,np.NaN), ('Ve_Plant', 'Buy', 'Good','China',np.NaN), ('Ve_Soda', 'Sell', 'Process'...
[ "\nI do not see any problem in here. Could you please elaborate it more if possible?\nI am sharing my piece of code below:\nimport pandas as pd\nimport numpy as np\ndf = pd.DataFrame([('Ve_Paper', 'Buy', '-','Canada',np.NaN),\n ('Ve_Gasoline', 'Sell', 'Done','Britain',np.NaN),\n ('...
[ 0, 0 ]
[]
[]
[ "database", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074256848_database_dataframe_numpy_pandas_python.txt
Q: Plotly Dash application not running I am attempting to run the following code from jupyter notebook: import dash import dash_core_components as dcc import dash_html_components as html external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_sty...
Plotly Dash application not running
I am attempting to run the following code from jupyter notebook: import dash import dash_core_components as dcc import dash_html_components as html external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div(children...
[ "Out of the box, as stated by a previous answer, you can't run debug=True. Hence people stick with:\nOn jupyter, do:\nif __name__ == '__main__':\n app.run_server()\n\non editor such as VSCode, you can do:\nif __name__ == '__main__':\n app.run_server(debug=True)\n\nYou're still keen on using Jupyter instead of...
[ 11, 3, 0, 0 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0059587439_plotly_dash_python.txt
Q: Type checking with dynamic class creation in Python I want to create a class dynamically: from pydantic import BaseConfig CompanyConfig: Type[BaseConfig] = type("CompanyConfig", (BaseConfig,), {}) Now, PyCharm 2022 complains Expected type 'Type[BaseConfig]', got 'type' instead. I can fix it by augmenting the typ...
Type checking with dynamic class creation in Python
I want to create a class dynamically: from pydantic import BaseConfig CompanyConfig: Type[BaseConfig] = type("CompanyConfig", (BaseConfig,), {}) Now, PyCharm 2022 complains Expected type 'Type[BaseConfig]', got 'type' instead. I can fix it by augmenting the type hint with "| type" or "| typing.Any": CompanyConfig: Ty...
[ "I didn't receive a warning in Pycharm 2022.2.3 CE on macOS for below codes\nCompanyConfig: Type[int] = type(\"CompanyConfig\", (int,), {})\n\nbut if you indeed met the mentioned problem, typing.cast might help\nfrom typing import (Type, cast)\n\nCompanyConfig = cast(Type[int], type(\"CompanyConfig\", (int,), {}))\...
[ 2 ]
[]
[]
[ "python", "types" ]
stackoverflow_0074242939_python_types.txt
Q: Is there a way to call the windows screenshot snipping tool (win+shift+s) in python? I'm wondering if there's a way to active the windows screenshot snipping tool from a python program. Currently I'm using pynput to press the windows + shift + s key but I feel that there is a better way to perform this. I've tried...
Is there a way to call the windows screenshot snipping tool (win+shift+s) in python?
I'm wondering if there's a way to active the windows screenshot snipping tool from a python program. Currently I'm using pynput to press the windows + shift + s key but I feel that there is a better way to perform this. I've tried to use subprocess to call snipping tool. subprocess.call([r'C:\\Windows\System32\Snipping...
[ "SnippingTool.exe provides some command line options to control its behavior.\nSee How to open the SnippingTool (Win Tool) passing a parameter to start automatically?\nTo start taking a screenshot (as winshifts does), pass /clip as an argument to it like this.\nsubprocess.call([r'C:\\\\Windows\\System32\\SnippingTo...
[ 1 ]
[]
[]
[ "python", "screenshot" ]
stackoverflow_0074258423_python_screenshot.txt
Q: Selenium Python Execute Script in JavaScript Console not working Good morning. I'm working on a program that uses Selenium and hooks into PokeClicker. One of the primary functions it has is to automatically download saves for me. After loading a profile and being on the main page, there is a JavaScript Class calle...
Selenium Python Execute Script in JavaScript Console not working
Good morning. I'm working on a program that uses Selenium and hooks into PokeClicker. One of the primary functions it has is to automatically download saves for me. After loading a profile and being on the main page, there is a JavaScript Class called ​Save that has a function called download() I can call this function...
[ "You have to navigate to the page where 'Start Menu' is available in the top right corner of the page, then you have to run the JS code:\n# clicking on the 'New Save' button to navigate to the next page where 'Start Menu' available\ndriver.find_element(By.XPATH, \"//*[contains(text(),'New Save')]\").click()\ntime.s...
[ 0 ]
[]
[]
[ "javascript", "python", "selenium", "selenium_firefoxdriver" ]
stackoverflow_0074258220_javascript_python_selenium_selenium_firefoxdriver.txt
Q: python sleep for second to throttle requests I have a celery periodic task which has a function call inside it i need to make the code sleep for a second for every 20 emails sent how can i achieve that. @app.task(bind=True) def send_email_reminder_on_due_date(self): send_email_from_template( su...
python sleep for second to throttle requests
I have a celery periodic task which has a function call inside it i need to make the code sleep for a second for every 20 emails sent how can i achieve that. @app.task(bind=True) def send_email_reminder_on_due_date(self): send_email_from_template( subject_template_path='emails/subject.txt', ...
[ "I would solve it like this:\n\nretrieve 20 records from database (LIMIT 20 by mysql)\nwait 1 seconds\n\nimport time\ntime.sleep(1) # Sleep for 1 second\n\n\nrepeat the first step\n\nWith this solution, it is also a given that newer emails in the database, e.g. they can be revoked or even modified.\n\nIs there any ...
[ 0 ]
[]
[]
[ "celery", "celery_task", "django", "django_celery", "python" ]
stackoverflow_0074258480_celery_celery_task_django_django_celery_python.txt
Q: Webdriver-manager ModuleNotFoundError: "Packaging" I'm on Windows 11, using Python Python 3.10.8 and pip 22.3. I'm trying to create a new selenium project using webdriver-manager for the webdriver. When I create a new project, I pip install webdriver-manager. I have tried in venvs, as well as resinstalling python ...
Webdriver-manager ModuleNotFoundError: "Packaging"
I'm on Windows 11, using Python Python 3.10.8 and pip 22.3. I'm trying to create a new selenium project using webdriver-manager for the webdriver. When I create a new project, I pip install webdriver-manager. I have tried in venvs, as well as resinstalling python but get the same result. Then I try to import webdriver-...
[ "It's a webdriver-manager bug, fixed in the master.\nInstall packages like the following.\n> pip install packaging\n\n", "pip install packaging\n\nor\npip install webdriver-manager==3.8.2\n\nnewest version of webdriver-manager is 3.8.4 which requires packaging module\n" ]
[ 10, 2 ]
[]
[]
[ "python" ]
stackoverflow_0074167502_python.txt
Q: Python 3 ImportError: No module named 'ConfigParser' I am trying to pip install the MySQL-python package, but I get an ImportError. Jans-MacBook-Pro:~ jan$ /Library/Frameworks/Python.framework/Versions/3.3/bin/pip-3.3 install MySQL-python Downloading/unpacking MySQL-python Running setup.py egg_info for package M...
Python 3 ImportError: No module named 'ConfigParser'
I am trying to pip install the MySQL-python package, but I get an ImportError. Jans-MacBook-Pro:~ jan$ /Library/Frameworks/Python.framework/Versions/3.3/bin/pip-3.3 install MySQL-python Downloading/unpacking MySQL-python Running setup.py egg_info for package MySQL-python Traceback (most recent call last): F...
[ "You can instead use the mysqlclient package as a drop-in replacement for MySQL-python. It is a fork of MySQL-python with added support for Python 3.\nI had luck with simply\npip install mysqlclient\n\nin my python3.4 virtualenv after\nsudo apt-get install python3-dev libmysqlclient-dev\n\nwhich is obviously specif...
[ 460, 454, 21, 17, 12, 8, 8, 8, 7, 7, 3, 3, 2, 2, 2, 1, 1, 1, 0 ]
[ "Kindly to see what is /usr/bin/python pointing to\nif it is pointing to python3 or higher change to python2.7\nThis should solve the issue.\nI was getting install error for all the python packages. Abe Karplus's solution & discussion gave me the hint as to what could be the problem. \nThen I recalled that I had m...
[ -1, -3 ]
[ "python", "python_3.x" ]
stackoverflow_0014087598_python_python_3.x.txt
Q: ModuleNotFoundError: No module named 'plyer.platforms.macosx' even after changing hiddenimports=['plyer.platforms.linux.notification'], I keep getting this error when trying to run the executable created Traceback (most recent call last): File "plyer/utils.py", line 93, in _ensure_obj ModuleNotFoundError: No mod...
ModuleNotFoundError: No module named 'plyer.platforms.macosx' even after changing hiddenimports=['plyer.platforms.linux.notification'],
I keep getting this error when trying to run the executable created Traceback (most recent call last): File "plyer/utils.py", line 93, in _ensure_obj ModuleNotFoundError: No module named 'plyer.platforms.macosx' Traceback (most recent call last): File "notifs.py", line 9, in <module> File "plyer/facades/notificat...
[ "based on the error message, have you tried importing the \"plyer.platforms.macosx.notification\" hidden import?\nas stated here:\nModuleNotFoundError: No module named 'plyer.platforms.macosx'\nthe error message is not asking for a linux import which is what you seem to be trying to fix but is instead asking for ma...
[ 0 ]
[]
[]
[ "desktop", "notifications", "python" ]
stackoverflow_0072333771_desktop_notifications_python.txt
Q: Discord.py - Message, which only one user can see in the server I'm making a Discord bot in Python and I want to add a feature, when message can be seen only by one user. I made an example from Dank Memer bot. Any ideas? A: These are called Ephemeral messages, however, they can only be used in response to an in...
Discord.py - Message, which only one user can see in the server
I'm making a Discord bot in Python and I want to add a feature, when message can be seen only by one user. I made an example from Dank Memer bot. Any ideas?
[ "These are called Ephemeral messages, however, they can only be used in response to an interaction. Examples of interactions are things like slash commands (like mentioned above), drop-down menus, and buttons.\nUnfortunately, the current version of discord.py does not support interactions, so you will have to use ...
[ 3, 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0069665314_bots_discord_discord.py_python.txt
Q: Pandas data frame to dictionary using dict comprehension I have a data frame of cities and info about them. I need to make a dictionary with the countries where the cities are located as keys of my dictionary and a list of the cities in that country as values of my dictionary. All of this using dictionary comprehe...
Pandas data frame to dictionary using dict comprehension
I have a data frame of cities and info about them. I need to make a dictionary with the countries where the cities are located as keys of my dictionary and a list of the cities in that country as values of my dictionary. All of this using dictionary comprehension and the columns df['country'] and df['city']. I've tried...
[ "Simple. just groupby country and aggregate cities using list then use to_dict to get the dict\ndf.groupby('country')['city'].agg(list).to_dict()\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "dictionary_comprehension", "pandas", "python" ]
stackoverflow_0074258616_dataframe_dictionary_comprehension_pandas_python.txt
Q: How to add a date column with a condition? I have a time series with daily values. I have extracted the month values in column L. I want to add a column (M) with date format. The first value of column ‘M’ is year 2000. I want the value 2000 is repeated if the month is the same, and when we go to the next month the...
How to add a date column with a condition?
I have a time series with daily values. I have extracted the month values in column L. I want to add a column (M) with date format. The first value of column ‘M’ is year 2000. I want the value 2000 is repeated if the month is the same, and when we go to the next month the value 2000 becomes 2001 and so on. This can be...
[ "A code gives you output which you want:\nfrom openpyxl import load_workbook\nimport datetime\n#initial date\nm2 = datetime.date(2000, 1, 1)\n#get the Book1 excel in python\nwb1 = load_workbook('Book1.xlsx')\n#select first sheet of the excel\nws1 = wb1.worksheets[0]\n#get max row of the excel\nMAXROW = ws1.max_row\...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074255560_python.txt
Q: making a dictionary that assigns letters to numbers then does math need a way to to take numbers from an input and assign the first number to the first character (and so on) in the input and then do math with it. For example, input: 1234 ab - cd output: -22 anyone got any ideas? I know how to create a dictionary w...
making a dictionary that assigns letters to numbers then does math
need a way to to take numbers from an input and assign the first number to the first character (and so on) in the input and then do math with it. For example, input: 1234 ab - cd output: -22 anyone got any ideas? I know how to create a dictionary with assigning the correct variables to numbers and I have kinda figured ...
[ "You either need to parse the expression yourself the same way you are parsing the mapping (looking for math operators and figuring out the expression). Sympy might have some tools for that.\nOR you are right that eval can also be used here, and that would be much simpler. If you can isolate the expression (for ins...
[ 1 ]
[]
[]
[ "dictionary", "math", "python" ]
stackoverflow_0074258555_dictionary_math_python.txt
Q: Replace outlier values with NaN in numpy? (preserve length of array) I have an array of magnetometer data with artifacts every two hours due to power cycling. I'd like to replace those indices with NaN so that the length of the array is preserved. Here's a code example, adapted from https://www.kdnuggets.com/2017...
Replace outlier values with NaN in numpy? (preserve length of array)
I have an array of magnetometer data with artifacts every two hours due to power cycling. I'd like to replace those indices with NaN so that the length of the array is preserved. Here's a code example, adapted from https://www.kdnuggets.com/2017/02/removing-outliers-standard-deviation-python.html. import numpy as np i...
[ "Use else in the list comprehension along the lines of:\n[x if x_condition else other_value for x in y]\n\n", "Got a less compact version to work. Full code:\nimport numpy as np\nimport plotly.express as px\n\n# For pulling data from CDAweb:\nfrom ai import cdas\nimport datetime\n\n# Import data:\nstart = datetim...
[ 0, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074117654_arrays_numpy_python.txt
Q: Convert csv to parquet file using python I am trying to convert a .csv file to a .parquet file. The csv file (Temp.csv) has the following format 1,Jon,Doe,Denver I am using the following python code to convert it into parquet from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql...
Convert csv to parquet file using python
I am trying to convert a .csv file to a .parquet file. The csv file (Temp.csv) has the following format 1,Jon,Doe,Denver I am using the following python code to convert it into parquet from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.types import * import os if __name__ == "__m...
[ "Using the packages pyarrow and pandas you can convert CSVs to Parquet without using a JVM in the background:\nimport pandas as pd\ndf = pd.read_csv('example.csv')\ndf.to_parquet('output.parquet')\n\nOne limitation in which you will run is that pyarrow is only available for Python 3.5+ on Windows. Either use Linux/...
[ 67, 27, 14, 12, 3, 1, 1 ]
[]
[]
[ "csv", "parquet", "python" ]
stackoverflow_0050604133_csv_parquet_python.txt
Q: How to compare two CSV's by first column and see if there are any duplicates using Python not pandas I am trying to read two CSV files and compare the first column (ID) and see if there are duplicates. If they are duplicates I have to tell the user which ID's are duplicates and only copy the unique ID's values int...
How to compare two CSV's by first column and see if there are any duplicates using Python not pandas
I am trying to read two CSV files and compare the first column (ID) and see if there are duplicates. If they are duplicates I have to tell the user which ID's are duplicates and only copy the unique ID's values into the first csv. first csv = transactions_ledgers.csv (contains column headers) and has some values stored...
[ "Thanks for writing some code. The first option works as is, although it writes IDs that are common to both files. Here's the code with that logic reversed - it only writes lines whose IDs are in transactions_q2.csv but not in transactions_q1.csv (just replace in with not in):\n#Using set\nwith open('transactions...
[ 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074242626_csv_python.txt
Q: Simple Selenium Webdriver importing doesnt work **from selenium import webdriver browser = webdriver.chrome("./chromedriver.exe") browser.get("https://www.google.com") I wrote the above code in visual studio code; however, every time I do this, this error occurs: Traceback (most recent call last): File "<stdin...
Simple Selenium Webdriver importing doesnt work
**from selenium import webdriver browser = webdriver.chrome("./chromedriver.exe") browser.get("https://www.google.com") I wrote the above code in visual studio code; however, every time I do this, this error occurs: Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'browser' is ...
[ "Start learning Selenium from any of the online tutorials.\nAlways careful on case sensitive while coding through Selenium with Python:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\n\nbrowser = webdriver.Chrome(service=Service(\"<path of the chromedriver.exe>\"))\nbrowser.g...
[ 1 ]
[]
[]
[ "python", "selenium", "webdriver" ]
stackoverflow_0074258871_python_selenium_webdriver.txt
Q: Read / Write Parquet files without reading into memory (using Python) I looked at the standard documentation that I would expect to capture my need (Apache Arrow and Pandas), and I could not seem to figure it out. I know Python best, so I would like to use Python, but it is not a strict requirement. Problem I need...
Read / Write Parquet files without reading into memory (using Python)
I looked at the standard documentation that I would expect to capture my need (Apache Arrow and Pandas), and I could not seem to figure it out. I know Python best, so I would like to use Python, but it is not a strict requirement. Problem I need to move Parquet files from one location (a URL) to another (an Azure stor...
[ "Great post, based on @Micah's answer, I put my 2 cents in it, in case you don't want to read the docs. A small snippet is the following:\nimport pandas as pd\nimport numpy as np\nfrom pyarrow.parquet import ParquetFile\n\n# create a random df then save to parquet\ndf = pd.DataFrame({\n 'A': np.arange(10000),\n ...
[ 6, 5, 1, 0 ]
[]
[]
[ "io", "parquet", "python" ]
stackoverflow_0068819790_io_parquet_python.txt
Q: How to cumsum() / cumcount() starting from an offset - the highest group id already allocated and saved? Precondition: Data from a dataframe (dfold) is already saved to CSV file. The data looks like so: import pandas as pd columns = ['timestamp','base'] data = [['2022-10-14 11:47:38',100], ['...
How to cumsum() / cumcount() starting from an offset - the highest group id already allocated and saved?
Precondition: Data from a dataframe (dfold) is already saved to CSV file. The data looks like so: import pandas as pd columns = ['timestamp','base'] data = [['2022-10-14 11:47:38',100], ['2022-10-14 11:47:39',100], ['2022-10-14 11:47:40',100], ['2022-10-14 11:47:41...
[ "I think you're overcomplicating it. If you have access to dfold at each iteration, why not just add the previous max group id?\ncolumns = [\"timestamp\", \"base\"]\ndata = [\n [\"2022-10-14 11:47:38\", 100],\n [\"2022-10-14 11:47:39\", 100],\n [\"2022-10-14 11:47:40\", 100],\n [\"2022-10-14 11:47:41\",...
[ 1, 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074243194_group_by_pandas_python.txt
Q: {% for top in topwear.brand %} is not executing I want to list the items by brand so user can choose according to the brand of the product in the sidebar but somehow it is not happenning views.py class home(View): def get (self,request): products=Product.objects.all() topwear=P...
{% for top in topwear.brand %} is not executing
I want to list the items by brand so user can choose according to the brand of the product in the sidebar but somehow it is not happenning views.py class home(View): def get (self,request): products=Product.objects.all() topwear=Product.objects.filter(Category='TW') bott...
[ "Instead of this:\n{% for top in topwear.brand %}\n <a href=\"{% url 'searchproduct' top %}\" class=\"dropdown-item\">Top Wear</a>\n{% endfor %}\n\ntry this:\n{% for top in topwear %}\n <a href=\"{% url 'searchproduct' top.brand %}\" class=\"dropdown-item\">Top Wear</a>\n{% endfor %}\n\n" ]
[ 1 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074258943_django_html_python.txt
Q: I am getting None type error for my code. This is from Pattern of strings in Geek for geeks The code should print in the decreasing order Example: input a = "Geek" Output Geek Gee Ge G END This is actually from geek for geeks I am trying to solve it using different variations #User function Template for python3 cl...
I am getting None type error for my code. This is from Pattern of strings in Geek for geeks
The code should print in the decreasing order Example: input a = "Geek" Output Geek Gee Ge G END This is actually from geek for geeks I am trying to solve it using different variations #User function Template for python3 class Solution: def pattern(self, S): n = len(S) for i in range (0, n): ...
[ "Using two loops is usually not the most efficient I would recommend slicing.\nLike this:\nclass Solution:\n def pattern(self,a):\n return [a[i:] for i in range(len(a))]\n\n\n# {\n# Driver Code Starts\n# Initial Template for Python 3\n\nif __name__ == '__main__':\n a = input()\n ob = Solution()\n ...
[ 0 ]
[ "You are printing the results once by calling answer = ob.Pattern(S) but then you loop through answer right after which at this point is None.\n" ]
[ -1 ]
[ "loops", "python", "string" ]
stackoverflow_0074258900_loops_python_string.txt
Q: Why do I keep getting GetOverlappedResult got err 109 So I got a piece of code like this: mgr = MP.Manager() mp_dataset = mgr.dict(dataset) mp_seen = mgr.dict({k: None for k in seen}) mp_barrier = MP.Barrier(WORKER_COUNT + 1) # +1 to include main process # TileQueue is a global var worker...
Why do I keep getting GetOverlappedResult got err 109
So I got a piece of code like this: mgr = MP.Manager() mp_dataset = mgr.dict(dataset) mp_seen = mgr.dict({k: None for k in seen}) mp_barrier = MP.Barrier(WORKER_COUNT + 1) # +1 to include main process # TileQueue is a global var workers = [ MP.Process(target=process_item_worker, args=(...
[ "Okay so after doing LOTS of experimentation, I found out the (possible) reason:\n\nI must also 'end' the Manager() instance\n\nSo I changed the finally block to be like this:\n finally:\n # Save the results first, convert from managed to normal dicts\n dataset.update(mp_dataset)\n progress[...
[ 0 ]
[]
[]
[ "python", "python_multiprocessing" ]
stackoverflow_0074258919_python_python_multiprocessing.txt
Q: How to find the difference of time series data points from the mean and create another column I have time series data, I want to append a column that gives the difference between the value(x_i) and the mean(x_avg). df time col1 newcolumn 1 30 0 2 20 -10 3 50 20 4 ...
How to find the difference of time series data points from the mean and create another column
I have time series data, I want to append a column that gives the difference between the value(x_i) and the mean(x_avg). df time col1 newcolumn 1 30 0 2 20 -10 3 50 20 4 20 -10 where mean of col1 = (30+20+50+20)/4 = 30. thanks.
[ "You can use apply function. But you need to store the average of that column separately.\ndef diff(row):\n global mean\n return row.col1 - mean\n\ndict = {'col1':[30,20,50,20]}\ndf = pd.DataFrame(dict)\n\nmean = df.col1.mean()\ndf['diff'] = df.apply(diff, axis=1)\n\nprint(df)\n\n col1 diff\n0 30 0.0\...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074258498_dataframe_pandas_python.txt
Q: How to turn a cifar10 dataset into a tensor I am trying to turn the cifar10 dataset into a tensor with trainset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transforms.ToTensor()) but it continually returns false when I run it torch.is_tensor(trainset) function which means it's not a tens...
How to turn a cifar10 dataset into a tensor
I am trying to turn the cifar10 dataset into a tensor with trainset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transforms.ToTensor()) but it continually returns false when I run it torch.is_tensor(trainset) function which means it's not a tensor and it also doesn't work for functions that re...
[ "trainset is a Dataset instance and you do not convert it to a tensor. You should load the data and then transform it.\nfor i, data in enumerate(trainset, 0):\n do whatever\n\n" ]
[ 1 ]
[]
[]
[ "conv_neural_network", "deep_learning", "python", "pytorch", "tensor" ]
stackoverflow_0074258668_conv_neural_network_deep_learning_python_pytorch_tensor.txt
Q: What's wrong with this BS4 to CSV code? Not getting list of items in csv correctly import csv from email import header from fileinput import filename from tokenize import Name import requests from bs4 import BeautifulSoup url = "https://www.azlyrics.com/l/linkinpark.html" r=requests.get(url) htmlContent = r.cont...
What's wrong with this BS4 to CSV code? Not getting list of items in csv correctly
import csv from email import header from fileinput import filename from tokenize import Name import requests from bs4 import BeautifulSoup url = "https://www.azlyrics.com/l/linkinpark.html" r=requests.get(url) htmlContent = r.content soup = BeautifulSoup(htmlContent,"html.parser") albumList=[] table = soup.find('div...
[ "albumList contains all the information you need, so the issue is just with the part where you write the csv at the end.\nYou have:\nfor i in albumList:\n thewriter.writerow(albumName)\n\nbut albumName is not referring to the elements of albumList - it's the temporary variable you used when creating that list. ...
[ 1 ]
[]
[]
[ "beautifulsoup", "csv", "python", "web_scraping" ]
stackoverflow_0074259032_beautifulsoup_csv_python_web_scraping.txt
Q: Create a column based of a status in another column can you help me please? I have the following table in my dataframe: DATE CUSTOMER STATUS 01/01/2022 A ACTIVATED 02/01/2022 A ACTIVE 03/01/2022 A INACTIVE 04/01/2022 A EXCEPTION 05/01/2022 A INACTIVATED I want to mark my dataframe row when my client inactiv...
Create a column based of a status in another column
can you help me please? I have the following table in my dataframe: DATE CUSTOMER STATUS 01/01/2022 A ACTIVATED 02/01/2022 A ACTIVE 03/01/2022 A INACTIVE 04/01/2022 A EXCEPTION 05/01/2022 A INACTIVATED I want to mark my dataframe row when my client inactivated (status inactivated). However, I only w...
[ "You can compare STATUS per groups and test for values s - 1 if exist both, 0 if no:\ns = {'ACTIVATED','INACTIVATED'}\ndf['ACTIVATED/INACTIVATED'] = (df.groupby('CUSTOMER')['STATUS']\n .transform(lambda x: set(x) >= s)\n .astype(int))\nprint (df)\n ...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python", "python_3.x", "status" ]
stackoverflow_0074259116_numpy_pandas_python_python_3.x_status.txt
Q: How to retrieve the position of a list in a list of lists in python A = [['0', '6', '4', '3'], ['0', '2', '8', '3'], ['0', '4', '1', '5'], ['0', '3', '2', '5']] B = ['0', '4', '1', '5'] Say I want to find out at which line does B equal to the list. How do I write a solution for this? The answer would be the third...
How to retrieve the position of a list in a list of lists in python
A = [['0', '6', '4', '3'], ['0', '2', '8', '3'], ['0', '4', '1', '5'], ['0', '3', '2', '5']] B = ['0', '4', '1', '5'] Say I want to find out at which line does B equal to the list. How do I write a solution for this? The answer would be the third line. I tried doing a for loop.
[ "You can try list.index(element) to get the index of the element in the original list (A). In your terminology, to get the line just add one to the index.\nline = A.index(B) + 1\n\n", "you dont need use loops.you can get the element index by indexing.\nA = [['0', '6', '4', '3'], ['0', '2', '8', '3'], ['0', '4', '...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074259215_python.txt
Q: Get array of string from url query param with Python Azure Function App HTTP I have an Azure Python Func app with the URL below: www.domain.com/api/url?users=[a,b,c] I want to get the users as an array from the URL above in Python import logging import azure.functions as func def main(req: func.HttpRequest) -> f...
Get array of string from url query param with Python Azure Function App HTTP
I have an Azure Python Func app with the URL below: www.domain.com/api/url?users=[a,b,c] I want to get the users as an array from the URL above in Python import logging import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: get the users as an array from the URL No answer from the l...
[ "\nI want to get the users as an array from the URL above in Python\n\nAFAIK, we can't get the query parameter as array by default it will be a string. It has either string or dictionary.\n\nYou can use urllib module to get the query parameter. Here I have used to urllib to get the params which follows.\nimport lo...
[ 0 ]
[]
[]
[ "azure", "azure_functions", "python" ]
stackoverflow_0074234647_azure_azure_functions_python.txt
Q: How to collect a data from a csv file using a specific Id? I want to iterate through all the fields in the csv file when I call for the data using the specific user ID for name, values in df.iteritems(): print('{name}:{value}'.format(name=name, value=values[1])) When I run this code its iterating through the...
How to collect a data from a csv file using a specific Id?
I want to iterate through all the fields in the csv file when I call for the data using the specific user ID for name, values in df.iteritems(): print('{name}:{value}'.format(name=name, value=values[1])) When I run this code its iterating through the first field then moving to the next. I want it to iterate throu...
[ "You are looking for iterrows method.\nIf name and value are column names:\nfor _, row in df.iterrows():\n print('{name}:{value}'.format(name=row[0], value=row[1]))\n\nIf name is an index and value is a column name:\nfor index, row in df.iterrows():\n print('{name}:{value}'.format(name=index, value=row[0]))...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074259189_python.txt
Q: save result rsponse from another application code to your application I have code in Django application for generating and download excel files, but now I created another application in the same project. Now I want to save that result excel file in the project directory itself. Here I am trying with the below co...
save result rsponse from another application code to your application
I have code in Django application for generating and download excel files, but now I created another application in the same project. Now I want to save that result excel file in the project directory itself. Here I am trying with the below code but I am not able to get any response. from xlwt import workbook def i...
[ "Try the following fix to solve cors error\nCORS_ALLOW_ALL_ORIGINS = True\n\nCORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ]\n\nCORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ]\n\nCOR...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0060107725_django_django_rest_framework_python.txt
Q: How to sort pandas DataFrame by two columns collectively, rather than one then the other? Say I have a dataframe, df, as below: Client Number (#) Volume ($) Num. z-Score Vol. z-Score 0 ABC 63 131.22 1.17 0.68 1 DEF 44 98.71 2.68 ...
How to sort pandas DataFrame by two columns collectively, rather than one then the other?
Say I have a dataframe, df, as below: Client Number (#) Volume ($) Num. z-Score Vol. z-Score 0 ABC 63 131.22 1.17 0.68 1 DEF 44 98.71 2.68 1.35 2 JKL 17 64.15 0.45 0.57 3 PQR 75...
[ "Looks like you're trying to find the max value between 'Num. z-Score' and 'Vol. z-Score'.\ndf['max_value'] = df[['Num. z-Score','Vol. z-Score']].max(axis=1)\ndf.sort_values(['max_value'], ascending=False)\n\n", "Use DataFrame.sort_index with maximum of both columns:\ndf = df.sort_index(key=df[['Vol. z-Score','Nu...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074259120_pandas_python.txt
Q: Pandas: Calculating the time duration for each person could anyone can teach me how to calculate the time duration for each person? I'm not good at describing the question because my English sucks but as the picture shows below, I want to select the latest date for the person and then subtract the oldest date to g...
Pandas: Calculating the time duration for each person
could anyone can teach me how to calculate the time duration for each person? I'm not good at describing the question because my English sucks but as the picture shows below, I want to select the latest date for the person and then subtract the oldest date to get the time duration. Thanks I wanna get the duration time....
[ "If need subtract maximal dates per customers use GroupBy.transform with Series.sub, last if necessary convert timedeltas to days by Series.dt.days:\ndf['date'] = pd.to_datetime(df['date'])\ndf['dur'] = df.groupby('customer')['date'].transform('max').sub(df['date']).dt.days\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "group_by", "pandas", "python", "survival_analysis" ]
stackoverflow_0074259026_datetime_group_by_pandas_python_survival_analysis.txt
Q: Double numbers in Python using Lambda I am trying to double numbers using Lambda function in python but can't understand the function that's all because I'm starting to learn python. Below is the function: def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) I just need to underst...
Double numbers in Python using Lambda
I am trying to double numbers using Lambda function in python but can't understand the function that's all because I'm starting to learn python. Below is the function: def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) I just need to understand how this code is working. Any help will...
[ "def myfunc(n): # this function is taking input n and returning a function object\n return lambda a : a * n # this function is taking input as a and we are returning this function object\n\n\nmydoubler = myfunc(2) # now we are calling the returned function object if you print(mydoubler)-> this will give you functi...
[ 0, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0074259216_lambda_python.txt
Q: Can I extend Django model fields without creating mixed types? I have subclassed built-in model Fields to reduce repetition in similar columns. This triggers exceptions in tests against Django 3.2 (but interestingly does work in the otherwise now irrelevant, unsupported, version 2.2) django.core.exceptions.FieldE...
Can I extend Django model fields without creating mixed types?
I have subclassed built-in model Fields to reduce repetition in similar columns. This triggers exceptions in tests against Django 3.2 (but interestingly does work in the otherwise now irrelevant, unsupported, version 2.2) django.core.exceptions.FieldError: Expression contains mixed types: DecimalField, DecimalFWB. You...
[ "Automatically selecting the shared field as the output has been fixed as of Bug #33397, released in Django 4.1 (but not backported). The change does however comes with a warning (emphasis mine):\n\nAs a guess, if the output fields of all source fields match then\nsimply infer the same type here.\nThis guess is mos...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0072512941_django_django_models_python.txt
Q: How to auto adjust the column width of a excel sheet using pandas I am trying to auto-adjust the column cells to the excel data i used this code which i found in stack overflow df=pd.read_excel(r"location of the file") writer = pd.ExcelWriter(r'C:\Users\Aparna\Downloads\columnwidth1.xlsx') df.to_excel(writer, she...
How to auto adjust the column width of a excel sheet using pandas
I am trying to auto-adjust the column cells to the excel data i used this code which i found in stack overflow df=pd.read_excel(r"location of the file") writer = pd.ExcelWriter(r'C:\Users\Aparna\Downloads\columnwidth1.xlsx') df.to_excel(writer, sheet_name='my_analysis', index=False, na_rep='NaN') # Auto-adjust column...
[ "This will format column width.\ndf = pd.read_excel(r\"location of the file\")\n\nwith pd.ExcelWriter(r\"C:\\Users\\Aparna\\Downloads\\columnwidth1.xlsx\", engine=\"xlsxwriter\") as writer:\n df.to_excel(writer, startrow=0, sheet_name=\"my_analysis\", index=False)\n\n for col in pd.Series(range(len(df.columns...
[ 1 ]
[]
[]
[ "data_science", "pandas", "python", "xlsxwriter" ]
stackoverflow_0074259141_data_science_pandas_python_xlsxwriter.txt
Q: Merge pyspark data frame rows with one column value different I want to merge two dataframe rows with one column value different. For example, DataframeA: firstName lastName age Alex Smith 19 Rick Mart 18 DataframeB: firstName lastName age Alex Smith 21 Result when I use merge Datafram...
Merge pyspark data frame rows with one column value different
I want to merge two dataframe rows with one column value different. For example, DataframeA: firstName lastName age Alex Smith 19 Rick Mart 18 DataframeB: firstName lastName age Alex Smith 21 Result when I use merge DataframeA with DataframeB using union: firstName lastName age Alex S...
[ "After union you can easily aggregate the resultant set get the max of age\nData Preparation\ns1 = StringIO(\"\"\"\nfirstName,lastName,age\nAlex,Smith,19\nRick,Mart,18\n\"\"\")\n\n\ndf1 = pd.read_csv(s1,delimiter=',')\n\nsparkDF1 = sql.createDataFrame(df1)\n\n\ns2 = StringIO(\"\"\"\nfirstName,lastName,age\nAlex,Smi...
[ 1, 1 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "pyspark", "python" ]
stackoverflow_0074255647_apache_spark_apache_spark_sql_pyspark_python.txt
Q: Chrome Webdriver Refresh does not respond since Chrome 106 Since I have upgraded to Chrome 106 (and now to 107) the driver manages to open the URL at the first time but after some timeout (?) or other criteria, the driver.refresh() does not return (i.e. no resposne). The way it looks to me, if the Refresh occurs w...
Chrome Webdriver Refresh does not respond since Chrome 106
Since I have upgraded to Chrome 106 (and now to 107) the driver manages to open the URL at the first time but after some timeout (?) or other criteria, the driver.refresh() does not return (i.e. no resposne). The way it looks to me, if the Refresh occurs within seconds since the initial open, then the refresh succeeds....
[ "Can you do it on google colab? try this\nimport sys sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')\nfrom selenium import webdriver \nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument('--headless') \nchrome_options.add_argument('--no-sandbox')\nchrome_options.add_argument('--disab...
[ 0 ]
[ "if your work does not depend much on it, just use earlier versions where it used to work.\nif not, try the following:\ndriver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'r')\n" ]
[ -1 ]
[ "google_chrome", "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074247710_google_chrome_python_selenium_selenium_chromedriver.txt
Q: How to find permutations of the options selected in a form So we have a form that has 4 areas City = Boston, Dallas, Detroit, Chicago, Pittsburgh Age Range = Young, Medium, Old Gender = Male, Female Nationality = Italian, Irish, Spanish, Saudi When a user comes to our page - they can choose any number of cities,...
How to find permutations of the options selected in a form
So we have a form that has 4 areas City = Boston, Dallas, Detroit, Chicago, Pittsburgh Age Range = Young, Medium, Old Gender = Male, Female Nationality = Italian, Irish, Spanish, Saudi When a user comes to our page - they can choose any number of cities, Example: user selects Boston, Pittsburgh, Dallas for cities us...
[ "I presume this is what you want:\nFirstly, we do combinations on each array(cities, gender, age, nationality) with different length. For instance, for gender, the combination tmp will be [('male',), ('female',), ('male', 'female')]. Then we perform product on those combinations. Thus, the final length will be:\nfi...
[ 1 ]
[]
[]
[ "list", "python", "python_3.x", "python_itertools" ]
stackoverflow_0074259269_list_python_python_3.x_python_itertools.txt
Q: trying to iterate my dataframe under condition I'm trying to manipulate date in a column by using for loop my dataframe looks like this(under condition, the origianl dataframe has (104959 rows × 49 columns): WARNSIGN_TP WARNSPEAK4DTL WARNBEHAV4DTL WARNEMOTION4DTL WARNSIGN_DTL 0 1 ...
trying to iterate my dataframe under condition
I'm trying to manipulate date in a column by using for loop my dataframe looks like this(under condition, the origianl dataframe has (104959 rows × 49 columns): WARNSIGN_TP WARNSPEAK4DTL WARNBEHAV4DTL WARNEMOTION4DTL WARNSIGN_DTL 0 1 enthutiastic running energetic ...
[ "Just change\n df['WARNSIGN_DTL'].isnull\n\nto\n df['WARNSIGN_DTL'].isnull()\n\n(add parentheses)\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074259333_python.txt
Q: In vs studio python Print ("Welcome") it does not run when I type the file name I used a simple code for python in my VS Studio. Print ("Welcome") when I run it through the run button it works fine but when I want to run it through typing the file name ( eg .\02_hello.py) and press enter it doesn't run and inste...
In vs studio python Print ("Welcome") it does not run when I type the file name
I used a simple code for python in my VS Studio. Print ("Welcome") when I run it through the run button it works fine but when I want to run it through typing the file name ( eg .\02_hello.py) and press enter it doesn't run and instead leave a blank line. I don't know what's wrong.please help I want the python code t...
[ "You need to specific the python interpreter to run your code\ntry:\npython ./02_hello.py\n\n", "Because you aren't telling the terminal what that python file should do. In default it opens the file in vscode. Try this:\npython 02_welcome.py\n\n", "check if you have a file of that name on path.\nalso type :\npy...
[ 1, 1, 0 ]
[]
[]
[ "python", "terminal", "visual_studio", "xcode" ]
stackoverflow_0074259367_python_terminal_visual_studio_xcode.txt
Q: Use python class to calculate euclidean distance between two points i am doing a question in class python. in the test results, there is a difference between my results with the answer, in the last test, The nearest point to Point(-30, 9) is Point(-19, 19), but my code prints Point(-20,20) i do not know where's w...
Use python class to calculate euclidean distance between two points
i am doing a question in class python. in the test results, there is a difference between my results with the answer, in the last test, The nearest point to Point(-30, 9) is Point(-19, 19), but my code prints Point(-20,20) i do not know where's wrong? please help me. thanks here is my codes here is my code. import m...
[ "Issue is in routine closest_point\n\nUsing the dictionary you're setting last point pair which has that distance (the issue is multiple pairs have the same distance)\nin below code the first pair which has the distance is used (answer agrees with the linked solution)\nincorrect looping over new_dict to find close...
[ 1 ]
[]
[]
[ "class", "python", "python_3.x" ]
stackoverflow_0074259264_class_python_python_3.x.txt
Q: Run further steps against a string only if re.sub() matches I have a series of strings. Some of them match a particular regular expression. If (and only if) they do, I want to do a substitution based on that regular expression and then some further processing as well. That can naively be written as: for string in ...
Run further steps against a string only if re.sub() matches
I have a series of strings. Some of them match a particular regular expression. If (and only if) they do, I want to do a substitution based on that regular expression and then some further processing as well. That can naively be written as: for string in stringlist: if re.search(r'^A \d+ (?:1 \d+ )?B \d+ C\d+ ', stri...
[ "I would do something like this:\nimport re\nmy_pattern = r'^(A \\d+ (?:1 \\d+ )B \\d+ C\\d+) (.*)$'\ncompiled = re.compile(my_pattern). # This is a re.Pattern object\n\ndef replace_function(match_obj):\n a = match_obj.group(1)\n b = match_obj.group(2)\n if a is not None and b is not None:\n return...
[ 1 ]
[]
[]
[ "performance", "python", "regex" ]
stackoverflow_0074258313_performance_python_regex.txt
Q: In Python, how will we convert this type of string into datetime format in pandas dataframe? I have done: 1. from datetime import datetime date_string = df['Date'] format = '%m/%d/%Y %I:%M %p' for i in date_string: my_date = datetime.strptime(i, format) print (my_date.strftime(format)) df['Date']=pd.to_datet...
In Python, how will we convert this type of string into datetime format in pandas dataframe?
I have done: 1. from datetime import datetime date_string = df['Date'] format = '%m/%d/%Y %I:%M %p' for i in date_string: my_date = datetime.strptime(i, format) print (my_date.strftime(format)) df['Date']=pd.to_datetime(df['Date'],format='%m/%d/%Y, %I:%M %p')
[ "Use %y for years in format YY, %Y is for format YYYY:\ndf['Date']=pd.to_datetime(df['Date'],format='%m/%d/%y, %I:%M %p')\nprint (df)\n Date\n0 2018-02-26 12:31:00\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "format", "logic", "pandas", "python" ]
stackoverflow_0074259482_datetime_format_logic_pandas_python.txt
Q: How to dynamically define project root path in config file? I want to define project root path in Hydra config file without hardcoding it. 'til now couldn't find any feature of Hydra that can imply the path! E.g., suppose we have the following project structure: project-name ├── conf │ ├── config.yaml │ ├── co...
How to dynamically define project root path in config file?
I want to define project root path in Hydra config file without hardcoding it. 'til now couldn't find any feature of Hydra that can imply the path! E.g., suppose we have the following project structure: project-name ├── conf │ ├── config.yaml │ ├── config.py ├── src │ ├── model.py Now I want to define the proj...
[ "This is not supported by Hydra. The concept of a root directory is not defined well enough.\nYou can use OmegaConf custom resolvers to implement your on logic on a specific node but it's not clear to me how you can achieve what you are trying to do in a clean and reusable way.\n" ]
[ 1 ]
[]
[]
[ "fb_hydra", "python", "python_3.x" ]
stackoverflow_0074256508_fb_hydra_python_python_3.x.txt
Q: Wagtail Tinymce - ModuleNotFoundError: No module named 'wagtail.wagtailadmin' I'm trying to install the package "wagtailtinymce" already downloaded it, however, the repository tutorial is completely bad. I do not know if it's because of some update or something. I'm using the latest version of wagtail and I alread...
Wagtail Tinymce - ModuleNotFoundError: No module named 'wagtail.wagtailadmin'
I'm trying to install the package "wagtailtinymce" already downloaded it, however, the repository tutorial is completely bad. I do not know if it's because of some update or something. I'm using the latest version of wagtail and I already have a project created (obvious). The error is in every import the package tries ...
[ "Looking at the documentation, https://github.com/isotoma/wagtailtinymce#wagtail-tinymce , this module is compatible with Wagtail 1.5 and currently we are in the 2.3 version.\n", "As mentioned, the pip package for wagtailtinymce is not up to date for latest versions of wagtail.\nHowever, the github repo of the pa...
[ 1, 1 ]
[]
[]
[ "django", "python", "tinymce", "wagtail" ]
stackoverflow_0052996511_django_python_tinymce_wagtail.txt
Q: Scraping data with BeautifulSoup I'm trying to scrape data from this website 1xbet but I'm getting this error <Response [404]> all the time. Here is my code. type here import requests, bs4 requests.packages.urllib3.disable_warnings() headers = {"User-Agent":"Mozilla/5.0"} url = "https://1xbet.com/sports/basketba...
Scraping data with BeautifulSoup
I'm trying to scrape data from this website 1xbet but I'm getting this error <Response [404]> all the time. Here is my code. type here import requests, bs4 requests.packages.urllib3.disable_warnings() headers = {"User-Agent":"Mozilla/5.0"} url = "https://1xbet.com/sports/basketball/early" response = requests.get(url,h...
[ "404 mean this url source not found,you need check the url is right\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074259495_beautifulsoup_python_web_scraping.txt
Q: Adding a favicon to a Flask server without HTML My flask server constantly reports xx.xxx.xxx.xxx - - [DD/MM/YYYY HH:MM:SS] "GET /favicon.ico HTTP/1.1" 404 - In the code for my flask server I've added, @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'),'...
Adding a favicon to a Flask server without HTML
My flask server constantly reports xx.xxx.xxx.xxx - - [DD/MM/YYYY HH:MM:SS] "GET /favicon.ico HTTP/1.1" 404 - In the code for my flask server I've added, @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon') a...
[ "Put the icon in your static directory as favicon.ico. and below code in python file\nimport os\nfrom flask import send_from_directory\n\n@app.route('/favicon.ico')\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, 'static'),\n 'favicon.ico',mimetype='image/vnd.mic...
[ 43, 0 ]
[]
[]
[ "favicon", "flask", "python" ]
stackoverflow_0040696745_favicon_flask_python.txt
Q: Different between List.clear and List = [] in Python What is the difference array.clear() and array = [] in the following two implementations. 1)print output is [1,2,3,4,5] class fistclass_(): def __init__(self): self.array = None def setarray(self): array = [1,2,3,4,5] self.array = a...
Different between List.clear and List = [] in Python
What is the difference array.clear() and array = [] in the following two implementations. 1)print output is [1,2,3,4,5] class fistclass_(): def __init__(self): self.array = None def setarray(self): array = [1,2,3,4,5] self.array = array array = [] return class another...
[ "If you have more than one reference to a list, then .clear() clears the list and preserves the references, but the assignment creates a new list and does not affect the original list.\na = [1,2,3]\nb = a # make an additional reference\nb.clear()\nprint(a, b)\n# [] []\na = [1,2,3]\nb = a # make an additional refere...
[ 5, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074259485_list_python.txt
Q: Python - How to continue last student number count? I have this menu-driven python program that lets the user create, add, and view a student record. The program stores the information in an array. MENU = """\n ---------------- MENU ---------------- \n Enter [1] to Create [2] to View """ def ma...
Python - How to continue last student number count?
I have this menu-driven python program that lets the user create, add, and view a student record. The program stores the information in an array. MENU = """\n ---------------- MENU ---------------- \n Enter [1] to Create [2] to View """ def main(): while True: print(MENU) comman...
[ "def create():\n print(\"\\n \\t ------- CREATE STUDENT INFORMATION ------- \\n\")\n\n recordSize = int (input(\"\\n Enter Number of Students: \"))\n\n studentNumber = len(studentRecord)\n\n for size in range(recordSize):\n studentNumber = studentNumber + size\n print(\"\\n ---------------...
[ 1 ]
[]
[]
[ "error_handling", "list", "multidimensional_array", "python" ]
stackoverflow_0074259292_error_handling_list_multidimensional_array_python.txt
Q: Python C/API How can I generate a module object from a code object compiled by Py_CompileString without using PyImport_ExecCodeModule? I could have used PyImport_ExecCodeModule directly to generate a module object. However, what I want is to get it when it is not executed. Execution is the key, I don't accept it. ...
Python C/API How can I generate a module object from a code object compiled by Py_CompileString without using PyImport_ExecCodeModule?
I could have used PyImport_ExecCodeModule directly to generate a module object. However, what I want is to get it when it is not executed. Execution is the key, I don't accept it. In fact, my ultimate goal is to embed some C++ functions in a python module using pybind11 before executing the module. Like this: C/C++ con...
[ "Use PyImport_AddModule to create a module instance inadvance?\npybind11::module module = py::reinterpret_steal<pybind11::module>(PyImport_AddModule(\"1\"));\nmodule.def(\"func1\", [](){});\nmodule.def(\"func2\", [](){});\n\nconst char *myCode = \"print('hello world')\";\n// const char *myCode = \"func1()\";\nPyObj...
[ 0 ]
[]
[]
[ "c++", "pybind11", "python" ]
stackoverflow_0074259137_c++_pybind11_python.txt
Q: Time value does not match the format. ValueError in python I am trying to convert a string to datetime object using the strptime function. I am encountering a ValueError that says format doesn't match, so I did double checking and confirmed that the format in the string matches the format I am passing as the para...
Time value does not match the format. ValueError in python
I am trying to convert a string to datetime object using the strptime function. I am encountering a ValueError that says format doesn't match, so I did double checking and confirmed that the format in the string matches the format I am passing as the parameter for strptime. I have also referenced this question: time d...
[ "You're almost there. You need %Y instead of %y since you're providing the year with the century (2022 instead of 22).\nYour code would be\nfrom datetime import datetime\n\nstg = \"2022-10-31-01:17:46\"\n\ndo = datetime.strptime(stg, '%Y-%m-%d-%H:%M:%S')\n\n" ]
[ 1 ]
[]
[]
[ "datetime", "parsing", "python", "string", "valueerror" ]
stackoverflow_0074259548_datetime_parsing_python_string_valueerror.txt
Q: [Airflow]: Running Python script with BashOperator I am new to Airflow and I am trying to apply DAG to run an ETL python script through BashOperator. Such ETL python scripts update pandas dataframe as new data emerges, and the output is an updated .csv file. In the Airflow webserver UI, the tasks are successfully ...
[Airflow]: Running Python script with BashOperator
I am new to Airflow and I am trying to apply DAG to run an ETL python script through BashOperator. Such ETL python scripts update pandas dataframe as new data emerges, and the output is an updated .csv file. In the Airflow webserver UI, the tasks are successfully completed, however the .csv files are not being generate...
[ "I'm assuming you've used the production docker image to setup your Airflow environment. Docker doesn't have access to the absolute path you've specified. In fact, it creates a /tmp location while invoking the BashOperator (see the logs).\nYou have to specify your scripts location on your docker-file and make it av...
[ 0 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0073879955_airflow_python.txt
Q: How can i use a single C function through SWIG? i have a SWIG C-python interface. I want to make individual functions from test.c available in my python interface. I feel like i am wasting hrs on the documentation without finding the simple way to do it. The only options i know are to either: %module test %{ #inc...
How can i use a single C function through SWIG?
i have a SWIG C-python interface. I want to make individual functions from test.c available in my python interface. I feel like i am wasting hrs on the documentation without finding the simple way to do it. The only options i know are to either: %module test %{ #include "test.h" //#include "test.c" %} %include "stdin...
[ "%module test\n\n%{\n// Whatever goes here is directly copied to the generated wrapper code.\n// Put what you need here for the wrapper to build, typically just\n// your public headers.\n#include \"test.h\"\n%}\n\n// Anything you declare or %import is processed to make the SWIG interface.\n// You can %import \"test...
[ 0 ]
[]
[]
[ "c", "python", "swig", "swig_typemap" ]
stackoverflow_0074258879_c_python_swig_swig_typemap.txt
Q: Web scrapping for png images I am working on scrapping company logos from there web site. I have 12 million company records of their domain names. I am trying to scrape from web site if the web site is forbidden then I am trying to scrape from wikipedia page of theirs. This is my code which I have worked seperatel...
Web scrapping for png images
I am working on scrapping company logos from there web site. I have 12 million company records of their domain names. I am trying to scrape from web site if the web site is forbidden then I am trying to scrape from wikipedia page of theirs. This is my code which I have worked seperately for domain names and wikipedia p...
[ "You can try something as follows:\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n \nhtmldata = urlopen('https://en.wikipedia.org/wiki/Pepsi')\nsoup = BeautifulSoup(htmldata, 'html.parser')\nimages = soup.find_all('img')\n \nfor item in images:\n img = 'https:' +item['src']\n #print(img...
[ 1 ]
[]
[]
[ "beautifulsoup", "image", "logos", "python", "web_scraping" ]
stackoverflow_0074258710_beautifulsoup_image_logos_python_web_scraping.txt
Q: How to update value in row using multiple queries python flask-sqlalchemy I am trying to update the value in the column 'score' at the row where student entry column = rowId.id. It is giving the error, List object has no attribute 'id'. below is my table structure, and the code I am trying to execute. class studen...
How to update value in row using multiple queries python flask-sqlalchemy
I am trying to update the value in the column 'score' at the row where student entry column = rowId.id. It is giving the error, List object has no attribute 'id'. below is my table structure, and the code I am trying to execute. class studentTimetable(UserMixin, db.Model): __tablename__ = 'studentTimetable' id ...
[ "SOLUTION\nboth __repr__ functions in the tables were removed, rowId was changed to a .first() as only one record should be present, and db.session.merge(checkpointUpdate) was added above the db.session.commit()\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074259388_python_sqlalchemy.txt
Q: Python: read outlook mail I have a script that uses the library "imbox" to get all the emails and their attachment, but since microsoft has disabled basic authentication obviously it does not work. For what I understood I first need an access token using the "msal" library and then probably use "imaplib" that supp...
Python: read outlook mail
I have a script that uses the library "imbox" to get all the emails and their attachment, but since microsoft has disabled basic authentication obviously it does not work. For what I understood I first need an access token using the "msal" library and then probably use "imaplib" that supports "XOAUTH2". Does anyone hav...
[ "result = app.acquire_token_by_username_password(username=username, password=password, scopes['https://graph.microsoft.com/IMAP.AccessAsUser.All'])\n\nMicrosoft does not advise customers to use it as it's less secure than the other flows. For more information about why you want to avoid using this grant, you can, f...
[ 0 ]
[]
[]
[ "authentication", "microsoft_graph_api", "microsoft_graph_mail", "office365", "python" ]
stackoverflow_0074252353_authentication_microsoft_graph_api_microsoft_graph_mail_office365_python.txt
Q: Delete second row of pandas dataframe I am trying to delete the second row of pandas dataframe but I was unable to do so. Code used: df1.drop([1,],axis=0, inplace=True) Note: The second row is empty that's why I want it gone. A: This one works for me df1.drop(1, inplace=True)
Delete second row of pandas dataframe
I am trying to delete the second row of pandas dataframe but I was unable to do so. Code used: df1.drop([1,],axis=0, inplace=True) Note: The second row is empty that's why I want it gone.
[ "This one works for me\ndf1.drop(1, inplace=True)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074257887_dataframe_pandas_python.txt
Q: No module named 'basic_units' I'm trying to run the code below, but I keep getting the same error : "ModuleNotFoundError: No module named 'basic_units'". import sympy as sym import math import numpy as np import os import matplotlib.pyplot as plt from basic_units import radians fig, ax = plt.subplots(subplot_kw={...
No module named 'basic_units'
I'm trying to run the code below, but I keep getting the same error : "ModuleNotFoundError: No module named 'basic_units'". import sympy as sym import math import numpy as np import os import matplotlib.pyplot as plt from basic_units import radians fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.plot([np...
[ "basic_units is not a python package, you should have a look for official matplotlib document:\n\nRadian ticks#\nPlot with radians from the basic_units mockup example package.\nThis example shows how the unit class can determine the tick locating,\nformatting and axis labeling.\nThis example requires basic_units.py...
[ 0, 0 ]
[]
[]
[ "matplotlib", "pip", "python" ]
stackoverflow_0074259599_matplotlib_pip_python.txt
Q: How to use Gurobi quicksum in Python to write this expression? I am trying to figure out how to write this constraint for Gurobi in Python. for j in city: for i in frequency: c2 = m.addConstr(gp.quicksum(x[i,j]) <= 1, "c2") But I am getting this error and I am a bit confused why it is wrong... A: The e...
How to use Gurobi quicksum in Python to write this expression?
I am trying to figure out how to write this constraint for Gurobi in Python. for j in city: for i in frequency: c2 = m.addConstr(gp.quicksum(x[i,j]) <= 1, "c2") But I am getting this error and I am a bit confused why it is wrong...
[ "The error message tells you that the quicksum function's argument is expected to be an iterable and a single Var object isn't iterable. Instead, you could do something like this:\nc2 = {}\nfor j in city:\n c2[j] = m.addConstr(gp.quicksum(x[i,j] for i in frequency) <= 1, \"c2\")\n\nAlternatively, you could use t...
[ 1 ]
[]
[]
[ "gurobi", "python" ]
stackoverflow_0074258446_gurobi_python.txt
Q: How to center the title and an image in streamlit? I've already tried the command below for the title and I couldn't. For the image, I just managed to center it by increasing the size so that it fills the entire page. Are there any arguments to st.title() and st.image that allow me to center them? title_alignment=...
How to center the title and an image in streamlit?
I've already tried the command below for the title and I couldn't. For the image, I just managed to center it by increasing the size so that it fills the entire page. Are there any arguments to st.title() and st.image that allow me to center them? title_alignment= """ <style> #the-title { text-align: center } </style...
[ "To center a text you can either use markdown like this:\n#A streamlit app with two centered texts with different seizes\nimport streamlit as st\n\nst.markdown(\"<h1 style='text-align: center; color: grey;'>Big headline</h1>\", unsafe_allow_html=True)\n\nst.markdown(\"<h2 style='text-align: center; color: black;'>S...
[ 6, 0 ]
[]
[]
[ "css", "python", "streamlit" ]
stackoverflow_0070932538_css_python_streamlit.txt
Q: pydantic : duplicate validator function I used the code below: It shows duplicated validator. Why cannot use both? How do I create an alias in the @validator if I cannot use Field? from pydantic import BaseModel, validator, Field import datetime class MultiSourceInput(BaseModel): abc : str = Field(..., al...
pydantic : duplicate validator function
I used the code below: It shows duplicated validator. Why cannot use both? How do I create an alias in the @validator if I cannot use Field? from pydantic import BaseModel, validator, Field import datetime class MultiSourceInput(BaseModel): abc : str = Field(..., alias= 'abc_1',description= "xxxxxxxxxxxx.") ...
[ "In my case, this occurred because the validation method was receiving self instead of cls, meaning:\n @validator(\"my_field\")\n def parse_my_field(self, v):\n ...\n\nInstead of:\n @validator(\"my_field\")\n def parse_my_field(cls, v):\n ...\n\n", "Check if there is a validator created ...
[ 2, 1, 0 ]
[]
[]
[ "pydantic", "python" ]
stackoverflow_0069655338_pydantic_python.txt
Q: I need an epub to text solution in Python I need to get text from an epub from epub_conversion.utils import open_book, convert_epub_to_lines f = open("demofile.txt", "a") book = open_book("razvansividra.epub") lines = convert_epub_to_lines(book) I use this but if I use print(lines) it does print only one line. A...
I need an epub to text solution in Python
I need to get text from an epub from epub_conversion.utils import open_book, convert_epub_to_lines f = open("demofile.txt", "a") book = open_book("razvansividra.epub") lines = convert_epub_to_lines(book) I use this but if I use print(lines) it does print only one line. And the library is 6 years old. Do you guys know...
[ "What about https://github.com/aerkalov/ebooklib\n\nEbookLib is a Python library for managing EPUB2/EPUB3 and Kindle\n files. It's capable of reading and writing EPUB files programmatically\n (Kindle support is under development).\nThe API is designed to be as simple as possible, while at the same\n time making ...
[ 3, 0, 0, 0 ]
[]
[]
[ "epub", "python" ]
stackoverflow_0055180484_epub_python.txt
Q: flask: stop server after exception I would like to stop my flask server as soon as an unhandled exception occurs. Here is an example: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): 1/0 # argh, exception return 'Hello World!' if __name__ == '__main__': app.run(port=1...
flask: stop server after exception
I would like to stop my flask server as soon as an unhandled exception occurs. Here is an example: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): 1/0 # argh, exception return 'Hello World!' if __name__ == '__main__': app.run(port=12345) If you run this and go to local...
[ "Stopping Flask requires getting into Werkzeug internals. See http://flask.pocoo.org/snippets/67/\nExtracted from a single-user app:\nfrom flask import request\n\n@app.route('/quit')\ndef shutdown():\n ...\n shutdown_hook = request.environ.get('werkzeug.server.shutdown')\n if shutdown_hook is not None:\n ...
[ 0, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0053327270_flask_python.txt
Q: Append a df as a column at the end of an csv file using Python I am appending a DF to an excel sheet. For some reason my DF values are being appended to the last row of the first column in my excel, but I need it to be appended as the last column of my excel (which is column BK). I need to include the header as we...
Append a df as a column at the end of an csv file using Python
I am appending a DF to an excel sheet. For some reason my DF values are being appended to the last row of the first column in my excel, but I need it to be appended as the last column of my excel (which is column BK). I need to include the header as well but don't need the index. The code I am using to append one speci...
[ "df.to_csv('excelfile.csv',columns=['Excel Column A','Excel Column B','Specific_Column'], mode='a',index=False)\n\nI can get the following results according to this code\nenter image description here\nenter image description here\nTry this\n" ]
[ 0 ]
[]
[]
[ "append", "dataframe", "export_to_excel", "python" ]
stackoverflow_0074259689_append_dataframe_export_to_excel_python.txt
Q: How do I connect a Python program in Visual Studio Code to MySQL Workbench 8.0? I am creating a program that uses VS Code and MySQL Workbench 8.0 together. I am stuck and do not know how to connect the two software together I also have to be able to upload records into a table that is stored in MySQL Workbench fro...
How do I connect a Python program in Visual Studio Code to MySQL Workbench 8.0?
I am creating a program that uses VS Code and MySQL Workbench 8.0 together. I am stuck and do not know how to connect the two software together I also have to be able to upload records into a table that is stored in MySQL Workbench from the Python program that uses variables. Please tell me if their are any details mis...
[ "There are many packages in python that can connect to the mysql database, here we take pymysql as an example.\n\nInstall pymysql\n\npip install PyMySQL\n\n\nI have already installed, so the prompt package already exists.\n\nSample code, query and insert data\n\nimport pymysql\n\ncon = pymysql.Connect(\n host='l...
[ 0 ]
[]
[]
[ "connection", "mysql", "mysql_workbench", "python", "visual_studio_code" ]
stackoverflow_0074250505_connection_mysql_mysql_workbench_python_visual_studio_code.txt
Q: How to generate dummy data like covid cases using python? I want to generate a random data with variable rate of increment not fixed one so that it resemble to real world. Thanks in advance I am not able to get a distribution like above A: Generating concise data on such a sensitive topic is not easy. I answer ...
How to generate dummy data like covid cases using python?
I want to generate a random data with variable rate of increment not fixed one so that it resemble to real world. Thanks in advance I am not able to get a distribution like above
[ "Generating concise data on such a sensitive topic is not easy. I answer this question with a purely demonstrative example, but I would refer you to reading scientific publications that explain well the underlying statistical criteria behind such studies.\nA good approach would be to train a machine learning model ...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python", "random" ]
stackoverflow_0074259391_numpy_pandas_python_random.txt
Q: Combining multiple pngs in a single pdf in python I am wondering if there is an easy way to combine multiple png images into a single pdf in python. I want each image to be a single page in the pdf. Is pypdf the best library to use for this? Any help would be greatly appreciated. Thanks! A: I've got the same pro...
Combining multiple pngs in a single pdf in python
I am wondering if there is an easy way to combine multiple png images into a single pdf in python. I want each image to be a single page in the pdf. Is pypdf the best library to use for this? Any help would be greatly appreciated. Thanks!
[ "I've got the same problem.\nSo I've created python function to unite multiple pictures in one pdf.\nCode is available at my github page on https://github.com/wizard1989/Unite-multiple-pictures-into-pdf.\nIt uses \"reportlab\".\nCode is based on answers from the following links:\nCreate PDF from a list of images\nC...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "image", "pdf", "python" ]
stackoverflow_0030154846_image_pdf_python.txt
Q: ModuleNotFoundError: No module named 'mlxtend.frequent_pattens' I have been trying to use apriori algorithm in my Jupyter notebook as well as Google Colab but keep running into the same error. I did everything that i could find. Installed mlxtend package through pip first but it was installed on an entirely differ...
ModuleNotFoundError: No module named 'mlxtend.frequent_pattens'
I have been trying to use apriori algorithm in my Jupyter notebook as well as Google Colab but keep running into the same error. I did everything that i could find. Installed mlxtend package through pip first but it was installed on an entirely different channel. Then i tried to install it through condaforge(according ...
[ "I shall delete this question as I figured out the error. It was a simple spelling error.\nfrom mlxtend.frequent_patterns import apriori\n\nI had missed the 'r' in patterns.\n" ]
[ 0 ]
[]
[]
[ "anaconda", "anaconda3", "apriori", "mlxtend", "python" ]
stackoverflow_0074064826_anaconda_anaconda3_apriori_mlxtend_python.txt
Q: Convert and manipulate a list of strings into a string (with extra characters) Using Python, I would like to convert a list to string looks like this: I'm looking for a more elegant way then loops cmd = ['cd ..', 'pwd', 'howami'] "cd..; pwd; howami" Thanks in advance (it is my first question BTW, please be gentl...
Convert and manipulate a list of strings into a string (with extra characters)
Using Python, I would like to convert a list to string looks like this: I'm looking for a more elegant way then loops cmd = ['cd ..', 'pwd', 'howami'] "cd..; pwd; howami" Thanks in advance (it is my first question BTW, please be gentle) Roy for cmdStr in cmd:
 cmdString += cmdStr + '; ' cmdString.rstrip('; '...
[ "You can use the join function.\n\"; \".join(cmd)\n\noutput\ncd ..; pwd; howami\n\n", "The method you are looking for is join.\nIn your example it would look like this:\ncmd = ['cd ..', 'pwd', 'howami']\n\n\"; \".join(cmd)\n\nMore on join in python docs: https://docs.python.org/3/library/stdtypes.html#str.join\n"...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074259709_python.txt
Q: Why does output of subprocess.run appear too early? I'm writing a script which runs in a CI/CD pipeline. It first does some configuration (fetching credentials, pulling down files from a server). Then, it runs an external CLI tool to analyse these files using subprocess.run(cli_args). After that is done, the resul...
Why does output of subprocess.run appear too early?
I'm writing a script which runs in a CI/CD pipeline. It first does some configuration (fetching credentials, pulling down files from a server). Then, it runs an external CLI tool to analyse these files using subprocess.run(cli_args). After that is done, the results are published to a few other systems. My problem is th...
[ "This is most likely because python buffers its standard output, so flush it before calling subprocess\nsys.stdout.flush()\n\n" ]
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0074259785_python_subprocess.txt
Q: Cannot copy to a TensorFlowLite tensor (input_values:0) with 0 bytes from a Java Buffer with 49152 bytes Hi I want to feed an input to my .tflite model in android studio 7.2.1 with below code : val catBitmap = getBitmapFromAsset("bwr.jpg")// a 64*64 image val output2 = TensorImage(DataType.FLOAT32...
Cannot copy to a TensorFlowLite tensor (input_values:0) with 0 bytes from a Java Buffer with 49152 bytes
Hi I want to feed an input to my .tflite model in android studio 7.2.1 with below code : val catBitmap = getBitmapFromAsset("bwr.jpg")// a 64*64 image val output2 = TensorImage(DataType.FLOAT32) for (y in 0..63) { for (x in 0..63) { val px: Int = catBitmap.g...
[ "Finally, I found the answer.\nThere was a problem with my .tflite model. I could not feed input to my model. when I removed some nodes from my graph and added some preprocessing steps to my graph. the problem fixed.\n" ]
[ 0 ]
[]
[]
[ "android_studio", "java", "python", "tensorflow", "tflite" ]
stackoverflow_0073246611_android_studio_java_python_tensorflow_tflite.txt
Q: How to schedule concurrent.future.Threadpool.executor map() function in python I have one web scraping function which fetches data of 190 URL's. To complete it fast I used concurrent.future.Threadpool.executor. I am saving that data to SQL Server database. I have to do these all process repeatedly to every 3 mins ...
How to schedule concurrent.future.Threadpool.executor map() function in python
I have one web scraping function which fetches data of 190 URL's. To complete it fast I used concurrent.future.Threadpool.executor. I am saving that data to SQL Server database. I have to do these all process repeatedly to every 3 mins from 9AM to 4PM. But when I use while loop or scheduler that concurrent future not w...
[ "You can create a seperate function and schedule it to execute the data_fetched(). I hope your urls variable contains the list of urls and not empty list.\nfrom schedule import every, repeat, run_pending\nimport time\nimport request\n\n\nurls = []\n\ndef data_fetched(url):\n # data fetching\n # operations on ...
[ 1 ]
[]
[]
[ "concurrent.futures", "multithreading", "python", "scheduler" ]
stackoverflow_0074259727_concurrent.futures_multithreading_python_scheduler.txt
Q: How to remove specific string on list from dataframe I have a list of stopwords and want to remove the words in the list from my dataframe. my dataframe is like this: data['review_normalized'] ['bagus'] ['sangat', 'baik'] ['oke'] ['setiap', 'mau', 'meeeting', 'lah'] My code is: list_stopwords ...
How to remove specific string on list from dataframe
I have a list of stopwords and want to remove the words in the list from my dataframe. my dataframe is like this: data['review_normalized'] ['bagus'] ['sangat', 'baik'] ['oke'] ['setiap', 'mau', 'meeeting', 'lah'] My code is: list_stopwords = (["yang", "rt", "dengan", "nya", "di", ...
[ "In column are strings, for convert them to lists use ast.literal_eval:\nimport ast\n\n# convert list to dictionary \nlist_stopwords = set(list_stopwords) \n\n#remove stopword pada strings converted to lists token \ndef stopwords_removal(words): \n return [word for word in ast.literal_eval(words) if ...
[ 1 ]
[]
[]
[ "dataframe", "list", "pandas", "python", "string" ]
stackoverflow_0074259908_dataframe_list_pandas_python_string.txt
Q: printing a number table of square n: 8 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 How to print a number table like this in python with n that can be any number? I am...
printing a number table of square
n: 8 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 How to print a number table like this in python with n that can be any number? I am using a very stupid way to print it bu...
[ "I won't show you the code directly, here is some tips for you. Do you know % operator in python? And how to use it to break lines. As for the format, zfill function will help you. You may need to learn for or while statement to solve your problem\n", "You can do this with a range loop and a list comprehension.\n...
[ 0, 0 ]
[]
[]
[ "numbers", "python" ]
stackoverflow_0074259497_numbers_python.txt
Q: Count the number of minutes in shift and distribute them I have shifts of 10 people, and i want to count the number of minutes by dividing them in early morning shift afternoon shift and night shift, assuming the early morning shift is from 6 am to 12 am afternoon being 12 am to 7 pm and night being 7 pm to 2 am, ...
Count the number of minutes in shift and distribute them
I have shifts of 10 people, and i want to count the number of minutes by dividing them in early morning shift afternoon shift and night shift, assuming the early morning shift is from 6 am to 12 am afternoon being 12 am to 7 pm and night being 7 pm to 2 am, and people can have shifts overlapping so 1 person can have a ...
[ "Create helper dictonary by ranges, use Series.map for shifts and aggregate GroupBy.size for counts:\nd = {'early morning':[range(6, 12)], \n 'afternoon':[range(12, 19)], \n 'night':[range(19, 25), range(0, 2)]}\n\nd1 = {y: k for k, v in d.items() for x in v for y in x}\ndf['shift'] = df['hour'].map(d1)\n\n...
[ 0 ]
[]
[]
[ "datetime", "pandas", "python", "python_datetime", "time" ]
stackoverflow_0074259204_datetime_pandas_python_python_datetime_time.txt
Q: How to revert a flat dictionary with exploded lists into a nested dictionary in Python I have written a function that takes a nested structure, and flattens it while also exploding any list elements. def __flatten_dict_explode_list(d,flat_d,is_list=False, path=[]): if not is_list: for k, v in d.items()...
How to revert a flat dictionary with exploded lists into a nested dictionary in Python
I have written a function that takes a nested structure, and flattens it while also exploding any list elements. def __flatten_dict_explode_list(d,flat_d,is_list=False, path=[]): if not is_list: for k, v in d.items(): if (isinstance(v, dict) and v != {}): __flatten_dict_explode_l...
[ "Something like this would work as __unflatten_dict_help:\ndef __unflatten_dict_help(key, val, d, sep):\n parts = [p if len(p) < 2 or p[0] != '[' or p[-1] != ']' else\n int(p[1:-1]) for p in key.split(separator)]\n for part, next_part in zip(parts, parts[1:] + [-1]):\n if isinstance(part, i...
[ 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074259426_dictionary_python.txt
Q: DJANGO: How can I create a custom User with a OneToOne relationship to Person I have a custom user model, I would like my CustomUser model to have a OneToOne relationship with the Person model; Since I want to first register persons and then create a username for them, since not all registered people need to have ...
DJANGO: How can I create a custom User with a OneToOne relationship to Person
I have a custom user model, I would like my CustomUser model to have a OneToOne relationship with the Person model; Since I want to first register persons and then create a username for them, since not all registered people need to have a username. I have tried the code shown below; but what I get is the following erro...
[ "What you're probably looking to do is subclass the django registration form. Then you can change the fields that are required.\nI believe the password field would be required by default so a NULL value would not be valid. However, you could quite easily set the password as a randomly generated UUID and then manual...
[ 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0074256349_authentication_django_python.txt
Q: PROBLEM: pandas.DataFrame.mean deleting columns I'm working with Google Colab to create a neural network. I've imported the dataset and created the dataframe, but when I use the function mean it deletes last columns (from the column "res_x4trap"). What I'm doing wrong? Here's the code: import numpy as np import pa...
PROBLEM: pandas.DataFrame.mean deleting columns
I'm working with Google Colab to create a neural network. I've imported the dataset and created the dataframe, but when I use the function mean it deletes last columns (from the column "res_x4trap"). What I'm doing wrong? Here's the code: import numpy as np import pandas as pd import tensorflow as tf from tensorflow im...
[ "I ran into that same problem, it turns out one of my columns was of type object because there were problematic entries, so pandas didn't know what to do when calculating the mean so it just deleted it.\nSo check the dtype of the columns using\ndf.dtypes\n" ]
[ 1 ]
[]
[]
[ "dataframe", "mean", "pandas", "python" ]
stackoverflow_0074013060_dataframe_mean_pandas_python.txt