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: Is it bad practice to define *args and **kwargs for future inheritance as a default in Python? Say I have a project with class Subscriber that I implement with constructors and methods that I need at this time of my project. Later my functionality needs a subclass of Subscriber, let's say Gold_subscriber that has ...
Is it bad practice to define *args and **kwargs for future inheritance as a default in Python?
Say I have a project with class Subscriber that I implement with constructors and methods that I need at this time of my project. Later my functionality needs a subclass of Subscriber, let's say Gold_subscriber that has methods that have different needs for arguments, for example more arguments, keyword arguments etc. ...
[ "I guess you are ok with unused **kwargs if those are at least commented in the code (space for future expansion) - but it is not the same for *args: adding positional arguments in specialized classes is much more problematic, due to possible conflicting arguments down the tree, and it would kill the possibility o...
[ 0 ]
[]
[]
[ "arguments", "inheritance", "keyword_argument", "python" ]
stackoverflow_0074625657_arguments_inheritance_keyword_argument_python.txt
Q: QListWidget and Multiple Selection I have a regular QListWidget with couple of signals and slots hookedup. Everything works as I expect. I can update, retrieve, clear etc. But the UI wont support multiple selections. How do I 'enable' multiple selections for QListWidget? My limited experience with PyQt tells me I ...
QListWidget and Multiple Selection
I have a regular QListWidget with couple of signals and slots hookedup. Everything works as I expect. I can update, retrieve, clear etc. But the UI wont support multiple selections. How do I 'enable' multiple selections for QListWidget? My limited experience with PyQt tells me I need to create a custom QListWidget by s...
[ "Unfortunately I can't help with the Python specific syntax but you don't need to create any subclasses. \nAfter your QListWidget is created, call setSelectionMode() with one of the multiple selection types passed in, probably QAbstractItemView::ExtendedSelection is the one you want. There are a few variations on t...
[ 34, 30, 13, 5, 4, 0 ]
[]
[]
[ "pyqt", "python", "qlistwidget", "user_interface" ]
stackoverflow_0004008649_pyqt_python_qlistwidget_user_interface.txt
Q: No problems have been detected in the workspace so far I am using and have been usnig Visual Studio to develop Python code. Previously when I saved a file it would review the code and provide warnings and errors. Now I only get "No problems have been detected in the workspace so far" I have looked through settings...
No problems have been detected in the workspace so far
I am using and have been usnig Visual Studio to develop Python code. Previously when I saved a file it would review the code and provide warnings and errors. Now I only get "No problems have been detected in the workspace so far" I have looked through settings but cannot find anything unchecked that is relevant. I have...
[ "Maybe you can switch the linter, such as from 'pylint' to 'flake8' or other switches. If you don't know how to switch, you can refer to this page.\nIf it still doesn't work, maybe some extension you installed caused the problem. Try to disable the extensions, and remember to restart the VSCode. You can refer to\nt...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "visual_studio_code", "vscode_settings" ]
stackoverflow_0062720400_python_visual_studio_code_vscode_settings.txt
Q: ModuleNotFoundError: No module named 'dlt' error when running Delta Live Tables Python notebook When attempting to create a Python notebook and follow the various examples for setting up databricks delta live tables, you will immediately be met with the following error if you attempt to run your notebook: ModuleN...
ModuleNotFoundError: No module named 'dlt' error when running Delta Live Tables Python notebook
When attempting to create a Python notebook and follow the various examples for setting up databricks delta live tables, you will immediately be met with the following error if you attempt to run your notebook: ModuleNotFoundError: No module named 'dlt' A self-sufficient developer may then attempt to resolve this wit...
[ "Gotcha! While you are expected to compose your delta live tables setup code in the databricks notebook environment, you are not meant to run it there. The only supported way to run your code is to head on over to the pipelines interface to run it.\nEnd of Answer.\nAlthough....\n\nThis is bad news for developers wh...
[ 0 ]
[]
[]
[ "azure_databricks", "databricks", "delta_live_tables", "pyspark", "python" ]
stackoverflow_0074646723_azure_databricks_databricks_delta_live_tables_pyspark_python.txt
Q: Creating a BAT file for python script How can I create a simple BAT file that will run my python script located at C:\somescript.py? A: c:\python27\python.exe c:\somescript.py %* A: Open a command line (⊞ Win+R, cmd, ↵ Enter) and type python -V, ↵ Enter. You should get a response back, something like Python 2....
Creating a BAT file for python script
How can I create a simple BAT file that will run my python script located at C:\somescript.py?
[ "c:\\python27\\python.exe c:\\somescript.py %*\n\n", "Open a command line (⊞ Win+R, cmd, ↵ Enter)\nand type python -V, ↵ Enter.\nYou should get a response back, something like Python 2.7.1.\nIf you do not, you may not have Python installed. Fix this first.\nOnce you have Python, your batch file should look like\n...
[ 71, 60, 19, 14, 6, 5, 3, 2, 2, 1, 0, 0, 0, 0, 0 ]
[ "start xxx.py\nYou can use this for some other file types.\n" ]
[ -1 ]
[ "batch_file", "python" ]
stackoverflow_0004571244_batch_file_python.txt
Q: Python: request url and get contents I am trying to get transaction history for the following address 9QgXqrgdbVU8KcpfskqJpAXKzbaYQJecgMAruSWoXDkM from the https://explorer.solana.com website. I have tried url="https://explorer.solana.com/address/9QgXqrgdbVU8KcpfskqJpAXKzbaYQJecgMAruSWoXDkM" output = requests.get(...
Python: request url and get contents
I am trying to get transaction history for the following address 9QgXqrgdbVU8KcpfskqJpAXKzbaYQJecgMAruSWoXDkM from the https://explorer.solana.com website. I have tried url="https://explorer.solana.com/address/9QgXqrgdbVU8KcpfskqJpAXKzbaYQJecgMAruSWoXDkM" output = requests.get(url).text print(output) However this give...
[ "The history data is loaded from external URL via JavaScript. You can use requests module to simulate this call:\nimport requests\nimport pandas as pd\n\n\napi_url = \"https://explorer-api.mainnet-beta.solana.com/\"\n\npayload = {\n \"id\": \"xxx\",\n \"jsonrpc\": \"2.0\",\n \"method\": \"getConfirmedSigna...
[ 2 ]
[]
[]
[ "get", "python", "python_requests", "solana", "url" ]
stackoverflow_0074646545_get_python_python_requests_solana_url.txt
Q: how to keep adding the value of an item? menu = { "Baja Taco": 4.00, "Burrito": 7.50, "Bowl": 8.50, "Nachos": 11.00, "Quesadilla": 8.50, "Super Burrito": 8.50, "Super Quesadilla": 9.50, "Taco": 3.00, "Tortilla Salad": 8.00 } while True: # keep adding to the price if user pr...
how to keep adding the value of an item?
menu = { "Baja Taco": 4.00, "Burrito": 7.50, "Bowl": 8.50, "Nachos": 11.00, "Quesadilla": 8.50, "Super Burrito": 8.50, "Super Quesadilla": 9.50, "Taco": 3.00, "Tortilla Salad": 8.00 } while True: # keep adding to the price if user prompts another item # i know the operation ...
[ "Things you need to do:\n\nDefine a variable for storing total outside the loop otherwise the variable will be overridden everytime\nGet the price from the menu dictionary and add it to the total\n\nIf both changes are done, the code should look something like this\ntotal = 0\nwhile True:\n try:\n x = inp...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074646662_python.txt
Q: Module function in cython gets extra check that a static method doesn't I have the following class static method and method user: @cython.cclass class TestClass: @staticmethod @cython.cfunc def func(v: float) -> float: return v + 1.0 def test_call(self): res = TestClass.func(2) ...
Module function in cython gets extra check that a static method doesn't
I have the following class static method and method user: @cython.cclass class TestClass: @staticmethod @cython.cfunc def func(v: float) -> float: return v + 1.0 def test_call(self): res = TestClass.func(2) return res The line res = TestClass.func(2) shows as white in the annn...
[ "You can make a cdef/cfunc function unable to raise an exception using @cython.exceptval(check=False) (or cdef float func() noexcept in the non-pure-Python syntax). See the documentation for full details about exceptions. If you do this it won't be checked.\nCython 3 has changed the default behaviour from \"cdef fu...
[ 1 ]
[]
[]
[ "arguments", "cython", "performance", "python" ]
stackoverflow_0074640883_arguments_cython_performance_python.txt
Q: I was doing K-means Clustering, before that, each data in the database has to be assigned to an index. However, TypeError occurs, how to fix it? Here's my code: with connection: with connection.cursor() as cursor: sql = """ SELECT `CPC-Current-DWPI`,`Assignee/Applicant First` FROM final.f...
I was doing K-means Clustering, before that, each data in the database has to be assigned to an index. However, TypeError occurs, how to fix it?
Here's my code: with connection: with connection.cursor() as cursor: sql = """ SELECT `CPC-Current-DWPI`,`Assignee/Applicant First` FROM final.f01l_patent; """ cursor.execute(sql) result = cursor.fetchall() count = [] ro=0 for i in...
[ "Your result is a list of Tuples. Try replacing the string 'CPC - Current - DWPI.split()' with the index (as an integer) of the item you want.\n" ]
[ 1 ]
[]
[]
[ "k_means", "python" ]
stackoverflow_0074646716_k_means_python.txt
Q: How to successfully use pandas.Dataframe.apply with pandas.NA and lambdas Given a dataframe with a pandas.NA value, how can I run a decision lambda over it import pandas import numpy # Setup dataframe = pandas.DataFrame({"c1": [1, 2, 3, 4], "c2": [2, 3, 4, pandas.NA]}) print(dataframe) my_lambda = lambda row: row[...
How to successfully use pandas.Dataframe.apply with pandas.NA and lambdas
Given a dataframe with a pandas.NA value, how can I run a decision lambda over it import pandas import numpy # Setup dataframe = pandas.DataFrame({"c1": [1, 2, 3, 4], "c2": [2, 3, 4, pandas.NA]}) print(dataframe) my_lambda = lambda row: row["c2"] if row["c2"] else row["c1"] # the issue dataframe["c2"] = dataframe.ap...
[ "You could just do\ndataframe.apply(lambda row: row[\"c2\"] if pd.notna(row[\"c2\"]) else row[\"c1\"], axis=1)\n\nOr better\ndataframe['c2'] = dataframe['c2'].fillna(dataframe['c1'])\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "lambda", "pandas", "python", "python_3.x" ]
stackoverflow_0074646756_dataframe_lambda_pandas_python_python_3.x.txt
Q: How can I identify objects inside the image using python opencv? I'm trying to identify objects present inside the plane area as in below image for some automation image1 for this I tried finding the contours on masked image obtained using thresholding the hsv range of object border colors which is yellowish then ...
How can I identify objects inside the image using python opencv?
I'm trying to identify objects present inside the plane area as in below image for some automation image1 for this I tried finding the contours on masked image obtained using thresholding the hsv range of object border colors which is yellowish then I did morphing operation to remove the small open lines and dilution o...
[ "Not perfect but here is another possible method:\nimport cv2\nfrom matplotlib import pyplot as plt\nimport matplotlib\nimport numpy as np\n\nmatplotlib.use('TkAgg')\n\n\ndef remove_noise(binary_image, max_noise_size=20):\n labels_count, labeled_image, stats, centroids = cv2.connectedComponentsWithStats(\n ...
[ 0 ]
[]
[]
[ "computer_vision", "image_processing", "opencv", "python", "python_3.x" ]
stackoverflow_0074642490_computer_vision_image_processing_opencv_python_python_3.x.txt
Q: How to allow a max Manhattan distance between all the points in a group I have a 2D-array in which I want to make groups where all the points in a group have a max Manhattan distance between them. The groups can be disjoint. For example, from this starting array (10 x 10): [[ 67 97 72 35 73 77 80 48 21 34...
How to allow a max Manhattan distance between all the points in a group
I have a 2D-array in which I want to make groups where all the points in a group have a max Manhattan distance between them. The groups can be disjoint. For example, from this starting array (10 x 10): [[ 67 97 72 35 73 77 80 48 21 34] [ 11 30 16 1 71 68 72 1 81 23] [ 85 31 94 10 50 85 63 1...
[ "In layman's terms, you wish to find k classification areas also known as clusters. In this case, I recommend you first read about clustering. After you acquire enough knowledge, you can advance on this related question, which generalizes this classification for a custom distance function.\n" ]
[ 0 ]
[]
[]
[ "arrays", "grouping", "manhattan", "multidimensional_array", "python" ]
stackoverflow_0074644378_arrays_grouping_manhattan_multidimensional_array_python.txt
Q: How to select the elements of a Pandas DataFrame given a Boolean mask? I was wondering wether, given a boolean mask, there is a way to retreive all the elements of a DataFrame positioned in correspondance of the True values in the mask. In my case I have a DataFrame containing the values of a certain dataset, for ...
How to select the elements of a Pandas DataFrame given a Boolean mask?
I was wondering wether, given a boolean mask, there is a way to retreive all the elements of a DataFrame positioned in correspondance of the True values in the mask. In my case I have a DataFrame containing the values of a certain dataset, for example let's take the following : l = [[5, 3, 1], [0, 3, 1], [7...
[ "You can use df.values to return a numpy representation of the DataFrame then use numpy.isnan and keep other values.\nimport numpy as np\narr = df.values\nres = arr[~np.isnan(arr)]\nprint(res)\n# [1. 2. 8. 8. 25. 6.]\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074646803_dataframe_pandas_python.txt
Q: Save html to file to work with later using Beautiful Soup I am doing a lot of work with Beautiful Soup. However, my supervisor does not want me doing the work "in real time" from the web. Instead, he wants me to download all the text from a webpage and then work on it later. He wants to avoid repeated hits on a we...
Save html to file to work with later using Beautiful Soup
I am doing a lot of work with Beautiful Soup. However, my supervisor does not want me doing the work "in real time" from the web. Instead, he wants me to download all the text from a webpage and then work on it later. He wants to avoid repeated hits on a website. Here is my code: import requests from bs4 import Beautif...
[ "So saving soup would be... tough, and out of my experience (read more about the pickleing process if interested). You can save the page as follows:\npage = requests.get(url)\nwith open('path/to/saving.html', 'wb+') as f:\n f.write(page.content)\n\nThen later, when you want to do analysis on it:\nwith open('path...
[ 4, 2, 0 ]
[]
[]
[ "file", "html", "python", "save" ]
stackoverflow_0067829316_file_html_python_save.txt
Q: OSError [Errno 22] invalid argument when use open() in Python def choose_option(self): if self.option_picker.currentRow() == 0: description = open(":/description_files/program_description.txt","r") self.information_shower.setText(description.read()) elif self.option_picker.c...
OSError [Errno 22] invalid argument when use open() in Python
def choose_option(self): if self.option_picker.currentRow() == 0: description = open(":/description_files/program_description.txt","r") self.information_shower.setText(description.read()) elif self.option_picker.currentRow() == 1: requirements = open(":/description_fi...
[ "That is not a valid file path. You must either use a full path\nopen(r\"C:\\description_files\\program_description.txt\",\"r\")\n\nOr a relative path\nopen(\"program_description.txt\",\"r\")\n\n", "Add 'r' in starting of path:\npath = r\"D:\\Folder\\file.txt\"\n\nThat works for me.\n", "I also ran into this fa...
[ 48, 12, 9, 7, 4, 3, 3, 2, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0025584124_python.txt
Q: python CSV writer keep escape character I have a CSV file, here are two lines in the file. c1,c2,c3,c4,c5 17939,2507974,11,DVD version has 1 hour of extras of 5 bonus matches including: - Stacy Keibler vs Torrie Wilson in a bikini contest. - A tour of Trish Stratus\' place. - Behind the scenes look at the WWE wome...
python CSV writer keep escape character
I have a CSV file, here are two lines in the file. c1,c2,c3,c4,c5 17939,2507974,11,DVD version has 1 hour of extras of 5 bonus matches including: - Stacy Keibler vs Torrie Wilson in a bikini contest. - A tour of Trish Stratus\' place. - Behind the scenes look at the WWE women division.,NULL 16641,2425413,11,"The Austra...
[ "You can use doublequote=False in csv.writer:\nimport csv\n\nwith open(\"input.csv\", \"r\") as f_in, open(\"output.csv\", \"w\") as f_out:\n reader = csv.reader(f_in, delimiter=\",\", quotechar='\"', escapechar=\"\\\\\")\n writer = csv.writer(\n f_out,\n delimiter=\",\",\n quotechar='\"'...
[ 0 ]
[]
[]
[ "backslash", "csv", "csvreader", "python" ]
stackoverflow_0074646678_backslash_csv_csvreader_python.txt
Q: Error: "metadata generation failed", can't install Artic Module I am trying to get started with downloading this project: https://github.com/sadighian/crypto-rl And I've downloaded the packages in the requirements file but I can't figure out why the artic package won't download. I am getting this error: × python...
Error: "metadata generation failed", can't install Artic Module
I am trying to get started with downloading this project: https://github.com/sadighian/crypto-rl And I've downloaded the packages in the requirements file but I can't figure out why the artic package won't download. I am getting this error: × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [...
[ "I faced a similar issue, due a recent change in pip. I solved it by adding the following to the installation command:\n--use-deprecated=backtrack-on-build-failures\n\nE.g. instead of pip install numpy I now ran:\npip install numpy --use-deprecated=backtrack-on-build-failures\n\n", "I had the same problem with me...
[ 21, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0070916814_python.txt
Q: How to sort this list to make the exponent value go first? Given list = [10, '3 ^ 2', '2 ^ 3'], how to sort the list to make the exponents values ( '3 ^ 2' and 2 ^ 3 ) are before any integer / float value and exponent values are sorted from the base. Desired Output: ['2 ^ 3', '3 ^ 2', 10] I have tried to remove() ...
How to sort this list to make the exponent value go first?
Given list = [10, '3 ^ 2', '2 ^ 3'], how to sort the list to make the exponents values ( '3 ^ 2' and 2 ^ 3 ) are before any integer / float value and exponent values are sorted from the base. Desired Output: ['2 ^ 3', '3 ^ 2', 10] I have tried to remove() and insert() the value but I can't figure out how to find the in...
[ "You shouldn't use list as a variable, it is reserved in python.\nNot pretty, but you can use this\nsorted(mylist, key=lambda x: (-len(str(x).split('^')), str(x).split('^')[0]))\n\nThis is sorting according to two criteria, first if there is an exponent, and then by the value of the base.\n" ]
[ 1 ]
[]
[]
[ "exponent", "list", "python" ]
stackoverflow_0074646874_exponent_list_python.txt
Q: Pandas: resample hourly values to monthly values with offset I want to aggregate a pandas.Series with an hourly DatetimeIndex to monthly values - while considering the offset to midnight. Example Consider the following (uniform) timeseries that spans about 1.5 months. import pandas as pd hours = pd.Series(1, pd.da...
Pandas: resample hourly values to monthly values with offset
I want to aggregate a pandas.Series with an hourly DatetimeIndex to monthly values - while considering the offset to midnight. Example Consider the following (uniform) timeseries that spans about 1.5 months. import pandas as pd hours = pd.Series(1, pd.date_range('2020-02-23 06:00', freq = 'H', periods=1008)) hours # 20...
[ "Not too much of an improvement on your attempt, but you could write the resampling as\nmonths = hours.resample('D', offset='06:00:00').sum().resample('MS').sum()\n\nchanging the index labels still requires the hack you've been doing, as in adding the time delta manually and setting freq to MS\nnote that you can pa...
[ 1 ]
[ "To aggregate a pandas.Series with an hourly DatetimeIndex to monthly values while considering the offset to midnight, you can use the offset parameter in the resample method to specify the offset from midnight to start the aggregation from. For example, if you want to start the aggregation from 6:00 AM, you can us...
[ -1 ]
[ "datetime", "pandas", "pandas_resample", "python" ]
stackoverflow_0074401212_datetime_pandas_pandas_resample_python.txt
Q: How can I find out the amount of susceptible, infected and recovered individuals in time = 50, where S(50), I(50), R(50)? (SIR MODEL) How can I find out the amount of susceptible, infected and recovered individuals in time = 50, where S(50), I(50), R(50)? (SIR MODEL) # Equações diferenciais e suas condições inicia...
How can I find out the amount of susceptible, infected and recovered individuals in time = 50, where S(50), I(50), R(50)? (SIR MODEL)
How can I find out the amount of susceptible, infected and recovered individuals in time = 50, where S(50), I(50), R(50)? (SIR MODEL) # Equações diferenciais e suas condições iniciais h = 0.05 beta = 0.8 nu = 0.3125 def derivada_S(time,I,S): return -beta*I*S def derivada_I(time,I,S): return beta*I*S - nu*I d...
[ "This link maybe help you to build the model SIR-derived ODE models\nalso here by I have code for you:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nBeta = 1.00205\nGamma = 0.23000\nN = 1000\n\ndef func_S(t,I,S):\n return - Beta*I*S/N\n\ndef func_I(t,I,S):\n return Beta*I*S/N - Gamma*I\n\ndef func_R...
[ 2, 0, 0 ]
[]
[]
[ "model", "python", "runge_kutta" ]
stackoverflow_0074513361_model_python_runge_kutta.txt
Q: pandas groupby and join lists I have a dataframe df, with two columns, I want to groupby one column and join the lists belongs to same group, example: column_a, column_b 1, [1,2,3] 1, [2,5] 2, [5,6] after the process: column_a, column_b 1, [1,2,3,2,5] 2, [5,6] I want to ...
pandas groupby and join lists
I have a dataframe df, with two columns, I want to groupby one column and join the lists belongs to same group, example: column_a, column_b 1, [1,2,3] 1, [2,5] 2, [5,6] after the process: column_a, column_b 1, [1,2,3,2,5] 2, [5,6] I want to keep all the duplicates. I have the...
[ "object dtype is a catch-all dtype that basically means not int, float, bool, datetime, or timedelta. So it is storing them as a list. convert_objects tries to convert a column to one of those dtypes.\nYou want\nIn [63]: df\nOut[63]: \n a b c\n0 1 [1, 2, 3] foo\n1 1 [2, 5] bar\n2 2 [5, 6...
[ 83, 23, 3, 1, 0 ]
[ "Thanks, helped me\nmerge.fillna(\"\", inplace = True) new_merge = merge.groupby(['id']).agg({ 'q1':lambda x: ','.join(x), 'q2':lambda x: ','.join(x),'q2_bookcode':lambda x: ','.join(x), 'q1_bookcode':lambda x: ','.join(x)}) \n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0023794082_pandas_python.txt
Q: python multiprocessing pool does nothing while executing I am currently trying to parallize a rather large task of computing a complex system of differential equations. I want to parallize the computation, so each computation has its own process. I need the results to be ordered, therefore I am using a dictionary ...
python multiprocessing pool does nothing while executing
I am currently trying to parallize a rather large task of computing a complex system of differential equations. I want to parallize the computation, so each computation has its own process. I need the results to be ordered, therefore I am using a dictionary to order it after the process. I am also on Windows 10. For no...
[ "there's a problem with multiprocessing and jupyterlab, so you should use pathos instead.\nimport multiprocessing as mp\nimport numpy as np\nimport scipy.constants as constants\nfrom concurrent.futures import ProcessPoolExecutor\nimport pathos.multiprocessing as mpathos\n\nNmin = 0\nNmax = 20\nperiods = np.linspace...
[ 1 ]
[]
[]
[ "jupyter_lab", "multiprocessing", "python" ]
stackoverflow_0074646673_jupyter_lab_multiprocessing_python.txt
Q: Pass dynamically created data-tables to another callback function as input in Dash The data tables have been created using the following snippet @app.callback( Output(component_id="my-tables-out", component_property="children")) def update_output_div(): params = ["A", "B"] num_tables = 5 for i in r...
Pass dynamically created data-tables to another callback function as input in Dash
The data tables have been created using the following snippet @app.callback( Output(component_id="my-tables-out", component_property="children")) def update_output_div(): params = ["A", "B"] num_tables = 5 for i in range(5): table = dash_table.DataTable( id=f"table-{i}", ...
[ "You can implement my-tables-out component id as the input to the next callback function and 'loop' for each table (since it is in a result list).\nIn your current implementation, it does not make sense to have table-1, table-2, table-3, etc. changing the data component because it is not possible in Dash to have mu...
[ 0 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074608153_plotly_dash_python.txt
Q: How to add items to a dictionary between two methods? I'm writing a method that takes in a list and returns a dictionary. This method is to be saved in a separate Python file and imported into Main.py The method that takes in a list calls another method that's meant to update the global dictionary. global myDict ...
How to add items to a dictionary between two methods?
I'm writing a method that takes in a list and returns a dictionary. This method is to be saved in a separate Python file and imported into Main.py The method that takes in a list calls another method that's meant to update the global dictionary. global myDict def addKeyValuePair(listItem): try: key = list...
[ "There are a few issues with the code you posted.\nFirst, you are trying to access a global variable called myDict from inside the makeDict function. However, you also define a local variable with the same name inside the function, which shadows the global variable. As a result, any modifications made to the local ...
[ 1 ]
[]
[]
[ "dictionary", "global_variables", "python" ]
stackoverflow_0074646916_dictionary_global_variables_python.txt
Q: How can i optimize my code so that it can run much more effciently? i am sorry if this this is the wrong type of question to ask here because its mostly like "pls help me fix bug" but if someone is willing to help that would be nice! so basiclly i am making a small game where at the current stage i click somewhere...
How can i optimize my code so that it can run much more effciently?
i am sorry if this this is the wrong type of question to ask here because its mostly like "pls help me fix bug" but if someone is willing to help that would be nice! so basiclly i am making a small game where at the current stage i click somewhere and color will spread out like a wave. currently it does that, but i am ...
[ "Probably the only way to get acceptable performance (with pygame) is to use pygame.mask.Mask and convolve(). Create a mask size of the screen:\nmask = pygame.mask.Mask(screen.get_size())\n\nCreate a convolution mask with the following pattern:\n[False, True, False]\n[True, True, True ]\n[False, True, False]\n\...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074616707_pygame_python.txt
Q: how to converting a for loop with await into asyncio.gather() how do I write the following piece of code using asyncio.gather and map? for i in range(len(data)): candlestick = data[i] candlesticks = data[0: i + 1] await strategy.execute(candlesticks, candlestick.startTim...
how to converting a for loop with await into asyncio.gather()
how do I write the following piece of code using asyncio.gather and map? for i in range(len(data)): candlestick = data[i] candlesticks = data[0: i + 1] await strategy.execute(candlesticks, candlestick.startTime)
[ "You could do it like this:\nfrom asyncio import gather, create_task\ntasks = []\nfor i in range(len(data)):\n candlestick = data[i]\n candlesticks = data[0: i + 1]\n tasks.append(create_task(strategy.execute(candlesticks, candlestick.startTime)))\nresults = await gather(*tasks, return_exceptions=False)\n\...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0071203112_python.txt
Q: Add a column (in Pandas) that is calculated based on another column I have a simple database that has every month's earnings, with Year (values 1991-2020), Month (Jan-Dec) and Earnings. I want to make a new column, where for years 1991-2005 I divide the Earnings column by 10000 but for 2006-2020 I want it to be th...
Add a column (in Pandas) that is calculated based on another column
I have a simple database that has every month's earnings, with Year (values 1991-2020), Month (Jan-Dec) and Earnings. I want to make a new column, where for years 1991-2005 I divide the Earnings column by 10000 but for 2006-2020 I want it to be the same as in the earnings column. I am a beginner, but what I was thinkin...
[ "Yoy should provide a minimum reproducible example. But assuming that you have the year in another column, the way to go could be\ndf['TrueEarn'] = np.where((df['YEAR'] >= 1991) & (df['YEAR'] <= 2005),\n df['Earnings'] / 10000, df['Earnings'])\n\nAs @wjandrea says, this can be done di...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074646960_pandas_python.txt
Q: How to count frequency of a value in a column of a data frame based on another column? I have dataframe with different traffic signs in different neighborhoods (both are columns). I want to count the quantity of each sign type in each neighborhood. i could create a query for each neighborhood and the count the val...
How to count frequency of a value in a column of a data frame based on another column?
I have dataframe with different traffic signs in different neighborhoods (both are columns). I want to count the quantity of each sign type in each neighborhood. i could create a query for each neighborhood and the count the value of each sign type like that but there are too many neighborhoods for that to be practical...
[ "You can group by the neighbourhood and sign type and do a size to have the count of each sign type in each neighbourhood.\nSample code\ndf.groupby([\"neighbourhood\", \"sign_type\"]).size()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074647020_dataframe_pandas_python.txt
Q: ArgumentError: FROM expression expected I have the following cell in jupyter notebook. What is in ***** is confidential information import psycopg2 import sqlalchemy as sa import pandas as pds from sqlalchemy import create_engine # Create an engine instance alchemyEngine = create_engine('***********************...
ArgumentError: FROM expression expected
I have the following cell in jupyter notebook. What is in ***** is confidential information import psycopg2 import sqlalchemy as sa import pandas as pds from sqlalchemy import create_engine # Create an engine instance alchemyEngine = create_engine('*****************************', pool_recycle=3600); # engine = creat...
[ "You still have some debugging work ahead of you.\nTake a look at the columns: team.c\n\nVerify spellings.\nPut each column (like \"hos_name\") on its own line, so it can easily be # commented out.\nSimplify the query. Start with an easy query of just a single column, and build up from there until you encounter bre...
[ 0, 0 ]
[]
[]
[ "jupyter", "python", "sqlalchemy" ]
stackoverflow_0074635284_jupyter_python_sqlalchemy.txt
Q: How to get max value and name from a Pandas series? Say I have a series like the one below: mySeries = pd.Series([1,2,3],['c','b','a']) How do I go about getting the max value along with the name associated with it in a single line? In this case: a: 3 I can get the max value with: mySeries.max(), the name of the...
How to get max value and name from a Pandas series?
Say I have a series like the one below: mySeries = pd.Series([1,2,3],['c','b','a']) How do I go about getting the max value along with the name associated with it in a single line? In this case: a: 3 I can get the max value with: mySeries.max(), the name of the max value with mySeries.idxmax(axis=1) but I can't figur...
[ "pd.Series.nlargest\nmySeries.nlargest(1)\n\na 3\ndtype: int64\n\n", "One with boolean indexing (just an alternative) i.e \nmySeries[mySeries.index==mySeries.idxmax()]\n\nor \nmySeries[mySeries == mySeries.max()]\n\nor(Thanks @piRSquared)\nmySeries[[mySeries.idxmax()]]\n\nOutput: \n\na 3\ndtype: int64\n\n" ...
[ 11, 1 ]
[ "You could do:\nfoo.value_counts()[:1].index.tolist()[0]}\n\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0046577525_pandas_python.txt
Q: PermissionError: [WinError 32] using pandas-dedupe I am trying to use pandas-dedupe, but after labelling data I run into permission issues I cannot solve. Minimum working example: import pandas_dedupe import seaborn as sns if __name__ == "__main__": iris = sns.load_dataset('iris') result = pandas_dedupe.d...
PermissionError: [WinError 32] using pandas-dedupe
I am trying to use pandas-dedupe, but after labelling data I run into permission issues I cannot solve. Minimum working example: import pandas_dedupe import seaborn as sns if __name__ == "__main__": iris = sns.load_dataset('iris') result = pandas_dedupe.dedupe_dataframe(iris, ["sepal_width", "sepal_length", "s...
[ "I had similar problems on Windows. I didn't find a solution for Windows itself, but using WSL(2) you can get this working properly.\nLyonk71 whom (co-)made the pandas-dedupe package also made an installation video, see below.\nhttps://www.youtube.com/watch?v=dq183fOB1Xg&t\nHope this helps you out, success!\n", "...
[ 0, 0 ]
[]
[]
[ "duplicates", "pandas", "permissionerror", "python", "windows" ]
stackoverflow_0074018382_duplicates_pandas_permissionerror_python_windows.txt
Q: python string formatting single quotes and double quotes I have a variable state = 'PA'. I am trying to generate a string as follows. I would like add single quotes on the state within a string. Also, I want to use this .format method because I will change this state later. 'select * from table where "state" = 'PA...
python string formatting single quotes and double quotes
I have a variable state = 'PA'. I am trying to generate a string as follows. I would like add single quotes on the state within a string. Also, I want to use this .format method because I will change this state later. 'select * from table where "state" = 'PA'' Currently, I could only be able to generate this 'select * ...
[ "You can escape the single quotes around the format specifier like this:\n>>> s = 'select * from table where \"state\" = \\'{}\\''.format(state)\n>>> print(s)\nselect * from table where \"state\" = 'PA'\n\n" ]
[ 0 ]
[]
[]
[ "formatting", "python", "single_quotes", "string" ]
stackoverflow_0074647076_formatting_python_single_quotes_string.txt
Q: Run aws Athena query by Lambda: error name 'response' is not defined I create an AWS lambda function with python 3.9 to run the Athena query and get the query result import time import boto3 # create Athena client client = boto3.client('athena') # create Athena query varuable query = 'select * from mydatabase....
Run aws Athena query by Lambda: error name 'response' is not defined
I create an AWS lambda function with python 3.9 to run the Athena query and get the query result import time import boto3 # create Athena client client = boto3.client('athena') # create Athena query varuable query = 'select * from mydatabase.mytable limit 8' DATABASE = 'mydatabase' output='s3://mybucket/' def lamb...
[ "You define the response variable inside the lambda_handler function. But you are referencing it in the global scope, outside of that function, here:\nquery_execution_id = response['QueryExecutionId']\n\nThe variable isn't defined on that scope, thus the error message. It appears that you may simply be missing inde...
[ 0 ]
[]
[]
[ "amazon_athena", "aws_lambda", "python" ]
stackoverflow_0074647062_amazon_athena_aws_lambda_python.txt
Q: How to round number to 3 decimals max? I am trying to round up 5.9999998 to 5.999. But I have a problem, If I do round(number) it'll round it up to 6. How can I round a number like this to max 3 decimals? A: You can use this: number = 5.999999998 new_number = int(number * 1e3) / 1e3 A: Here is a short code. x...
How to round number to 3 decimals max?
I am trying to round up 5.9999998 to 5.999. But I have a problem, If I do round(number) it'll round it up to 6. How can I round a number like this to max 3 decimals?
[ "You can use this:\nnumber = 5.999999998\nnew_number = int(number * 1e3) / 1e3\n\n", "Here is a short code.\n\nx = 4/3\n\n# round up to 3 decimal places\nx = round(x, 3)\n\nprint(x)\n\n\n" ]
[ 3, 0 ]
[]
[]
[ "numbers", "python" ]
stackoverflow_0074647047_numbers_python.txt
Q: How to edit and delete keys and values in python dict i have a little problem that needs solving, i have to write a program that saves contacts in a dict and be able to 1- add new contacts 2- delete contacts 3- edit contacts 4- list contacts 5- show contacts i wrote a simple program that saves contacts into a dict...
How to edit and delete keys and values in python dict
i have a little problem that needs solving, i have to write a program that saves contacts in a dict and be able to 1- add new contacts 2- delete contacts 3- edit contacts 4- list contacts 5- show contacts i wrote a simple program that saves contacts into a dictionary but i have a problem with the rest and i could reall...
[ "For your def's you dont need to use a for ... in range(...) loop, rather you can just call upon that value by the value of user_value. I've decided to not include def edit_contact(): in this as it currently doesn't edit anything, all it does is add a new element within contacts with that in mind\ncontacts = {\"Moh...
[ 0 ]
[]
[]
[ "dictionary", "for_loop", "list", "loops", "python" ]
stackoverflow_0074646847_dictionary_for_loop_list_loops_python.txt
Q: Conditional writes to DynamoDB when executing an AWS glue script without Boto? I've written an AWS glue job ETL script in python, and I'm looking for the proper way to perform conditional writes to the DynamoDb table I'm using as the target. # Write to DynamoDB glueContext.write_dynamic_frame_from_options(...
Conditional writes to DynamoDB when executing an AWS glue script without Boto?
I've written an AWS glue job ETL script in python, and I'm looking for the proper way to perform conditional writes to the DynamoDb table I'm using as the target. # Write to DynamoDB glueContext.write_dynamic_frame_from_options( frame=SelectFromCollection_node1665510217343, connection_type="dyna...
[ "You cannot do conditional updates with the EMR DynamoDB connector which Glue uses. It does a complete overwrite of the data. For that you would have to use Boto3 and distribute it using forEachPartition across the Spark executors.\n" ]
[ 0 ]
[]
[]
[ "amazon_dynamodb", "aws_glue", "python" ]
stackoverflow_0074646481_amazon_dynamodb_aws_glue_python.txt
Q: ValueError: Invalid element(s) received for the 'data' property I encounter an issue with plotly. I would like to display different figures but, somehow, I can't manage to achieve what I want. I created 2 sources of data: from plotly.graph_objs.scatter import Line import plotly.graph_objs as go trace11 = go.Scatt...
ValueError: Invalid element(s) received for the 'data' property
I encounter an issue with plotly. I would like to display different figures but, somehow, I can't manage to achieve what I want. I created 2 sources of data: from plotly.graph_objs.scatter import Line import plotly.graph_objs as go trace11 = go.Scatter( x = [0, 1, 2], y = [0, 0, 0], line = Line({'color': '...
[ "The reason why you are getting an error it is because the function append_trace() is expecting a single trace in the form you've declared them. However, the graph object Figure has the function add_traces() with which you can pass the data parameter as a list with more than one trace.\nTherefore, I suggest two sim...
[ 6, 0, 0, 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0060992109_plotly_python.txt
Q: How to rank the column values in pyspark dataframe according to conditions i have a dataframe: id vehicle asIs EU EU_variant 1 A3345 PQ1298 FV1 FV1_variant 2 A3346 PQ1287 FV2 FV2_variant 3 A3346 PQ1207 FV2 FV2_variant 4 A3347 QP9 QP9_variant 5 A3347 QP9 ...
How to rank the column values in pyspark dataframe according to conditions
i have a dataframe: id vehicle asIs EU EU_variant 1 A3345 PQ1298 FV1 FV1_variant 2 A3346 PQ1287 FV2 FV2_variant 3 A3346 PQ1207 FV2 FV2_variant 4 A3347 QP9 QP9_variant 5 A3347 QP9 QP9_variant 6 A3347 QP3 QP3_variant 7 A3348 MP6553 YR34 Y...
[ "You can use a Window with rank:\nfrom pyspark.sql import functions as F, Window\n\n# you can order by the column you prefer, not only id\nw = Window.partitionBy('vehicle', 'EU_variant').orderBy('id')\ndf.withColumn(\n 'ECU_Variant_rank', \n F.concat_ws('', F.col('EU_variant'), F.lit('('), F.rank().over(w), F...
[ 1 ]
[]
[]
[ "pyspark", "python", "python_3.x" ]
stackoverflow_0074646405_pyspark_python_python_3.x.txt
Q: How do I create and populate a gitignore file for a 15.5gb machine learning project? I'm working on an university project with ML, and the project got quite big, I usually don't use github but I need to format my pc and do not trust the Google Drive backup I have, therefore I wanna have a second one so I don't los...
How do I create and populate a gitignore file for a 15.5gb machine learning project?
I'm working on an university project with ML, and the project got quite big, I usually don't use github but I need to format my pc and do not trust the Google Drive backup I have, therefore I wanna have a second one so I don't lose the code whatsoever. I'm using Git with GitHub desktop, I'm not very knowledgeable in Gi...
[ "A .gitignore file will not help you there - you need to remove the dependencies from your project's history. There are two ways to do that:\nThe traditional way involves git-filter-branch. I've done that once in the past. It works, but it's easy to get wrong.\nThe alternative is to use BFG. I have no personal expe...
[ 0, 0 ]
[]
[]
[ "git", "github", "github_desktop", "pycharm", "python" ]
stackoverflow_0074647074_git_github_github_desktop_pycharm_python.txt
Q: Python scripts involving selenium behaving differently when called from task scheduler, but working as intended when run from spyder or command line I have created a python program which uses selenium and chromedriver. I cannot successfully run this script (or any others using selenium) from the TaskScheduler in ...
Python scripts involving selenium behaving differently when called from task scheduler, but working as intended when run from spyder or command line
I have created a python program which uses selenium and chromedriver. I cannot successfully run this script (or any others using selenium) from the TaskScheduler in any way. However, it runs perfectly fine and does all tasks I need when I run it from Spyder. It also runs perfectly while logged in when I call it via t...
[ "Currently dealing with the same issue, with my Python script doing almost exactly as yours does. My initial workaround for running the script on a set schedule was utilizing datetime variables and while True loops, then switched to apscheduler for convenience. Switching back to the workaround again ran the script ...
[ 0 ]
[]
[]
[ "python", "scheduled_tasks", "selenium", "selenium_chromedriver", "taskscheduler" ]
stackoverflow_0058754950_python_scheduled_tasks_selenium_selenium_chromedriver_taskscheduler.txt
Q: Wrapping a method from outside the class in Python with decorator I would like to ask a question, how I can override/extend the existing external python class. I wanted to be able to call the same API, like parent class, but with some modifications. Something like that: [a] b = 1 import configparser # my wrapper...
Wrapping a method from outside the class in Python with decorator
I would like to ask a question, how I can override/extend the existing external python class. I wanted to be able to call the same API, like parent class, but with some modifications. Something like that: [a] b = 1 import configparser # my wrapper class class MyConfigParser(configparser.ConfigParser): # override/...
[ "I think you are confused about what a decorator is and what the word wrapping typically refers to. Neither of those apply here, if I understood your intent correctly.\nOf course you can subclass some existing class that you may or may not have any control over and override its methods. And of course you can conven...
[ 1 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0074645630_configparser_python.txt
Q: How to add item last and remove first item in python dataframe? My dataframe is like this: data = { "a": [420, 380, 390], "b": [50, 40, 45] } df = pd.DataFrame(data) I want to add new item at the end of this dataframe, and remove the first item. I mean cont will be 3 each addition. New item add {"a": 300, b:...
How to add item last and remove first item in python dataframe?
My dataframe is like this: data = { "a": [420, 380, 390], "b": [50, 40, 45] } df = pd.DataFrame(data) I want to add new item at the end of this dataframe, and remove the first item. I mean cont will be 3 each addition. New item add {"a": 300, b: 88} and last stuation will be: data = { "a": [380, 390, 300], "...
[ "You can use pd.concat because append is getting deprecated. Ref\ndct = {\"a\": 300, \"b\": 88}\ndf_new = pd.concat([df, pd.Series(dct).to_frame().T]\n ).iloc[1:, :].reset_index(drop=True)\nprint(df_new)\n\n# If maybe the values of 'dict' have multiple items.\n# dct = {\"a\": [300, 400], \"b\": [88...
[ 1, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074647052_dataframe_pandas_python.txt
Q: Python-Jenkins tunnel connection failed: 403 Forbidden I have been using the Python Jenkins APIs to manager my Jenkins jobs. It has worked for a long time, but it stopped suddenly working. This is the code excerpt: import jenkins server = jenkins.Jenkins('https://jenkins.company.com', username='xxxx', password='p...
Python-Jenkins tunnel connection failed: 403 Forbidden
I have been using the Python Jenkins APIs to manager my Jenkins jobs. It has worked for a long time, but it stopped suddenly working. This is the code excerpt: import jenkins server = jenkins.Jenkins('https://jenkins.company.com', username='xxxx', password='password') server._session.verify = False print(server.jobs_c...
[ "tl;dr: You lack connectivity.\nThe jenkins library depends on import requests,\nwhich is reporting the connectivity error.\nRegrettably, it uses ProxyError in the diagnostic.\nThe rationale goes like this:\n\nWe're making a GET request for the application.\nOptionally the \"GET from server S\" will be turned into ...
[ 0, 0 ]
[]
[]
[ "api", "jenkins", "json", "python" ]
stackoverflow_0074647215_api_jenkins_json_python.txt
Q: Can I set a multiprocessing.pool as non-deamon? I have to do CPU-bound tasks, every task is assigened to a process with multiprocessing.Pool with multiprocessing.Pool(3) as p: results = list(p.map(task, [args1, args2, args3, aegs4, ..., argsn])) In every task there is a for loop, as the last one, that can be...
Can I set a multiprocessing.pool as non-deamon?
I have to do CPU-bound tasks, every task is assigened to a process with multiprocessing.Pool with multiprocessing.Pool(3) as p: results = list(p.map(task, [args1, args2, args3, aegs4, ..., argsn])) In every task there is a for loop, as the last one, that can be parallelized with multiprocessing.pool, but when i d...
[ "This is a bit too long to answer as a comment, and so ...\nIf what these tasks are doing is all or mostly all CPU-processing with very little waiting, then you should not be creating a processing pool greater than the number of CPU cores you have. See below for the general idea. Instead of using a multithreading p...
[ 0 ]
[]
[]
[ "for_loop", "multiprocessing", "parallel_processing", "pool", "python" ]
stackoverflow_0074641688_for_loop_multiprocessing_parallel_processing_pool_python.txt
Q: How to apply a function on combining two columns in pandas dataframe? I have two columns "ColA" and "ColB" in a pandas dataframe like below: I want apply a custom function on ColA and ColB, and update another column ColC. The custom function is like below: def customFunc(file_name, pattern): match_index = -1 ...
How to apply a function on combining two columns in pandas dataframe?
I have two columns "ColA" and "ColB" in a pandas dataframe like below: I want apply a custom function on ColA and ColB, and update another column ColC. The custom function is like below: def customFunc(file_name, pattern): match_index = -1 with open(file_name) as f: data = f.read() for n, line in e...
[ "using axis = 1 did the trick.\ndf[\"ColC\"] = df[[\"ColA\", \"ColB\"]].apply(lambda x: customFunc(x.ColA, x.ColB), axis = 1)\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074647326_pandas_python.txt
Q: Restore an image after rotation without black borders in python I've used the following code in order to rotate an image (initial image) and make some processing: def rotate_image(mat, angle): """ Rotates an image (angle in degrees) and expands image to avoid cropping """ height, width = mat.shape...
Restore an image after rotation without black borders in python
I've used the following code in order to rotate an image (initial image) and make some processing: def rotate_image(mat, angle): """ Rotates an image (angle in degrees) and expands image to avoid cropping """ height, width = mat.shape[:2] # image shape has 3 dimensions image_center = (width/2, heig...
[ "For rotating back, we may compute the inverse transformation, and apply it to the rotated image:\nExample:\ninv_rotation_mat = cv2.invertAffineTransform(rotation_mat) # Get inverse transformation matrix\nunrotated_mat = cv2.warpAffine(rotated_mat, inv_rotation_mat, (mat.shape[1], mat.shape[0])) # Apply warp (and...
[ 3 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074646959_image_processing_opencv_python.txt
Q: Unable to pull default text from input element with Selenium I'm trying to get the 11/30/2022 date from the SOA Handled Date/Time field from this site pictured here. It's not a public site, so I can't simply post the link. The text is in an input field that's filled in by default when you open the page, and it has...
Unable to pull default text from input element with Selenium
I'm trying to get the 11/30/2022 date from the SOA Handled Date/Time field from this site pictured here. It's not a public site, so I can't simply post the link. The text is in an input field that's filled in by default when you open the page, and it has the following HTML. <td> <input type="text" name="soa_h_d...
[ "Nevermind I figured it out. I had to use a javascript executor to pull the text with the following code.\nelement = driver.find_element_by_xpath('//input[@id=\"soa_h_date\"]')\ndate = driver.execute_script(\"return arguments[0].value\",element)\n\n" ]
[ 0 ]
[]
[]
[ "html", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074643472_html_python_selenium_selenium_webdriver.txt
Q: Is it possible to improve python performance for this code? I have a simple code that: Read a trajectory file that can be seen as a list of 2D arrays (list of positions in space) stored in Y I then want to compute for each pair (scipy.pdist style) the RMSD My code works fine: trajectory = read("test.lammpstrj", in...
Is it possible to improve python performance for this code?
I have a simple code that: Read a trajectory file that can be seen as a list of 2D arrays (list of positions in space) stored in Y I then want to compute for each pair (scipy.pdist style) the RMSD My code works fine: trajectory = read("test.lammpstrj", index="::") m = len(trajectory) #.get_positions() return a 2d numpy...
[ "You've mentioned that snapshot.get_positions() returns some 2D array, suppose of shape (p, q). So I expect that Y is a 3D array with some shape (m, p, q), where m is the number of snapshots in the trajectory. You also expect m to scale rather high.\nLet's see a basic way to speed up the distance calculation, on th...
[ 6, 4, 2, 1 ]
[]
[]
[ "julia", "numpy", "python" ]
stackoverflow_0074635970_julia_numpy_python.txt
Q: Split list from regex expression to regex expression I'm looking for a regex expression to split this list into x lists. where each list start with russian and ends with english. like this : [''Мальчик и девочка играют','A boy and a girl are playing','\xa0literal\xa0 Boy and girl [are] playing'] ['Мы стояли и ждал...
Split list from regex expression to regex expression
I'm looking for a regex expression to split this list into x lists. where each list start with russian and ends with english. like this : [''Мальчик и девочка играют','A boy and a girl are playing','\xa0literal\xa0 Boy and girl [are] playing'] ['Мы стояли и ждали','We were standing and waiting'] ['Слушали все: и мужчин...
[]
[]
[ "This creates a list of lists, grouping the phrases.\nfinal_list = []\nsublist = []\nfor phrase in starting_list:\n if re.match('^[а-яёА-ЯЁ]', phrase):\n final_list.append(sublist)\n sublist = [phrase]\n else:\n sublist += [phrase]\n\n" ]
[ -1 ]
[ "list", "python", "string" ]
stackoverflow_0074646958_list_python_string.txt
Q: Remove dictionary from list If I have a list of dictionaries, say: [{'id': 1, 'name': 'paul'}, {'id': 2, 'name': 'john'}] and I would like to remove the dictionary with id of 2 (or name 'john'), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry ...
Remove dictionary from list
If I have a list of dictionaries, say: [{'id': 1, 'name': 'paul'}, {'id': 2, 'name': 'john'}] and I would like to remove the dictionary with id of 2 (or name 'john'), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be...
[ "thelist[:] = [d for d in thelist if d.get('id') != 2]\n\nEdit: as some doubts have been expressed in a comment about the performance of this code (some based on misunderstanding Python's performance characteristics, some on assuming beyond the given specs that there is exactly one dict in the list with a value of ...
[ 143, 11, 8, 8, 2, 1, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0001235618_dictionary_list_python.txt
Q: Pandas Dataframe index & loc I am pretty new to Pandas , and working on an assignment to convert some pandas code to pyspark. Can someone pls explain me what is below code is actually doing. There is a Pandas Dataframe named DFF and it looks like below: DB SalesOrder SOItem SLNo 4500041 ...
Pandas Dataframe index & loc
I am pretty new to Pandas , and working on an assignment to convert some pandas code to pyspark. Can someone pls explain me what is below code is actually doing. There is a Pandas Dataframe named DFF and it looks like below: DB SalesOrder SOItem SLNo 4500041 10 1 PP 4501034 20 ...
[ "This is the below action that is being performed with the below code.\nSDD.loc[DFF.index, 'RDD'] = SDD.loc[DFF.index, 'DlvDate']\nBasically in this above line the following operations are being done.\nAll the index columns of DFF Dataframe and All the Index columns of SDD Dataframe are joined. A new column is crea...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074634149_pandas_python.txt
Q: Uwsgi Locking Up After a Few Requests with Nginx/Traefik/Flask App Running over HTTPS/TLS and Docker Problem I have an app that uses nginx to serve my Python Flask app in production that only after a few requests starts locking up and timing out (will serve the first request or two quickly then start timing out an...
Uwsgi Locking Up After a Few Requests with Nginx/Traefik/Flask App Running over HTTPS/TLS and Docker
Problem I have an app that uses nginx to serve my Python Flask app in production that only after a few requests starts locking up and timing out (will serve the first request or two quickly then start timing out and locking up afterwards). The Nginx app is served via Docker, the uwsgi Python app is served on barebones ...
[ "This is no longer a problem and the solution is real frustrating - it was Docker's fault. For ~6 months there was a bug in Docker that was dropping connections (ultimately leading to the timeouts mentioned above) which was finally fixed in Docker Desktop 4.14.\nThe moment I upgraded Docker (it had just come out at...
[ 4 ]
[]
[]
[ "docker", "nginx", "python", "traffic", "uwsgi" ]
stackoverflow_0073596677_docker_nginx_python_traffic_uwsgi.txt
Q: 'float' object is not subscriptable error while trying to add data into a csv file I have a csv file containing reviews. I want to calculate each review's sentiment polarity, and then output a new column that says if the review's sentiment is positive or negative The Whole thing looks like this filename = r'./Dis...
'float' object is not subscriptable error while trying to add data into a csv file
I have a csv file containing reviews. I want to calculate each review's sentiment polarity, and then output a new column that says if the review's sentiment is positive or negative The Whole thing looks like this filename = r'./DisneylandReviews.csv' df = pd.read_csv(filename, encoding='latin-1') df.columns=['ID','ra...
[ "To the function, review_to_sent(row) you are not passing the whole row, you are passing only the row values of a particular column called sentiment so\nMethod 1:\nChange calling methodology by doing apply on dataframe like\ndf.apply(Review_to_Sent(row))\n\nMethod 2:\nRemove row[‘sentiment’] from the check conditio...
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074647406_csv_pandas_python.txt
Q: if else statement to a comprehension list with enumeration? Using if-else statements in comprehension lists like this is great: a = [1, 0, 1, 0, 1, 0, 1, 0, 1] b = [i-1 if i > 0 else i+1 for i in a] b [0, 1, 0, 1, 0, 1, 0, 1, 0] also using the enumerations makes possible to use the iterator like: c = [j for j, ...
if else statement to a comprehension list with enumeration?
Using if-else statements in comprehension lists like this is great: a = [1, 0, 1, 0, 1, 0, 1, 0, 1] b = [i-1 if i > 0 else i+1 for i in a] b [0, 1, 0, 1, 0, 1, 0, 1, 0] also using the enumerations makes possible to use the iterator like: c = [j for j, item in enumerate(b) if item > 0 ] c [1, 3, 5, 7] but how to add...
[ "Just rearrange, such as\nc = [j if item>0 else 99 for j, item in enumerate(b)]\n\nproduces\n[99, 1, 99, 3, 99, 5, 99, 7, 99]\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074647365_python.txt
Q: passing multiple flags in argparse? I am trying to pass multiple different flags using argparse. I know this kind of code would work for a single flag. if the -percentage flag is passed then do something import argparse parser = argparse.ArgumentParser() parser.add_argument('-percentage', action='store_true') bu...
passing multiple flags in argparse?
I am trying to pass multiple different flags using argparse. I know this kind of code would work for a single flag. if the -percentage flag is passed then do something import argparse parser = argparse.ArgumentParser() parser.add_argument('-percentage', action='store_true') but I'm trying to pass multiple flags, for ...
[ "I was debugging it wrong. I spent last 5 hours trying to figure this out. Thanks to everyone who mentioned the comment!\nfor anyone experiencing the same issue, when you are debugging using a launch.json file. make sure your args are like this \"args\": [\n\"--serviceA\", \"--activate\"\n],\nI had set up args like...
[ 0 ]
[]
[]
[ "argparse", "arguments", "command_line", "command_line_arguments", "python" ]
stackoverflow_0074647313_argparse_arguments_command_line_command_line_arguments_python.txt
Q: How to do multi-line string search in a file and get start line, end line info in python? I want to search for multi-line string in a file in python. If there is a match, then I want to get the start line number, end line number, start column and end column number of the match. For example: in the below file, I w...
How to do multi-line string search in a file and get start line, end line info in python?
I want to search for multi-line string in a file in python. If there is a match, then I want to get the start line number, end line number, start column and end column number of the match. For example: in the below file, I want to match the below multi-line string: pattern = """b'0100000001685c7c35aabe690cc99f947a8172...
[ "You should use the re.MULTILINE flag to search multiple lines\nimport re\npattern = r\"(c\\nd)\"\nstring = \"\"\"\na\nb\nc\nd\ne\nf\n\"\"\"\n\nmatch = re.search(pattern, string, flags=re.MULTILINE)\nprint(match)\n\nTo get the start line, you could count the newline characters as follows\nstart, stop = match.span()...
[ 0 ]
[]
[]
[ "match", "python", "python_re" ]
stackoverflow_0074636125_match_python_python_re.txt
Q: How to combine two JSON objects using jq I have two files: kube-apiserver.json { "apiVersion": "v1", "kind": "Pod", "metadata": { [...] }, "spec": { "containers": [ { "command": [ "kube-apiserver", "--advertise-...
How to combine two JSON objects using jq
I have two files: kube-apiserver.json { "apiVersion": "v1", "kind": "Pod", "metadata": { [...] }, "spec": { "containers": [ { "command": [ "kube-apiserver", "--advertise-address=192.168.49.2", "--...
[ "jq --slurpfile patch patch.json '\n (.spec.containers |= map(.command |= (. + $patch[].spec.containers[0].command | unique) |\n .volumeMounts |= (. + $patch[].spec.containers[0].volumeMounts | unique))) |\n (.spec.volumes |= (. + $patch[].spec.volumes | unique))\n' kube-api...
[ 0 ]
[]
[]
[ "jq", "json", "python", "text_processing" ]
stackoverflow_0074646311_jq_json_python_text_processing.txt
Q: How to override a mock for an individual test within a class that already has a mock I have a test class that has a mock decorator, and several tests. Each test receives the mock, because mock is defined on the class level. Great. Here's what it looks like: @mock.patch("foo", bar) class TestMyThing(TestCase): de...
How to override a mock for an individual test within a class that already has a mock
I have a test class that has a mock decorator, and several tests. Each test receives the mock, because mock is defined on the class level. Great. Here's what it looks like: @mock.patch("foo", bar) class TestMyThing(TestCase): def test_A(self): assert something def test_B(self): assert something def test...
[ "Yes! You can leverage the setUp/tearDown methods of the unittest.TestCase and the fact that unittest.mock.patch in its \"pure\" form (i.e. not as context manager or decorator) returns a \"patcher\" object that has start/stop methods to control when exactly it should do its magic.\nYou can call on the patcher to st...
[ 1 ]
[]
[]
[ "python", "python_unittest", "unit_testing" ]
stackoverflow_0074641489_python_python_unittest_unit_testing.txt
Q: javascript for-loop not iterating within python loop I have a list of dates in python that I would like to iterate through to create button elements. df2 = ['Sat Nov 12 11:57:21 CST 2022', 'Wed Nov 23 18:13:31 CST 2022', 'Wed Nov 23 18:13:32 CST 2022', 'Thu Nov 10 19:07:50 CST 2022', 'Fri Nov 11 09:54:54 CST 2...
javascript for-loop not iterating within python loop
I have a list of dates in python that I would like to iterate through to create button elements. df2 = ['Sat Nov 12 11:57:21 CST 2022', 'Wed Nov 23 18:13:31 CST 2022', 'Wed Nov 23 18:13:32 CST 2022', 'Thu Nov 10 19:07:50 CST 2022', 'Fri Nov 11 09:54:54 CST 2022', 'Fri Nov 11 10:18:36 CST 2022', 'Sat Nov 26 10:50:...
[ "If you're dfoing the looping in Python, as you are doing here, then you don't need to do any looping in Javascript. The HTML you create will already have all of the data enumerated:\ndf2 = ['Sat Nov 12 11:57:21 CST 2022',\n 'Wed Nov 23 18:13:31 CST 2022',\n 'Wed Nov 23 18:13:32 CST 2022',\n 'Thu Nov 10 19:07:50 C...
[ 2 ]
[]
[]
[ "html", "javascript", "loops", "python" ]
stackoverflow_0074647592_html_javascript_loops_python.txt
Q: I am lost on what i am doing wrong I am trying to call the class AQIparameters to present to the user the variables stored in the function aqi_parameters but it is only displaying me the strings in aqiparameters I have tried calling the aqiparameters class in the function but it results in an location error or som...
I am lost on what i am doing wrong
I am trying to call the class AQIparameters to present to the user the variables stored in the function aqi_parameters but it is only displaying me the strings in aqiparameters I have tried calling the aqiparameters class in the function but it results in an location error or some other form of error The form.py where ...
[ "It looks like the issue you are experiencing is that when you try to access the values of the aqi_parameter dictionary in your template, you are using the string names of the dictionary keys instead of the keys themselves.\nFor example, in your template, you are trying to access the coordinates value by using aqi_...
[ 0 ]
[]
[]
[ "api", "class", "function", "python" ]
stackoverflow_0074647548_api_class_function_python.txt
Q: Python Pandas: Execute comparison between columns in two DataFrames if values in their rows are equal I have df1 and df2. Each dataframe contains an ID column. Each dataframe also contains a geometry column. I would like to calculate the distance between each dataframe's geometry column only for rows where ID's ma...
Python Pandas: Execute comparison between columns in two DataFrames if values in their rows are equal
I have df1 and df2. Each dataframe contains an ID column. Each dataframe also contains a geometry column. I would like to calculate the distance between each dataframe's geometry column only for rows where ID's match in each dataframe. I would imagine it looks something like this but can't figure it out: for geom in df...
[ "There's the function .equals()\ndf1['system_id'].equals(df2f['systemID'])\n\nwhich will return a boolean\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074647675_dataframe_pandas_python.txt
Q: How should I handle timestamps in Python? Whenever I read floats from sqlite using pandas.read_sql_query, there's a chance it'll have a slight precision error. So when I search for that row later by using that unprecise float, it can't find that row. Here's the exact process I used to recreate the problem: Create...
How should I handle timestamps in Python?
Whenever I read floats from sqlite using pandas.read_sql_query, there's a chance it'll have a slight precision error. So when I search for that row later by using that unprecise float, it can't find that row. Here's the exact process I used to recreate the problem: Create row in sqlite database test table insert into...
[ "Don't use floats if you can avoid it, this is just how they work:\n>>> print (\"%40.18f\\n\" % (1669836415.8800698))\n **1669836415.880069732666015625 <<<< the actual value**\n\n>>> print (\"%40.7f\\n\" % (1669836415.8800698))\n **1669836415.8800697 <<<< the rounded value**\n\n" ]
[ 0 ]
[]
[]
[ "floating_point", "precision", "python" ]
stackoverflow_0074634839_floating_point_precision_python.txt
Q: Python symlink to python3 So I'm setting up my default variables in a new MacBook M1 and for some reason, my symlink doesn't seem to work. Why is the following behaviour happening? The symlink from python to python3 gets lost somehow. /Users/overflow/Documents/tools is part of my PATH variable. $ type python pytho...
Python symlink to python3
So I'm setting up my default variables in a new MacBook M1 and for some reason, my symlink doesn't seem to work. Why is the following behaviour happening? The symlink from python to python3 gets lost somehow. /Users/overflow/Documents/tools is part of my PATH variable. $ type python python is /Users/overflow/Documents/...
[ "Given the path is not being utilized, it is being overridden by a shell alias. This can be confirmed by typing set | grep python\nIf you are using virtualenv:\nTry: /usr/bin/python3 -m venv python3.8.9\nThe common MacOS python managers are:\n\npythonz\n\nList installs using pythonz list\nChange using: /usr/bin/pyt...
[ 4, 3, 0 ]
[]
[]
[ "apple_m1", "python", "symlink", "unix" ]
stackoverflow_0069470556_apple_m1_python_symlink_unix.txt
Q: Use Python to remove unneeded elements from XML file I'm writing a program in Python to use an API that doesn't seem to filter out requests based on if a user is considered active. When I ask the API for a list of active users I get a much longer XML document that looks like the below text and it still includes us...
Use Python to remove unneeded elements from XML file
I'm writing a program in Python to use an API that doesn't seem to filter out requests based on if a user is considered active. When I ask the API for a list of active users I get a much longer XML document that looks like the below text and it still includes users where the <active> tag is false. <ArrayOfuser xmlns="W...
[ "Since you're dealing with xml, you should use a proper xml parser. Note that in this case you have to deal with namespaces as well.\nSo try this:\nfrom lxml import etree\n#load your file\ndoc = etree.parse(\"users.xml\")\n#declare namespaces\nns = {'xx': 'WebsiteWhereDataComesFrom.com'}\n\n#locate your deletion ta...
[ 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0074646352_python_xml.txt
Q: Create a Category Tree using python A category tree is a representation of a set of categories and their parent-child relationships. Each category has a unique name (no two categories have the same name). A category can have a parent category. Categories without a parent category are called root categories. Need t...
Create a Category Tree using python
A category tree is a representation of a set of categories and their parent-child relationships. Each category has a unique name (no two categories have the same name). A category can have a parent category. Categories without a parent category are called root categories. Need to create a category tree with following d...
[ "To create a category tree in Python, you can define a CategoryTree class that has the following methods:\n\nadd_category(name: str, parent: Optional[str]): This method should add a new category with the given name and parent to the category tree. If a null value is provided as the parent, the category should be ad...
[ 0 ]
[]
[]
[ "exception", "python", "tree" ]
stackoverflow_0074647726_exception_python_tree.txt
Q: python: [Errno 10054] An existing connection was forcibly closed by the remote host I am writing python to crawl Twitter space using Twitter-py. I have set the crawler to sleep for a while (2 seconds) between each request to api.twitter.com. However, after some times of running (around 1), when the Twitter's rate ...
python: [Errno 10054] An existing connection was forcibly closed by the remote host
I am writing python to crawl Twitter space using Twitter-py. I have set the crawler to sleep for a while (2 seconds) between each request to api.twitter.com. However, after some times of running (around 1), when the Twitter's rate limit not exceeded yet, I got this error. [Errno 10054] An existing connection was forcib...
[ "This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection. ...
[ 24, 15, 13, 2, 2, 0 ]
[]
[]
[ "python", "twitter", "web_crawler" ]
stackoverflow_0008814802_python_twitter_web_crawler.txt
Q: uncheck checkbox tkinter after a certain time interval my program is based on independent checkboxes, that is, they do not depend on a booleanVar, I am using a setInterval created from a thread , and after a certain time I want the checkbox to 'turn off' and be able to receive another setInterval self.timer = Chec...
uncheck checkbox tkinter after a certain time interval
my program is based on independent checkboxes, that is, they do not depend on a booleanVar, I am using a setInterval created from a thread , and after a certain time I want the checkbox to 'turn off' and be able to receive another setInterval self.timer = Checkbutton(command=session_timer ,text='Session Timer') self.ti...
[ "The checkbutton has a documented method named deselect which does what the name implies.\nif timer >= timer_interval_minutes:\n self.timer.deselect()\n\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074647867_python_tkinter.txt
Q: async apscheduler does not start the task Trying to create a scheduler: sheduler = AsyncIOScheduler(timezone='Europe/Moscow') async def thread_maintaining_communication(): print('There') async def main(): sheduler.add_job(thread_maintaining_communication,"interval", seconds=20) sheduler.start() #...
async apscheduler does not start the task
Trying to create a scheduler: sheduler = AsyncIOScheduler(timezone='Europe/Moscow') async def thread_maintaining_communication(): print('There') async def main(): sheduler.add_job(thread_maintaining_communication,"interval", seconds=20) sheduler.start() #await bot.infinity_polling(skip_pending=True) ...
[ "I was given an answer, I hope that someone who faces the same problem will find this topic\nsheduler.add_job(thread_maintaining_communication,\"interval\", seconds=20)\nbot.add_custom_filter(asyncio_filters.StateFilter(bot))\nsheduler.start()\nloop = asyncio.get_event_loop() \nloop.run_until_complete(bot.polling(s...
[ 0 ]
[]
[]
[ "apscheduler", "asynchronous", "python" ]
stackoverflow_0074641830_apscheduler_asynchronous_python.txt
Q: how can I create a new column with two columns combination? i want a new column that contains the amount of times user_id and artist_id are the same, for example if user_id = 0, and artist_id = 10, and it happens 5 times, i want to store number 5 in a column in the 5 rows in which this occurs. This code gives me t...
how can I create a new column with two columns combination?
i want a new column that contains the amount of times user_id and artist_id are the same, for example if user_id = 0, and artist_id = 10, and it happens 5 times, i want to store number 5 in a column in the 5 rows in which this occurs. This code gives me the value, but I can't store it. treino.groupby(['user_id', 'artis...
[ "IIUC you need a column that represents the size of each group in each row. Then you need to use groupby.transform.\ndf[\"group_size\"] = (\n df.assign(group_size=1)\n .groupby([\"user_id\", \"artist_id\"])[\"group_size\"]\n .transform(\"count\")\n)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074646247_dataframe_pandas_python.txt
Q: Python CLI and Import Module I'm trying to figure out how to set up a python "project" as both a CLI command and an import "object". This probably has a simple answer(s), but I'm not as familiar with the technical terms so I'm not quite sure what I need to research. What I would like to have: mytool being a python...
Python CLI and Import Module
I'm trying to figure out how to set up a python "project" as both a CLI command and an import "object". This probably has a simple answer(s), but I'm not as familiar with the technical terms so I'm not quite sure what I need to research. What I would like to have: mytool being a python "thing" (module/package?) I can r...
[ "Finally found a question that lead me to a solution, but I still welcome feedback and comments!\nThis question:\nhttps://softwareengineering.stackexchange.com/q/243044\n(they asked which is preferred)\nasks about single python file distribution where you have a file foo.py which has an internal thing (function,cla...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_import" ]
stackoverflow_0074647151_python_python_3.x_python_import.txt
Q: Center the flower using turtle I want to draw a flower with turtle. Although I am facing problem in centering the flower (0,0) should be flower's center or where turtle initially is spawned. How can I center it? import turtle import math turtle.speed(-1) def Flower(): global radius, num_of for i in range(...
Center the flower using turtle
I want to draw a flower with turtle. Although I am facing problem in centering the flower (0,0) should be flower's center or where turtle initially is spawned. How can I center it? import turtle import math turtle.speed(-1) def Flower(): global radius, num_of for i in range(num_of): turtle.setheading(i...
[ "Since the turtle draws from a edge, we need to move the turtle to compensate for the radius of the entire image. To simplify this move, we align the starting point of the image with one (X) axis. We also switch from absolute coordinates (setheading()) to relative coordinates (right()) so our initial rotational o...
[ 1 ]
[]
[]
[ "flower", "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074625622_flower_python_python_turtle_turtle_graphics.txt
Q: AWS SAM DockerBuildArgs It does not add them when creating the lambda image I am trying to test a lambda function locally, the function is created from the public docker image from aws, however I want to install my own python library from my github, according to the documentation AWS sam Build I have to add a vari...
AWS SAM DockerBuildArgs It does not add them when creating the lambda image
I am trying to test a lambda function locally, the function is created from the public docker image from aws, however I want to install my own python library from my github, according to the documentation AWS sam Build I have to add a variable to be taken in the Dockerfile like this: Dockerfile FROM public.ecr.aws/la...
[ "I am having this issue too. What I have learned is that in the Metadata field there is DockerBuildArgs: that you can also add. Example:\n Metadata:\n DockerBuildArgs:\n MY_VAR: <some variable>\n\nWhen I add this it does make it to the DockerBuildArgs dict.\n" ]
[ 1 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "aws_sam_cli", "docker", "python" ]
stackoverflow_0073507177_amazon_web_services_aws_lambda_aws_sam_cli_docker_python.txt
Q: Is there any option to reset label after printing it ? [Python, Tkinter] this is my code from tkinter import * root = Tk() root.title("MyTitle") root.iconbitmap("icon.ico") root.geometry("800x800") c = [] feature1 = IntVar() feature1.set(0) feature2 = IntVar() feature2.set(0) feature3 = IntVar() feature3.set(0) C...
Is there any option to reset label after printing it ? [Python, Tkinter]
this is my code from tkinter import * root = Tk() root.title("MyTitle") root.iconbitmap("icon.ico") root.geometry("800x800") c = [] feature1 = IntVar() feature1.set(0) feature2 = IntVar() feature2.set(0) feature3 = IntVar() feature3.set(0) Checkbutton(root, text="Pizza", variable=feature1).pack() Checkbutton(root, tex...
[ "c should not be a global. You need to rebuild it from scratch every time the button is clicked. adej also does not need to be a global.\nThis works. Also, delete the global definitions of c and adej.\ndef receipt():\n c = []\n if feature1.get() == 1:\n c.append(\"Pizza\")\n if feature2.get() == ...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074647460_python_tkinter.txt
Q: Odoo Smartbutton access rights for different model I have added smartbutton in res.partner form view header that opens the current partner helpdesk tickets (helpdesk.ticket model). Smartbutton view (If i remove this code then button is removed and users can freely open partner form view) <odoo> <data> ...
Odoo Smartbutton access rights for different model
I have added smartbutton in res.partner form view header that opens the current partner helpdesk tickets (helpdesk.ticket model). Smartbutton view (If i remove this code then button is removed and users can freely open partner form view) <odoo> <data> <record id="helpdesk_ticket_smart_button" model="ir.ui....
[ "You can set a group on your extension view:\n<field name=\"groups_id\" eval=\"[(4,ref('helpdesk.group_helpdesk_user'))]\"/>\nWill look like this:\n<odoo>\n <data>\n <record id=\"helpdesk_ticket_smart_button\" model=\"ir.ui.view\">\n <field name=\"name\">partner.helpdesk.ticket.smart.buttons</f...
[ 1, 1 ]
[]
[]
[ "access_rights", "odoo", "odoo_14", "python" ]
stackoverflow_0074643745_access_rights_odoo_odoo_14_python.txt
Q: Python - Passing a function with multiple arguments into another function I have this method that I want to pass into another function. def get_service_enums(context, enum): svc = Service(context) return svc.get_enum(enum) I want to pass this function is as a parameter to another class. ColumnDef(enum_value...
Python - Passing a function with multiple arguments into another function
I have this method that I want to pass into another function. def get_service_enums(context, enum): svc = Service(context) return svc.get_enum(enum) I want to pass this function is as a parameter to another class. ColumnDef(enum_values=my_func) Ideally, my_func is get_service_enums. However get_service_enums ha...
[ "using partial from functools to create a new function that only takes the first argument.\nfrom functools import partial\n\ndef get_service_enums(context, enum):\n print(context, enum)\n\npartial_function = partial(get_service_enums, enum=\"second_thing\")\npartial_function(\"first_thing\")\n\nfirst_thing secon...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074648077_python_python_3.x.txt
Q: Cannot Keep My Datetime Data and 'No' Word in My Pandas DataFrame I have a pandas dataframe from csv and I want to clean it using Regex in Python. The data that I have look like this: Name Date Status Number A/bCDef 2022-07-11 Yes io123-07 GhIjK-l 2022-07-12 No io456-08 I'm trying to clean the dataframe so it ...
Cannot Keep My Datetime Data and 'No' Word in My Pandas DataFrame
I have a pandas dataframe from csv and I want to clean it using Regex in Python. The data that I have look like this: Name Date Status Number A/bCDef 2022-07-11 Yes io123-07 GhIjK-l 2022-07-12 No io456-08 I'm trying to clean the dataframe so it will be easier to process, but the thing is, my code deletes ...
[ "can you try this:\ndf = df.applymap(lambda s: s.lower() if type(s) == str else s) #lower string values\ndf.columns = df.columns.str.lower() #lower for columns\ndf['name']=df['name'].str.replace(r'\\W+', '') #remove any non-word character\n\n#output\n'''\n name date status number\n0 abcdef 2022-07-1...
[ 0 ]
[]
[]
[ "datetime", "nlp", "python", "python_regex" ]
stackoverflow_0074636944_datetime_nlp_python_python_regex.txt
Q: How to sum duplicate columns in dataframe and return nan if at least one value is nan I have a dataframe with duplicate columns (number not known a priori) like this example: a a a b b 0 1 1 1 1 1 1 1 nan 1 1 1 I need to be able to aggregate the columns by summing their values (by rows) and returning NaN if at...
How to sum duplicate columns in dataframe and return nan if at least one value is nan
I have a dataframe with duplicate columns (number not known a priori) like this example: a a a b b 0 1 1 1 1 1 1 1 nan 1 1 1 I need to be able to aggregate the columns by summing their values (by rows) and returning NaN if at least one value, in one of the columns among the duplicates, is NaN. I have tri...
[ "One workaround might be to use apply to get the DataFrame.sum:\ndf.groupby(level=0, axis=1).apply(lambda x: x.sum(axis=1, skipna=False))\n\nOutput:\n a b\n0 3.0 2.0\n1 NaN 2.0\n\n", "Another possible solution:\ncols, ldf = df.columns.unique(), len(df)\n\npd.DataFrame(\n np.reshape([sum(df.loc[i, x]...
[ 2, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074646196_dataframe_numpy_pandas_python.txt
Q: Will converting to PySDL2 make my app run faster than it does under PyGame? I've written a little toy in Python using Pygame. It generates critters (a circle with a directional line, not an image) to wander around the screen. I'm interested in making it more sophisticated, but I'm running into serious performance ...
Will converting to PySDL2 make my app run faster than it does under PyGame?
I've written a little toy in Python using Pygame. It generates critters (a circle with a directional line, not an image) to wander around the screen. I'm interested in making it more sophisticated, but I'm running into serious performance problems. As the number of critters on the screen passes 20, the frame rate drops...
[ "Do not create the font object in each frame. Creating a font object is a very expensive operation because the font must be read from the resource and decoded. Create the font before the application loop, but use it in the application loop:\nmyfont = pygame.font.SysFont(\"monospace\", 15) # <-- INSE...
[ 0 ]
[]
[]
[ "pygame", "pysdl2", "python" ]
stackoverflow_0043614091_pygame_pysdl2_python.txt
Q: How to accept all data from connection in socketserver python? How to receive all data from a connection in socketserver so that it the connection does not hang on the client side class ConnectionHandler(BaseRequestHandler): def handle(self): data = b'' while 1: tmp = self.request....
How to accept all data from connection in socketserver python?
How to receive all data from a connection in socketserver so that it the connection does not hang on the client side class ConnectionHandler(BaseRequestHandler): def handle(self): data = b'' while 1: tmp = self.request.recv(1024) if not tmp: break ...
[ "In order to receive all data from a connection in socketserver, you can use the makefile method of the socket object. This method returns a file-like object that can be used to read data from the connection. Here is an example of how you could use this method to receive all data from the connection:\nclass Connect...
[ 2, 0 ]
[]
[]
[ "python", "recv", "socketserver", "tcp" ]
stackoverflow_0074647416_python_recv_socketserver_tcp.txt
Q: MetPy geostrophic wind for WRF data Edit: I'm starting to suspect the problems arising below are due to the metadata, because even after correcting the issues raised regarding units mpcalc.geostrophic_wind(z) still issues warnings about the coordinates and ordering. Maybe the function is unable to identify the coo...
MetPy geostrophic wind for WRF data
Edit: I'm starting to suspect the problems arising below are due to the metadata, because even after correcting the issues raised regarding units mpcalc.geostrophic_wind(z) still issues warnings about the coordinates and ordering. Maybe the function is unable to identify the coordinates from the file? Perhaps this is b...
[ "wrfpython's getvar function, while it takes units as a parameter, only uses this (as far as I can tell) to convert values in the arrays before returning them. To use this with MetPy you need to attach proper units. I would do this using a small helper function:\nfrom metpy.units import units\n\ndef metpy_getvar(fi...
[ 2, 0, 0 ]
[]
[]
[ "metpy", "python", "python_xarray" ]
stackoverflow_0074615766_metpy_python_python_xarray.txt
Q: assignment to variable using exponents showing answer which is confusing a = 1 b = 0 a = a ^ b b = a ^ b a a = a ^ b print(a, b) Can someone shed some light on this? I see the answer is (0, 1) but why? first line would make a = 1 making it (1,0), second line would make it (1,1) so Im thinking the third line woul...
assignment to variable using exponents showing answer which is confusing
a = 1 b = 0 a = a ^ b b = a ^ b a a = a ^ b print(a, b) Can someone shed some light on this? I see the answer is (0, 1) but why? first line would make a = 1 making it (1,0), second line would make it (1,1) so Im thinking the third line would make it 1 ^ 1 which = 1, but its showing (0, 1). what am I not understanding...
[ "In python, the exponent operator is not ^ but **. The ^ operator is actually the bitwise XOR operator.\n" ]
[ 0 ]
[]
[]
[ "exponent", "python", "variable_assignment" ]
stackoverflow_0074648216_exponent_python_variable_assignment.txt
Q: Python Error ModuleNotFoundError: No module named 'transformers' I'm getting below error when running 'import transformers', even though I have installed in the same vitual env. I'm using python 3.8 ModuleNotFoundError: No module named 'transformers' Error: enter image description here I have uninstalled it and r...
Python Error ModuleNotFoundError: No module named 'transformers'
I'm getting below error when running 'import transformers', even though I have installed in the same vitual env. I'm using python 3.8 ModuleNotFoundError: No module named 'transformers' Error: enter image description here I have uninstalled it and reinstalled it using 'pip3 install transformers' from python cmd line....
[ "its resolved now. I just tried to use %pip install transformers==3.4.0, instead of !pip install transformers==3.4.0 in jupyter book, and it worked. I can proceed with the project for now. Although I don't know what I did wrong in my python command line earlier that caused the inconsistency. Will open a new thread....
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074607244_jupyter_notebook_python.txt
Q: Python Discord bot not responding in servers I have run into a very strange problem and I would appreciate any help that comes my way So I made a discord bot using discord.py library and hosted it on Heroku. It was working perfectly well. Until recently had to take it down for some development. Now when I uploaded...
Python Discord bot not responding in servers
I have run into a very strange problem and I would appreciate any help that comes my way So I made a discord bot using discord.py library and hosted it on Heroku. It was working perfectly well. Until recently had to take it down for some development. Now when I uploaded it again it does not work. Here is a summary of w...
[ "You need to enable message Intents in the Discord site, then specify the messages intent in the code. That should work for you.\n" ]
[ 0 ]
[]
[]
[ "asynchronous", "discord.py", "heroku", "python" ]
stackoverflow_0071721558_asynchronous_discord.py_heroku_python.txt
Q: How can I extract a set of 2D slices from a larger 2D numpy array? If I have a large 2D numpy array and 2 arrays which correspond to the x and y indices I want to extract, It's easy enough: h = np.arange(49).reshape(7,7) # h = [[0, 1, 2, 3, 4, 5, 6], # [7, 8, 9, 10, 11, 12, 13], # [14, 15, 16, 17, 18, 19...
How can I extract a set of 2D slices from a larger 2D numpy array?
If I have a large 2D numpy array and 2 arrays which correspond to the x and y indices I want to extract, It's easy enough: h = np.arange(49).reshape(7,7) # h = [[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, ...
[ "You can index np.lib.stride_tricks.sliding_window_view using your x and y indices:\nimport numpy as np\n\nh = np.arange(49).reshape(7,7)\n\nx_indices = np.array([1,3,4])\ny_indices = np.array([2,3,5])\n\na = 1\nwindow = (2*a+1, 2*a+1)\n\nout = np.lib.stride_tricks.sliding_window_view(h, window)[x_indices-a, y_indi...
[ 4 ]
[]
[]
[ "array_broadcasting", "numpy", "numpy_slicing", "python" ]
stackoverflow_0074646902_array_broadcasting_numpy_numpy_slicing_python.txt
Q: Subseting python dataframe using position values from lists I have a dataframe with raw data and I would like to select different range of rows for each column, using two different lists: one containing the first row position to select and the other the last. INPUT | Index | Column A | Column B | |:--------:|:...
Subseting python dataframe using position values from lists
I have a dataframe with raw data and I would like to select different range of rows for each column, using two different lists: one containing the first row position to select and the other the last. INPUT | Index | Column A | Column B | |:--------:|:--------:|:--------:| | 1 | 2 | 8 | | 2...
[ "Basically, as far as I can see, you have two meaningful columns in your DataFrame.\nThus, I would suggest using \"Index\" column as the index indeed:\ndf.set_index(df.columns[0], inplace=True)\n\nThat way you might use .loc:\ndf_out = pd.concat(\n [\n df.loc[first_position, \"Column A\"].reset_index(drop...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "subset" ]
stackoverflow_0074647945_dataframe_pandas_python_subset.txt
Q: Python: Unable to call function within a seperate function? (undefined name 'getItemClassiness') For some reason the getClassiness Function does not work as it is not able to call the helper function getItemClassiness. Is there any reason this might be? Thanks! class Classy(object): def __init__(self): ...
Python: Unable to call function within a seperate function? (undefined name 'getItemClassiness')
For some reason the getClassiness Function does not work as it is not able to call the helper function getItemClassiness. Is there any reason this might be? Thanks! class Classy(object): def __init__(self): self.items = [] def addItem(self, item): self.items.append(item) def ge...
[ "In line 21 call for a class method is made without using the self keyword.\n x = self.getItemClassiness(item)\n\nSimilarly on line 8 in self keyword is required with as parameter for function definition of getItemClassiness\ndef getItemClassiness(self, item):\n\n", "You should declare getItemClassiness as a stat...
[ 0, 0, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0072455810_function_python.txt
Q: If a logging warning occurs before __main__, how is it being called? I'm working on a corporate python program which uses buck build. When I run part of the program, abc.py (via a .par file), then it runs the program starting with if __name__ == "__main__" etc. However, I'm trying to find source of logging warning...
If a logging warning occurs before __main__, how is it being called?
I'm working on a corporate python program which uses buck build. When I run part of the program, abc.py (via a .par file), then it runs the program starting with if __name__ == "__main__" etc. However, I'm trying to find source of logging warnings that occur before any of the contents of the if __name__ ... are run. Or...
[ "Your mistake is thinking execution starts with if __name__ == \"__main__\":. That check is a guard that prevents the guarded code from executing when imported as a module, rather than run as the main script. The unguarded code always runs, regardless of how the module is loaded, so if the guard is at the bottom of...
[ 1 ]
[]
[]
[ "buck", "python" ]
stackoverflow_0074648292_buck_python.txt
Q: Convert Pandas DataFrame WITHOUT connecting to a SQL database All solutions I have seen require connecting to a SQL database, which IS NOT the goal of this question. The Goal Is To Convert A DataFrame To A String Capturing How To Re-Create The DataFrame That I Can Save As A Valid .sql File Let's say I have a simpl...
Convert Pandas DataFrame WITHOUT connecting to a SQL database
All solutions I have seen require connecting to a SQL database, which IS NOT the goal of this question. The Goal Is To Convert A DataFrame To A String Capturing How To Re-Create The DataFrame That I Can Save As A Valid .sql File Let's say I have a simple pandas DataFrame: df = pd.DataFrame({{'hello'}:[1], {'world}:[2]}...
[ "you need to map all the datatypes correctly, i only used a sample to show you how top start.\nBut to be correct you need to rebuild all https://www.postgresql.org/docs/current/sql-createtable.html if you want to have all options\nSo i repeat my comment, best is to backup your database on database server with a bac...
[ 0 ]
[]
[]
[ "pandas", "postgresql", "python", "sql" ]
stackoverflow_0074645609_pandas_postgresql_python_sql.txt
Q: Generic is an abstract class in python? I'm trying to create a base class that works for any CRUD in applications and I've seen the following implementation: ModelType = TypeVar("ModelType", bound=Base) CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) UpdateSchemaType = TypeVar("UpdateSchemaType", b...
Generic is an abstract class in python?
I'm trying to create a base class that works for any CRUD in applications and I've seen the following implementation: ModelType = TypeVar("ModelType", bound=Base) CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) class CRUDBase(Generic[Model...
[ "If your question is about the purpose of typing.Generic I would suggest you read through PEP 484. It has a section dedicated to user defined generic classes with some examples specifically for this, but the entire document is worthwhile reading IMHO. If you are unsure about the entire concept of generic types, the...
[ 0 ]
[]
[]
[ "abstract_class", "crud", "generics", "python", "type_variables" ]
stackoverflow_0074647999_abstract_class_crud_generics_python_type_variables.txt
Q: Margins in PyQtGraph's GraphicsLayout Having a simple graphics layout with PyQtGraph: from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg app = QtGui.QApplication([]) ...
Margins in PyQtGraph's GraphicsLayout
Having a simple graphics layout with PyQtGraph: from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg app = QtGui.QApplication([]) view = pg.Graphi...
[ "I think this might be a Qt bug. There's an easy workaround:\nl = pg.GraphicsLayout()\nl.layout.setContentsMargins(0, 0, 0, 0)\n\nTo understand this, let's look at a modified example:\nfrom pyqtgraph.Qt import QtGui, QtCore\nimport pyqtgraph as pg\n\napp = QtGui.QApplication([])\nview = pg.GraphicsView()\nview.show...
[ 2, 0 ]
[]
[]
[ "pyqt", "pyqtgraph", "python" ]
stackoverflow_0027092164_pyqt_pyqtgraph_python.txt
Q: How to make program sleep until next day I need my code to stop and wait until the next day. The time does not matter, I just need it to continue when the date changes. currentDate = datetime.datetime.now() future = datetime.datetime(currentDate.year, currentDate.month, (currentDate.day + 1)) time.sleep((fu...
How to make program sleep until next day
I need my code to stop and wait until the next day. The time does not matter, I just need it to continue when the date changes. currentDate = datetime.datetime.now() future = datetime.datetime(currentDate.year, currentDate.month, (currentDate.day + 1)) time.sleep((future-currentDate).total_seconds()) The code p...
[ "Two options here with comments.\nFirst do imports\nimport datetime\nimport time\n\n\none uses a while loop - probably not a good solution but highlights one way to wait for a condition to be met.\n\ndef loop_until_tomorrow():\n \"\"\" Will use a while loop to iterate until tomorrow \"\"\"\n\n #get current da...
[ 2, 1 ]
[]
[]
[ "python", "sleep", "time" ]
stackoverflow_0074647866_python_sleep_time.txt
Q: Substract 2 Columns and show the current Value on a new one I have this DataFrame: Names Account_1 Account_2 ID_Movement Less_1 Less_2 Peter 35 70 Movement_1 0 5 Peter 35 70 Movement_2 6 0 Peter 35 70 Movement_3 1 0 Peter 35 70 Movement_4 0 2 Jhon 55 60 Movement_5 6 0 Jhon 55 60 Movement_6 0 2 Jhon 55 60 M...
Substract 2 Columns and show the current Value on a new one
I have this DataFrame: Names Account_1 Account_2 ID_Movement Less_1 Less_2 Peter 35 70 Movement_1 0 5 Peter 35 70 Movement_2 6 0 Peter 35 70 Movement_3 1 0 Peter 35 70 Movement_4 0 2 Jhon 55 60 Movement_5 6 0 Jhon 55 60 Movement_6 0 2 Jhon 55 60 Movement_7 0 3 Jhon 55 60 Movement_8 12 0 Jhon 55 ...
[ "Use groupby.cumsum and subtraction with to_numpy():\ndf[['New_Account1', 'New_Account2']] = (df[['Account_1', 'Account_2']]\n - df.groupby('Names')[['Less_1', 'Less_2']]\n .cumsum().to_numpy()\n ...
[ 3, 0 ]
[]
[]
[ "dataframe", "multiple_columns", "pandas", "python" ]
stackoverflow_0074647640_dataframe_multiple_columns_pandas_python.txt
Q: saving from api to s3 bucket I'm trying to get the below python code to save the csv from an api to an amazon s3 bucket using bot03 and python, but I can't see where I'm going wrong. When I execute the code I don't get any error but the file never appear in the s3 bucket. import boto3 from botocore.exceptions imp...
saving from api to s3 bucket
I'm trying to get the below python code to save the csv from an api to an amazon s3 bucket using bot03 and python, but I can't see where I'm going wrong. When I execute the code I don't get any error but the file never appear in the s3 bucket. import boto3 from botocore.exceptions import ClientError file_name = "test...
[ "I used this code to acheive what I need\nfile_name = \"test.csv\"\nbucket = \"my_bucket\"\n\ndef main():\n url = \"https://api0.solar.sheffield.ac.uk/pvlive/v3/pes/10?start=2021-01-01T00:00:00&end=2021-07-06T00:00:00&data_format=csv\"\n x = requests.get(url,headers={'Content-Type': 'application/json', 'Accep...
[ 1 ]
[ "per the OP(Original Post),\ndid you try\n(line 11) s3 = boto3.client(\"s3\") -- OP: bot03.client(\"s3\")\n" ]
[ -1 ]
[ "amazon_s3", "amazon_web_services", "api", "python" ]
stackoverflow_0068350137_amazon_s3_amazon_web_services_api_python.txt
Q: Creating functions to read file in python This a sample txt file called "price_file.txt": Apple,$2.55 Banana,$5.79 Carrot,$8.19 Dragon Fruit,$8.24 Eggs,$1.44 Hamburger Buns,$1.89 Ice Pops,$4.42 This is a function to allow the user to read the file: def addpricefile (price_file): # input: price file t...
Creating functions to read file in python
This a sample txt file called "price_file.txt": Apple,$2.55 Banana,$5.79 Carrot,$8.19 Dragon Fruit,$8.24 Eggs,$1.44 Hamburger Buns,$1.89 Ice Pops,$4.42 This is a function to allow the user to read the file: def addpricefile (price_file): # input: price file txt # output: item mapped to its pri...
[ "Try this code, I was a bit confused by what you had there but you can simplify the operation a bit. This will achieve the same result. I hope this helps you solve your problem.\ndef openAndSeperate(filename):\n with open(filename,'r') as file:\n priceList = {}\n for i in file:\n i = i.s...
[ 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074648240_function_python.txt
Q: Same code in C++ and Python calculates diff values after a lot of loops, is it the nature of float/double? I am writing a driver model using C++ and Python to compare the performance. The simulation gives data like width, position, speed, etc. and the driver model does some calculations to decide if it needs to br...
Same code in C++ and Python calculates diff values after a lot of loops, is it the nature of float/double?
I am writing a driver model using C++ and Python to compare the performance. The simulation gives data like width, position, speed, etc. and the driver model does some calculations to decide if it needs to brake or not. Both models have the same variables and calculations, but after looping over 500 times first diverge...
[ "As a rule of thumb, if you every find yourself in a situation, where your code does not work because of floating point arithmetic, it is very likely that at least one of the following sentences applies to you:\n\nYou work in a very niche field of research.\nYou have a bug in your code.\nYou are dealing with a math...
[ 1, 0 ]
[]
[]
[ "c++", "floating_point", "python", "python_3.x" ]
stackoverflow_0074401499_c++_floating_point_python_python_3.x.txt
Q: create a new dataframe from selecting specific rows from existing dataframe python i have a table in my pandas dataframe. df id count price 1 2 100 2 7 25 3 3 720 4 7 221 5 8 212 6 2 200 i want to create a new dataframe(df2) from this, selecting rows where count is 2 and...
create a new dataframe from selecting specific rows from existing dataframe python
i have a table in my pandas dataframe. df id count price 1 2 100 2 7 25 3 3 720 4 7 221 5 8 212 6 2 200 i want to create a new dataframe(df2) from this, selecting rows where count is 2 and price is 100,and count is 7 and price is 221 my output should be df2 = id count price 1...
[ "You nedd add () because & has higher precedence than ==:\ndf3 = df[(df['count'] == '2') & (df['price'] == '100')]\nprint (df3)\n id count price\n0 1 2 100\n\nIf need check multiple values use isin:\ndf4 = df[(df['count'].isin(['2','7'])) & (df['price'].isin(['100', '221']))]\nprint (df4)\n id count price\...
[ 18, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0040885318_pandas_python.txt
Q: How to skip Index count using enumerate when value is zero? I have currently one dict with key-value and one list with values. e.g. data = { 'total': { '06724': 0, '06725': 0, '06726': 0, '06727': 0, '06712': 22, '06713': 35, '06714': 108, '06715'...
How to skip Index count using enumerate when value is zero?
I have currently one dict with key-value and one list with values. e.g. data = { 'total': { '06724': 0, '06725': 0, '06726': 0, '06727': 0, '06712': 22, '06713': 35, '06714': 108, '06715': 70, '06716': 0, '06717': 24, '06718': 0...
[ "If I understand you correctly:\nout = dict(\n zip(data[\"item_number\"], (v for v in data[\"total\"].values() if v != 0))\n)\nprint(out)\n\nPrints:\n{\n \"1\": 22,\n \"2\": 35,\n \"3\": 108,\n \"4\": 70,\n \"5\": 24,\n \"6\": 75,\n \"7\": 123,\n \"8\": 224,\n \"9\": 28,\n}\n\n", "Ei...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074648412_python.txt
Q: Error when trying to update pip Good morning, I use Linux Void with Openbox and SpaceFm. I would like to update the pip, but uninstalling the installed version (9.0.3) fails: is there a solution? I also tried the "python3 -m pip install --upgrade pip" command with the same result. This is the terminal output. Than...
Error when trying to update pip
Good morning, I use Linux Void with Openbox and SpaceFm. I would like to update the pip, but uninstalling the installed version (9.0.3) fails: is there a solution? I also tried the "python3 -m pip install --upgrade pip" command with the same result. This is the terminal output. Thank you. $ pip install --upgrade pip Co...
[ "Try using \"sudo\" or any user with enough privileges like \"root\"\n", "Try putting \"--user\" at the end of the command\n" ]
[ 0, 0 ]
[]
[]
[ "linux", "pip", "python", "python_3.x" ]
stackoverflow_0050113257_linux_pip_python_python_3.x.txt
Q: Continue running code when KeyError: "['Column'] not in index" occurs for null values? I get KeyError: "['marketCap'] not in index" when there is no data in the "marketCap" column for a particular symbol. How do I put "Null" when there's no data so the code can continue running and not error out? import pandas as...
Continue running code when KeyError: "['Column'] not in index" occurs for null values?
I get KeyError: "['marketCap'] not in index" when there is no data in the "marketCap" column for a particular symbol. How do I put "Null" when there's no data so the code can continue running and not error out? import pandas as pd from yahooquery import Ticker symbols = ['MSFT','GOOG','AAPL'] #I have to put 75,000+ s...
[ "Got this working:\nimport pandas as pd\nfrom yahooquery import Ticker\n\nsymbols = ['MSFT','GOOG','AAPL'] #I have to put 75,000+ symbols here.\nheader = [\"regularMarketPrice\", \"marketCap\"]\n\nfor tick in symbols:\n faang = Ticker(tick)\n faang.price\n df = pd.DataFrame(faang.price,{\"regularMarketPric...
[ 0 ]
[]
[]
[ "arrays", "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074645315_arrays_csv_dataframe_pandas_python.txt
Q: How to read an excel file with data and some empty cells in panda's python? I have an excel file with huge dataset. I tried to read the excel file using the below command using pandas. df = pd.read_csv(f'{cwd}/data.csv', keep_default_na=False, header=None) print(df) However the empty rows found in the csv file is...
How to read an excel file with data and some empty cells in panda's python?
I have an excel file with huge dataset. I tried to read the excel file using the below command using pandas. df = pd.read_csv(f'{cwd}/data.csv', keep_default_na=False, header=None) print(df) However the empty rows found in the csv file is missing in the output. I get something like below. Input: Output from the ...
[ "You need to specify the parameter skip_blank_lines=False from pandas.read_csv. Here's a fixed version of your code:\nimport pandas as pd\n\ndf = pd.read_csv(f'{cwd}/data.csv', header=None, na_filter=False, skip_blank_lines=False)\ndf\n\nOutputs:\n\nOr:\nimport pandas as pd\n\ndf = pd.read_csv(f'{cwd}/data.csv', he...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074648226_pandas_python.txt