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: ValueError: invalid literal for int() with base 10: '0.294' I want to generate a random int and then use time.sleep(). I want it to generate something like 0.123 randomly. Here is my code: s = f"0.{str(random.randint(111, 333))}" s = int(s) time.sleep(s) I am getting the error: time.sleep(s) ValueError: inval...
ValueError: invalid literal for int() with base 10: '0.294'
I want to generate a random int and then use time.sleep(). I want it to generate something like 0.123 randomly. Here is my code: s = f"0.{str(random.randint(111, 333))}" s = int(s) time.sleep(s) I am getting the error: time.sleep(s) ValueError: invalid literal for int() with base 10: '0.198' I tried a lot of thin...
[ "You're trying to convert a floating point number (0.xxx) to an int.\nWhat you need to do is convert it to a float instead:\ns = float(s)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074295663_python.txt
Q: Slicing certain elements of a tuple If I have tuple: myT=(β€œa”, β€œb”, β€œc”, β€œd”, β€œe”, β€œf”) Is it possible to slice out say β€œa”, β€œd”, β€œe”? Something like myT = myT[0, 3, 4]. A: I don't think there is a standard concise way to write something like that. What you can do is: a = ('a', 'b', 'c', 'd', 'e', 'f') b = (a[0...
Slicing certain elements of a tuple
If I have tuple: myT=(β€œa”, β€œb”, β€œc”, β€œd”, β€œe”, β€œf”) Is it possible to slice out say β€œa”, β€œd”, β€œe”? Something like myT = myT[0, 3, 4].
[ "I don't think there is a standard concise way to write something like that.\nWhat you can do is:\na = ('a', 'b', 'c', 'd', 'e', 'f')\nb = (a[0], a[3], a[4])\n\nOr, if you don't want to refer to a more than once, the simplest option should be something like this:\nb = tuple(a[x] for x in [0, 3, 4])\n\nBut if you fi...
[ 1, 0 ]
[]
[]
[ "python", "slice" ]
stackoverflow_0074295676_python_slice.txt
Q: Python- Send email using css I am trying to send an email using this function I have written: def send_email(recip, subj, content): email = MIMEMultipart('alternative') email['To'] = ",".join(recip) email['From'] = 'xyz@abc.com' email['Subject'] = subj body = MIMEText(content, 'html') email...
Python- Send email using css
I am trying to send an email using this function I have written: def send_email(recip, subj, content): email = MIMEMultipart('alternative') email['To'] = ",".join(recip) email['From'] = 'xyz@abc.com' email['Subject'] = subj body = MIMEText(content, 'html') email.attach(body) smtpObj = smtpli...
[ "Each email client (Outlook, Thunderbird, Gmail in a web browser, etc.) handles CSS differently. But the end result is that you generally should NOT rely on CSS embedded in head elements - it just doesn't work reliably in email. What mostly works is to use inline CSS - i.e., CSS on the actual HTML elements in the b...
[ 0, 0 ]
[]
[]
[ "mime", "python" ]
stackoverflow_0074295702_mime_python.txt
Q: Split a pandas dataframe when rows are blank into multiple datadrames I have the following dataframe: [['M', 'A', '0', '0.2', '0.2', '0.2'], [nan, nan, nan, '0.3', '0.3', '1'], [nan, nan, nan, '1.4', '3.2', '32'], [nan, nan, nan, nan, nan, nan], [nan, nan, nan, nan, nan, nan], ['sex', 'test', 'conc', 'sugar',...
Split a pandas dataframe when rows are blank into multiple datadrames
I have the following dataframe: [['M', 'A', '0', '0.2', '0.2', '0.2'], [nan, nan, nan, '0.3', '0.3', '1'], [nan, nan, nan, '1.4', '3.2', '32'], [nan, nan, nan, nan, nan, nan], [nan, nan, nan, nan, nan, nan], ['sex', 'test', 'conc', 'sugar', 'flour', 'yeast'], ['M', 'A', '3', '1.2', '1.2', '1.2'], [nan, nan, nan,...
[ "IIUC, you can use:\nm = df.isna().all(axis=1)\n\ndfs = [g for k,g in df[~m].groupby(m.cumsum())]\n\nOutput:\n[ 0 1 2 3 4 5\n 0 M A 0 0.2 0.2 0.2\n 1 NaN NaN NaN 0.3 0.3 1\n 2 NaN NaN NaN 1.4 3.2 32,\n 0 1 2 3 4 5\n 5 sex test conc sugar ...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074295670_dataframe_pandas_python.txt
Q: Rank value from a column from lowest to highest I want to to something like this Input Animal Weight 0 Cat 1.2 1 Cat 1.1 2 Cat 2.5 3 Cat 0.8 4 Dog 5.3 5 Dog 4.7 6 Dog 4.2 7 Dog 3.6 8 Dog 4.9 9 Dog 6.0 Output Animal Weight Position 0 Cat 1.2 2 1 Cat 1.1 ...
Rank value from a column from lowest to highest
I want to to something like this Input Animal Weight 0 Cat 1.2 1 Cat 1.1 2 Cat 2.5 3 Cat 0.8 4 Dog 5.3 5 Dog 4.7 6 Dog 4.2 7 Dog 3.6 8 Dog 4.9 9 Dog 6.0 Output Animal Weight Position 0 Cat 1.2 2 1 Cat 1.1 3 2 Cat 2.5 1 3 Cat 0.8 4 4 ...
[ "You can use groupby.rank with method='dense', ascending=False:\ndf['Position'] = (df.groupby('Animal').rank(method='dense', ascending=False)\n .astype(int) # optional\n )\n\nOutput:\n Animal Weight Position\n0 Cat 1.2 2\n1 Cat 1.1 3\n2 Cat ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074295770_dataframe_pandas_python.txt
Q: How can I wrap a string using python's textwrap library to be exactly a set amount of characters in width? I have a chunk of text and I want to print it so that every line is exactly n characters in width. I'm using python's textwrap library but the problem I've had with that is that sometimes the line of text wil...
How can I wrap a string using python's textwrap library to be exactly a set amount of characters in width?
I have a chunk of text and I want to print it so that every line is exactly n characters in width. I'm using python's textwrap library but the problem I've had with that is that sometimes the line of text will be less than n characters in length with no whitespace padding. My code looks like this from tabulate import t...
[ "See what you think about this. This post-processes textwrap.wrap to do justification:\nimport textwrap\n\ndef wrapme(s):\n\n width = 64\n lines = s.splitlines()\n result = []\n for l in lines:\n if len(l) < 64:\n result.append(l)\n else:\n breaks = textwrap.wrap( l,...
[ 0 ]
[]
[]
[ "python", "tabulate", "word_wrap" ]
stackoverflow_0074286313_python_tabulate_word_wrap.txt
Q: View is returning an HttpResponse, but says it returns None I have a button in one of my views that triggers a function "compileUpdate" and then returns a file as a response. This was working previously but now I receive the error: "ValueError: The view didn't return an HttpResponse object. It returned None instea...
View is returning an HttpResponse, but says it returns None
I have a button in one of my views that triggers a function "compileUpdate" and then returns a file as a response. This was working previously but now I receive the error: "ValueError: The view didn't return an HttpResponse object. It returned None instead." The block of code below essentially: Gets the correct campaig...
[]
[]
[ "You did not return anything if req == \"Bulk Delete\"\nYou should add HttpResponse as well.\n elif req == \"Bulk Delete\":\n cmp_id = request.headers.get('cmp')\n\n campaign = Campaign.objects.get(id=cmp_id)\n\n return HttpResponse(status=204)\n\n" ]
[ -1 ]
[ "django", "django_templates", "django_views", "javascript", "python" ]
stackoverflow_0074295591_django_django_templates_django_views_javascript_python.txt
Q: 'str' object is not callable error while trying to read data Declare the class TreasureChest. The attributes should be private. Text file TreasureChestData.txt stores data in the order of question, answer, points. Use readData() to read each question, answer and points Create an object of type TreasureChest for ea...
'str' object is not callable error while trying to read data
Declare the class TreasureChest. The attributes should be private. Text file TreasureChestData.txt stores data in the order of question, answer, points. Use readData() to read each question, answer and points Create an object of type TreasureChest for each question. Declare an array named arrayTreasure of type: Trasure...
[ "Error\ntreasureChest = str(TreasureChest(\"\", 0, 0))\n\nThis instantiates a TreasureChest, then generate a string version of it, then you try to use it to instantiate other TreasureChest, that has no sense\n\nFix\nUse the class to instantiate the object, type well the list, use with open\narrayTreasure: list[Trea...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074295772_python.txt
Q: try except, how to retry after exception error? im trying to use try and expect to update some values from API this is the code which im using and i think its not working well, due to while its find error its filling all upcoming data with the same error value ` new_budget = [] new_revenue = [] i = 42 start_time =...
try except, how to retry after exception error?
im trying to use try and expect to update some values from API this is the code which im using and i think its not working well, due to while its find error its filling all upcoming data with the same error value ` new_budget = [] new_revenue = [] i = 42 start_time = time.time() while len(new_budget) < 20: try: ...
[ "The issue is, when there's a HTTPError, the code flow jumps to the except block at that exact line. The code does not gets a chance to get to the 13th line where the i is getting incremented.\nSince the value of i remains the same, it keeps on fetching the same value from the API and gets the same Error message fo...
[ 0 ]
[]
[]
[ "error_handling", "exception", "python" ]
stackoverflow_0074259387_error_handling_exception_python.txt
Q: Python not showing correct version on Mac OSX I am trying to update Python to 3.7.4 on my Mac. Currently when I type python3 --version, it shows that I have Python 3.7.3 I have tried to update using just the standalone installer from the website as well as homebrew but even through all of these methods, python3 --...
Python not showing correct version on Mac OSX
I am trying to update Python to 3.7.4 on my Mac. Currently when I type python3 --version, it shows that I have Python 3.7.3 I have tried to update using just the standalone installer from the website as well as homebrew but even through all of these methods, python3 --version still returns to me 3.7.3. Even when I try ...
[ "Update: Check what python version you are using by running which python, at this point you might figure out what version of Python is being used to solve this problem. Otherwise, follow up this steps:\nI would remove all Python installations and use Homebrew to install it.\nFirst, run which python:\n/Library/Frame...
[ 6, 1, 0, 0 ]
[]
[]
[ "homebrew", "macos", "python", "python_3.7", "python_3.x" ]
stackoverflow_0057965583_homebrew_macos_python_python_3.7_python_3.x.txt
Q: Python AttributeError: module 'requests' has no attribute 'requestURL' I would like to run the code from the module requests_with_caching.py that uses the build in requests module from Python. I have 2 py.files in the samefolder (requests_with_caching.py + test.py). The library requests is installed. I get an At...
Python AttributeError: module 'requests' has no attribute 'requestURL'
I would like to run the code from the module requests_with_caching.py that uses the build in requests module from Python. I have 2 py.files in the samefolder (requests_with_caching.py + test.py). The library requests is installed. I get an AttributeError: module 'requests' has no attribute 'requestURL'. I don't get w...
[ "The module requests_with_caching.py was written for Runestone by the University of Michigan in their Coursera course Data Collection and Processing with Python.\nThis module imports the requests module, and seems to use a special requests method called requestURL().\nThe thing is, the requests.requestURL() method ...
[ 0 ]
[]
[]
[ "attributes", "python", "python_requests" ]
stackoverflow_0070291508_attributes_python_python_requests.txt
Q: add a border (filled with 0's) around an existing array I'm trying to add a border (filled with 0's) around an existing array. My code: a = np.random.random((4, 5)) m, n = a.shape b = np.zeros((m+1, n+1)) b[1:-1,1:-1] = a a,b but I got a error: ValueError: could not broadcast input array from shape (4,5) into sha...
add a border (filled with 0's) around an existing array
I'm trying to add a border (filled with 0's) around an existing array. My code: a = np.random.random((4, 5)) m, n = a.shape b = np.zeros((m+1, n+1)) b[1:-1,1:-1] = a a,b but I got a error: ValueError: could not broadcast input array from shape (4,5) into shape (3,4) Why can't I directly assign values to parts of a 2D ...
[ "You can accomplish your task using np.pad function:\nb = np.pad(a, 1)\n\nShorter code than yours.\nRead the documentation of this function for any details.\n", "b[:, [0, -1]] = 0\nb[[0, -1], :] = 0\n\n" ]
[ 1, 0 ]
[]
[]
[ "broadcast", "numpy", "python" ]
stackoverflow_0070736162_broadcast_numpy_python.txt
Q: How do I create a new column that references other row's data for its values? I have the following data frame: Month Day Year Open High Low Close Week 0 1 1 2003 46.593 46.656 46.405 46.468 1 1 1 2 2003 46.538 46.66 46.47 46.673 1 2 1 3 2003 46.717 46.781 46.53 46.750 1 3 1 4 2003 46.815 46.843 46.68 46.750 1...
How do I create a new column that references other row's data for its values?
I have the following data frame: Month Day Year Open High Low Close Week 0 1 1 2003 46.593 46.656 46.405 46.468 1 1 1 2 2003 46.538 46.66 46.47 46.673 1 2 1 3 2003 46.717 46.781 46.53 46.750 1 3 1 4 2003 46.815 46.843 46.68 46.750 1 4 1 5 2003 46.935 47.000 46.56 46.593 1 ... ... ... ... ... ... ... ...
[ "I am assuming you are using pandas. Other libraries will work similar.\nCreate a new DataFrame aggregated per week using groupby and join it back to your original DataFrame\ndf_grouped = df[\"Week\", \"High\"].groupby(\"Week\").max().rename(columns={\"High\":\"Highest High\"}\ndf_result = df.join(df_grouped, \"Wee...
[ 0, 0 ]
[]
[]
[ "dataframe", "date", "python", "stock" ]
stackoverflow_0074295632_dataframe_date_python_stock.txt
Q: Formatter black is not working on my VSCode...but why? I have started using Python and Django and I am very new in this field. And this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue... When I installed and set VSCode formatter 'black' (after setting ...
Formatter black is not working on my VSCode...but why?
I have started using Python and Django and I am very new in this field. And this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue... When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up ...
[ "I use Black from inside VSCode and it rocks. It frees mental cycles that you would spend deciding how to format your code. It's best to use it from your favorite editor. Just run from the command line if you need to format a lot of files at once.\nFirst, check if you have this in your VSCode settings.json (open it...
[ 55, 30, 7, 6, 6, 3, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ "The best way to use black is through terminal in my opinion. All you need to do is install it on pip on terminal using: pip install black\nThen when it's installed you go onto terminal and type: black filename.py\nthe full line would be: black filepath/file.py\nSo for a file called test.py located on desktop if on...
[ -2 ]
[ "python", "python_black", "visual_studio_code" ]
stackoverflow_0065101442_python_python_black_visual_studio_code.txt
Q: remove duplicates from value of dicts of list I have a list like this: list = [{"name": "name1", "zipcode": "zipcode1", "id": "id1"},{"name": "name2", "zipcode": "zipcode2", "id": "id2"}, {"name": "name1", "zipcode": "zipcode3", "id": "id1"}] I want to remove dicts which has same ids. I know how to remove duplica...
remove duplicates from value of dicts of list
I have a list like this: list = [{"name": "name1", "zipcode": "zipcode1", "id": "id1"},{"name": "name2", "zipcode": "zipcode2", "id": "id2"}, {"name": "name1", "zipcode": "zipcode3", "id": "id1"}] I want to remove dicts which has same ids. I know how to remove duplicates but notice they are not duplicates, they have d...
[ "Just use set to track seen ids:\nseen = set()\nalist = [\n {\"name\": \"name1\", \"zipcode\": \"zipcode1\", \"id\": \"id1\"},\n {\"name\": \"name2\", \"zipcode\": \"zipcode2\", \"id\": \"id2\"},\n {\"name\": \"name1\", \"zipcode\": \"zipcode3\", \"id\": \"id1\"}\n]\nresult = []\nfor obj in alist:\n idx...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "duplicates", "list", "python", "python_3.x" ]
stackoverflow_0074290220_dictionary_duplicates_list_python_python_3.x.txt
Q: Plot Mahalanobis distance as ellipse for PCA is missing part of circle edge I am working creating a PCA combined with a Mahalanobis distance function to remove any outliers detected from the PCA transformation. I have come across this article which uses R: Mahalanobis output in R. However, how do I implement the M...
Plot Mahalanobis distance as ellipse for PCA is missing part of circle edge
I am working creating a PCA combined with a Mahalanobis distance function to remove any outliers detected from the PCA transformation. I have come across this article which uses R: Mahalanobis output in R. However, how do I implement the Mahalanobis with Python and get an ellipse to centre around the cluster. Some samp...
[ "Please add plt.xlim() and plt.ylim():\nplt.legend(loc=\"best\", shadow=False, scatterpoints=1)\nplt.title(\"PCA of IRIS dataset\")\nplt.xlim(-3,4) # ADD\nplt.ylim(-3,3) # ADD\nxx, yy = np.meshgrid(\n np.linspace(plt.xlim()[0], plt.xlim()[1], 100),\n np.linspace(plt.ylim()[0], plt.ylim()[1], 100),)\nz...
[ 3 ]
[]
[]
[ "machine_learning", "mahalanobis", "pca", "python", "scikit_learn" ]
stackoverflow_0074294001_machine_learning_mahalanobis_pca_python_scikit_learn.txt
Q: Making Turtle Graphics Python game start only after main menu button has been clicked so i'm currently making a python turtle graphics game, it's a pong game where there is a 2 paddles and they pass the ball to each other, once ball touches each side the player gets a point, the game is fully functional in 1920x10...
Making Turtle Graphics Python game start only after main menu button has been clicked
so i'm currently making a python turtle graphics game, it's a pong game where there is a 2 paddles and they pass the ball to each other, once ball touches each side the player gets a point, the game is fully functional in 1920x1080 res, the thing is i made a main menu type of thing where the game starts after the Start...
[ "You've made this difficult to implement by putting too much functionality at the top level of the code instead of encapsulated in functions. I've reworked your code to shoehorn in this functionality below. Your \"start\" button is just a giant circle as I don't have your artwork:\nfrom turtle import Screen, Turt...
[ 0 ]
[]
[]
[ "python", "python_3.x", "turtle_graphics" ]
stackoverflow_0074295135_python_python_3.x_turtle_graphics.txt
Q: Select first element of srcset with python selenium Using selenium in Python, I have been able to successfully access some url's of an image I want to download. However, the image link is stored within a srcset image attribute. When I use get_attribute('srcset'), it returns a string with the 4 links. I just want t...
Select first element of srcset with python selenium
Using selenium in Python, I have been able to successfully access some url's of an image I want to download. However, the image link is stored within a srcset image attribute. When I use get_attribute('srcset'), it returns a string with the 4 links. I just want the one. How would I go about doing this? Could I possibly...
[ "The image seems to have an attribute called currentSrc which hold only the current value.\nimg_url = driver.find_element(By.XPATH, \"//div[@class = 'responsive-image-wrapper']/img\").get_attribute(\"currentSrc\")\ndriver.get(img_url)\n\n", "You can simply split the value extracted from that web element.\nAs foll...
[ 1, 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "split", "xpath" ]
stackoverflow_0074295441_python_selenium_selenium_webdriver_split_xpath.txt
Q: For a SciPy sparse matrix, how to get indices of values below a threshold When using a conditional statement to filter values in a SciPy sparse array, how can I get the indices of those values? I am trying to use apply the conditional statement to csc_array().data to get the indices but they don't match the csc_ar...
For a SciPy sparse matrix, how to get indices of values below a threshold
When using a conditional statement to filter values in a SciPy sparse array, how can I get the indices of those values? I am trying to use apply the conditional statement to csc_array().data to get the indices but they don't match the csc_array().nonzero() indices. Here is an example of the issue I am facing: import n...
[ "To get around the mis-match between the ordering of csc_array().data and csc_array().nonzero(), you can simply use the nonzero indices throughout, as shown here:\nimport numpy as np\nfrom scipy.sparse import dok_array, csc_array\n\nm = dok_array((1000, 1000))\nfor i, j in zip(np.random.randint(0, 1000, 100), np.ra...
[ 0 ]
[]
[]
[ "python", "scipy", "sparse_matrix" ]
stackoverflow_0074296024_python_scipy_sparse_matrix.txt
Q: How i can get JSON list without attributes ("count": 3, "next": null, "previous": null, "results":) I have JSON like this: {"count":3,"next":null,"previous":null,"results":[{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name...
How i can get JSON list without attributes ("count": 3, "next": null, "previous": null, "results":)
I have JSON like this: {"count":3,"next":null,"previous":null,"results":[{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11...
[ "If you have whole json as a dictionary like this:\nresponse_json = {\"count\":3,\"next\":null,\"previous\":null,\"results\":[{\"name\":\"Max\",\"slug\":\"DrMax\",\"directions\":[\"Surgery\",\"Stomach\"],\"description\":\"Surgery\",\"work_experience\":\"2\",\"birt_date\":\"2018-12-04\"},{\"name\":\"Ban\",\"slug\":\...
[ 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074295599_json_python.txt
Q: Recursion error while trying to write an memoization decorator This is an wrapper function that will be used to decorate the function that we want to memoize. I wrote that as an exercise to understand how memoization works and challange myself to write it without looking at the solution. It works, but I'm not sure...
Recursion error while trying to write an memoization decorator
This is an wrapper function that will be used to decorate the function that we want to memoize. I wrote that as an exercise to understand how memoization works and challange myself to write it without looking at the solution. It works, but I'm not sure if it's the best way to do it. I got some errors while testing it w...
[ "In terms of dealing with the RecursionError, I think this answer might help you out a bit.\nTL;DR -\n\nPython don't have a great support for recursion because of it's lack\nof TRE (Tail Recursion Elimination).\nThis means that each call to your recursive function will create a\nfunction call stack and because ther...
[ 0 ]
[]
[]
[ "memoization", "python", "recursion" ]
stackoverflow_0074296005_memoization_python_recursion.txt
Q: Django-admin is is not recognized I've been trying to start a Django project and when I try to create a new project, it gives me an error django-admin startproject example The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. I've added Python to environ...
Django-admin is is not recognized
I've been trying to start a Django project and when I try to create a new project, it gives me an error django-admin startproject example The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. I've added Python to environmental variable and of course installe...
[ "I had the same problem when trying to run it on windows 10 CMD. It worked well on anaconda3powershell using django-admin startproject project.\nTo create a project using windows CMD or any other terminal that does not support django-admin use the following.python -m django startproject Project\n", "First check t...
[ 1, 0, 0, 0 ]
[]
[]
[ "cmd", "django", "python" ]
stackoverflow_0056796303_cmd_django_python.txt
Q: Principle Component Analysis, add a line to the 3d graph showing the first principal component I am conducting PCA on a dataset. I am attempting to add a line in my 3d graph which shows the first principal component. I have tried a few methods but have not been able to display the first principal component as a li...
Principle Component Analysis, add a line to the 3d graph showing the first principal component
I am conducting PCA on a dataset. I am attempting to add a line in my 3d graph which shows the first principal component. I have tried a few methods but have not been able to display the first principal component as a line in my 3d graph. Any help is greatly appreciated. My code is as follows: import numpy as np np.set...
[ "Some remarks to begin with:\n\nYou are computing PCA twice! To compute PCA is to compute eigen values and eigen vectors of the covariance matrix. So, either you use the sklearn function pca.fit, either you do it yourself. But you don't need to do both, unless you want to discover pca.fit and see for yourself that ...
[ 0 ]
[]
[]
[ "components", "data_science", "pca", "principal", "python" ]
stackoverflow_0074295038_components_data_science_pca_principal_python.txt
Q: Finding the maximum value in a python dictionary It prints the last value as the maximum value dict = { 'Alissa': 14, 'Believe': 13, 'Miracle': 2, } for student in dict: name = '' score = 0 if dict.get(student) > score: name = student score = dict.get(student) print(f"{stude...
Finding the maximum value in a python dictionary
It prints the last value as the maximum value dict = { 'Alissa': 14, 'Believe': 13, 'Miracle': 2, } for student in dict: name = '' score = 0 if dict.get(student) > score: name = student score = dict.get(student) print(f"{student} had the highest score of {score}.") Miracle had ...
[ "dict = {\n 'Alissa': 14,\n 'Believe': 13,\n 'Miracle': 2,\n}\nvalues=list(dict.values())\nkeys=list(dict.keys())\n\nmax_value = max(values)\n\nmax_key = keys[values.index(max_value)]\n\nprint(max_value)\n\nprint(max_key)\n\n" ]
[ -1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074296001_python_python_3.x.txt
Q: Recently, I switched to python 3.11 & I'm unable to install kivy & kivymd Here, is the error image. Recently, I switched to python 3.11 & I'm unable to install kivy & kivymd. Luckily, I've big brain & I switched back to python 3.10 & install kivy & its works like a charm. How can I install kivy with python 3.11 ??...
Recently, I switched to python 3.11 & I'm unable to install kivy & kivymd
Here, is the error image. Recently, I switched to python 3.11 & I'm unable to install kivy & kivymd. Luckily, I've big brain & I switched back to python 3.10 & install kivy & its works like a charm. How can I install kivy with python 3.11 ???
[ "Kivy 2.1.0 officially supports Python versions 3.7 - 3.10.\nSource: https://kivy.org/doc/stable/gettingstarted/installation.html\n" ]
[ 1 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0074293899_kivy_python.txt
Q: How to eliminate pixel offset generated while try to draw points based on the color of the pixels [OpenCV] I'm trying to draw a horizontal line across a shape (ellipse in this instance with only the centroid and the boundary of the ellipse on a black background) starting from the centroid of the shape (ellipse) . ...
How to eliminate pixel offset generated while try to draw points based on the color of the pixels [OpenCV]
I'm trying to draw a horizontal line across a shape (ellipse in this instance with only the centroid and the boundary of the ellipse on a black background) starting from the centroid of the shape (ellipse) . I started off checking each and every pixel along +x and -x axes from centroid and replacing each non-green pixe...
[ "There are couple of problems, one hiding neatly behind another.\nThe first issue is evident in this snippet of code extracted from your script:\n# ...\nval = ((654, 664),(264, 266),80)\ncentroid = (val[0][0],val[0][1])\n\ny_center = centroid[1]\nright_pt = centroid[0]\nleft_pt = centroid[0]\n\nwhile(np.any(canvas[...
[ 3 ]
[]
[]
[ "computer_vision", "numpy", "opencv", "python", "shapes" ]
stackoverflow_0074285571_computer_vision_numpy_opencv_python_shapes.txt
Q: read dictionaries from file - python I'm trying to read a series of dictionaries from a file: GFG.txt {'geek': 10, 'geeky': True} {'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'} {'supergeek': 5} and I found this website with the following solution: import pickle geeky_file = open('GFG.txt', 'r') dictio...
read dictionaries from file - python
I'm trying to read a series of dictionaries from a file: GFG.txt {'geek': 10, 'geeky': True} {'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'} {'supergeek': 5} and I found this website with the following solution: import pickle geeky_file = open('GFG.txt', 'r') dictionary_list = pickle.load(geeky_file) for...
[ "If every \"text dictionary\" is on a single line, ast.literal_eval can help:\nimport ast\n\nwith open('GFG.txt', 'rb') as f:\n list_of_dicts = [ast.literal_eval(line.decode()) for line in f]\nlist_of_dicts\n\nOutput:\n[{'geek': 10, 'geeky': True},\n {'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'},\n ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074295664_python.txt
Q: If the row satisfies a certain condition, write the specific expression in the empty column import pandas as pd df = pd.DataFrame({'action': ['visited', 'clicked', 'switched'], 'target': ['pricing page', 'homepage', 'succeesed'] 'type': [np.nan, np.nan, np.nan],})` I have a...
If the row satisfies a certain condition, write the specific expression in the empty column
import pandas as pd df = pd.DataFrame({'action': ['visited', 'clicked', 'switched'], 'target': ['pricing page', 'homepage', 'succeesed'] 'type': [np.nan, np.nan, np.nan],})` I have an empty "type" column in the dataframe. I want a text to be written if the row certain condition ...
[ "df.loc[df['action'].eq('visited') & df['target'].eq('pricing page'), 'type'] = 'free'\n\naction target type\n0 visited pricing page free\n1 clicked homepage NaN\n2 switched succeesed NaN\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074295854_dataframe_pandas_python.txt
Q: how do i get bot.command() to work? (discord.py) ive tried everything i could find but nothing seems to be working heres what i have: import discord from discord.ext import commands import os import requests import json import random import string my_secret = os.environ['my_secret'] client = discord.Client() @cl...
how do i get bot.command() to work? (discord.py)
ive tried everything i could find but nothing seems to be working heres what i have: import discord from discord.ext import commands import os import requests import json import random import string my_secret = os.environ['my_secret'] client = discord.Client() @client.event async def on_ready(): print("we're in ...
[]
[]
[ "Try @bot.command()Rename to @client.command()\nAnd if you want the bot to work for a long time and if I understand correctly that you include the bot in the replit.com if so, create a file called webserver.py then import from webserver import keep_alive Go to the file you created and write there\nfrom flask import...
[ -1 ]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074210796_bots_discord_discord.py_python.txt
Q: Why does my program to calculate the average of numbers entered into a while loop not work as expected? I am new to coding. I would like to attend a course but there are assessments first in order to be chosen. The question I am stuck on is: Write a program that always asks the user to enter a number. When the us...
Why does my program to calculate the average of numbers entered into a while loop not work as expected?
I am new to coding. I would like to attend a course but there are assessments first in order to be chosen. The question I am stuck on is: Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program ...
[ "so lets break this down together.\nThis is fine.\nnum = 0\ninputs = []\n\nYou will want to modify this while true statement to be while True (if using python) like below\nwhile True:\n\nNext, it doesn't explicitly say integers, and technically there are different number types, but for simplicity sake we check to s...
[ 2, 1 ]
[]
[]
[ "average", "python", "while_loop" ]
stackoverflow_0074296057_average_python_while_loop.txt
Q: my .append() function didn't work properly I couldn't spot why (beginner level Python) im a beginner programmer and im trying to make a simple blackjack game just for exercise in Python 3.10 using PyCharm CE but I wasn't able to solve a problem. The problem is my player_draw_card() function is not drawing a card. ...
my .append() function didn't work properly I couldn't spot why (beginner level Python)
im a beginner programmer and im trying to make a simple blackjack game just for exercise in Python 3.10 using PyCharm CE but I wasn't able to solve a problem. The problem is my player_draw_card() function is not drawing a card. I wanted to put the whole code in case I miss something but I also highlighted the important...
[ "You are defining the player_cards list twice. Once it is defined on line 7, and then again inside the blackjack() method on line 41.\nWhat happens is that you are creating two differently scoped variables player_cards. When you're calling the player_draw_card() from the blackjack() method, the player_draw_card() d...
[ 0 ]
[]
[]
[ "append", "debugging", "python" ]
stackoverflow_0074296074_append_debugging_python.txt
Q: inside on_message in discord.py, if statements to check content doesn't work @client.event async def on_message(message): if message.author.bot: return if message.content == 'hi': await message.channel.send("hi") Why doesn't this work? The code runs without errors but it doesn't detect the m...
inside on_message in discord.py, if statements to check content doesn't work
@client.event async def on_message(message): if message.author.bot: return if message.content == 'hi': await message.channel.send("hi") Why doesn't this work? The code runs without errors but it doesn't detect the message "hi" I wanted the bot to send a message when I send a certain message.
[ "You have to have 'message content intent' enabled in your Discord Developer Portal (https://i.stack.imgur.com/jD6zh.png) and your program:\nintents = discord.Intents.default()\nintents.message_content = True\nclient = discord.Client(intents=intents)\n\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074295868_discord.py_python.txt
Q: How to I append elements to a list of lists in python I've a list of lists like: a = [[1,2], [3,4]] To each of the lists I want to add an element like 0 at the beginning, so that the result looks like: b = [[0,1,2], [0,3,4]] What's the Python way to do it? I already tried it with "map", but without success. I kn...
How to I append elements to a list of lists in python
I've a list of lists like: a = [[1,2], [3,4]] To each of the lists I want to add an element like 0 at the beginning, so that the result looks like: b = [[0,1,2], [0,3,4]] What's the Python way to do it? I already tried it with "map", but without success. I know, I could easily do it with a loop, but what's the functi...
[ "Use list comprehension and addition of lists to get in done in one short line of code:\nb = [[0]+item for item in a]\n\n" ]
[ 5 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074296187_list_python.txt
Q: Python Try-Except inside of Function I've got a pretty good understanding of python's try-except clause, but I'm encountering problems when trying to put it inside of a function. >>> def tryAppend(child, parent): ... try: ... parent.append(child) ... except NameError: ... print "WRO...
Python Try-Except inside of Function
I've got a pretty good understanding of python's try-except clause, but I'm encountering problems when trying to put it inside of a function. >>> def tryAppend(child, parent): ... try: ... parent.append(child) ... except NameError: ... print "WRONG NAME" >>> var1 = [] >>> var2 = 'test2' ...
[ "tryAppend(foo, var1) is evaluated (roughly) in this order:\n\nFetch the object tryAppend references\nFetch the object foo references\nFetch the object var1 references\nCall the first with the second and third as arguments (=do whatever the function tryAppend does, uncluding the try-except)\n\nThe error occurs at #...
[ 11, 5, 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "exception", "exception_handling", "python", "try_catch" ]
stackoverflow_0004148015_exception_exception_handling_python_try_catch.txt
Q: Check if Price Column has value in Lacs or Crore, then convert the value to actual number df = pd.DataFrame({'Price' : ['5.5 lacs', '5.7 Crore', '3.5 lacs', '3.15 lacs']}) 5.5 lacs will become 550000 and 5.7 Crore will become 57000000. Then Save these new values in the same column Price at the corresponding place...
Check if Price Column has value in Lacs or Crore, then convert the value to actual number
df = pd.DataFrame({'Price' : ['5.5 lacs', '5.7 Crore', '3.5 lacs', '3.15 lacs']}) 5.5 lacs will become 550000 and 5.7 Crore will become 57000000. Then Save these new values in the same column Price at the corresponding places. I know to change one of them at a time i.e values in lac. df['Price'] = df['Price'].str.str...
[ "arr = ['5.5 lacs', '5.7 Crore', '3.5 lacs', '3.15 lacs']\nnew = list(map(lambda x: (\n denom := x.find('lacs'),\n float(x[:denom].strip(\" \"))*100000 if denom!=-1 else float(x[:x.find('Crore')].strip(\" \"))*10000000\n ), arr))\n\nnew = list(map(lambda x : x[1], new))\n\nThe following...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074295657_python.txt
Q: Running setup.py install for tesseract-ocr did not run successfully So im trying to install Tesseract-OCR packages to this project for some personal scripts im trying to run and its not installing the packages. Ever time I try to install Tesseract-OCR/give it the command e.g. pip install tesseract-ocr its gives me...
Running setup.py install for tesseract-ocr did not run successfully
So im trying to install Tesseract-OCR packages to this project for some personal scripts im trying to run and its not installing the packages. Ever time I try to install Tesseract-OCR/give it the command e.g. pip install tesseract-ocr its gives me this end of output, im using Python 3.9 and am on windows, i was expecti...
[ "simple answer is to Directly install tesseract-ocr from the directory its installed in if you downloaded the files from the internet, apparently tesseract cant be installed from pycharm on my pc, in terminal of pcharm in your project type the following: note it goes disk:\\folder\\Teesseract-OCR\nthen\npip install...
[ 0 ]
[]
[]
[ "pycharm", "python", "tesseract" ]
stackoverflow_0074277033_pycharm_python_tesseract.txt
Q: Iterating Through a List of Functions in Python Let's say I have the following code: string = "XxXxXx" print(string.lower()) print(string.upper()) How could I use a list instead along the lines of: string = "XxXxXx" list = [lower(), upper()] for i in list: print(string.i) Obviously the code above does not wo...
Iterating Through a List of Functions in Python
Let's say I have the following code: string = "XxXxXx" print(string.lower()) print(string.upper()) How could I use a list instead along the lines of: string = "XxXxXx" list = [lower(), upper()] for i in list: print(string.i) Obviously the code above does not work at all and the problem I'm working on is way more ...
[ "Functions (and methods) are first class objects in python. You can therefore store them in a list just like you would anything else.\nIf you want to be able to apply the functions to arbitrary strings, use the unbound function objects in the class:\nstring = \"XxXxXx\"\nfunc_list = [str.lower, str.upper]\nfor i in...
[ 1 ]
[]
[]
[ "methods", "python", "python_3.x", "string" ]
stackoverflow_0074296279_methods_python_python_3.x_string.txt
Q: Normalizing nested JSON in pandas I am trying to address a list of dictionaries inside a list of JSON dictionaries to produce a normalized table of its contents. One item from my JSON file: import pandas as pd file_json = [ { "id": 1, "type": "gin", "name": "1085 Toledo Gin", "f...
Normalizing nested JSON in pandas
I am trying to address a list of dictionaries inside a list of JSON dictionaries to produce a normalized table of its contents. One item from my JSON file: import pandas as pd file_json = [ { "id": 1, "type": "gin", "name": "1085 Toledo Gin", "first_name": null, "second_name"...
[ "If data contains the parsed Json from the question, you can try:\ndf = pd.DataFrame(data)\ndf[\"perfect_tonics\"] = df[\"perfect_tonics\"].str[\"data\"]\ndf[\"perfect_garnishes\"] = df[\"perfect_garnishes\"].str[\"data\"]\n\ndf = df.explode(\"perfect_tonics\").explode(\"perfect_garnishes\")\n\ndf = pd.concat(\n ...
[ 1 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074296260_json_pandas_python.txt
Q: Python: Use the "i" counter in while loop as digit for expressions This seems like it should be very simple but am not sure the proper syntax in Python. To streamline my code I want a while loop (or for loop if better) to cycle through 9 datasets and use the counter to call each file out using the counter as a way...
Python: Use the "i" counter in while loop as digit for expressions
This seems like it should be very simple but am not sure the proper syntax in Python. To streamline my code I want a while loop (or for loop if better) to cycle through 9 datasets and use the counter to call each file out using the counter as a way to call on correct file. I would like to use the "i" variable within th...
[ "Think of things in terms of lists.\ntemps = []\nfor name in ('113VW','113W6',...):\n temps.append( pd.read_excel(f\"/content/{name}.xlsx\") )\n\navg = []\nDelta = []\ndeltaT = []\nfor data in temps:\n avg.append(np.mean(np.array([data['CC_H='],data['CC_V=']]),axis=0) \n Delta.append(np.max(avg[-...
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074296105_pandas_python.txt
Q: Fedex API Python: Reference Tracking numbers do not exist The end goal is to use the Fedex API to read a spreadsheet of tracking numbers and then update their shipping status via the Fedex API The first step was to attempt to read the status of a tracking number via the API. To accomplish this is am following the...
Fedex API Python: Reference Tracking numbers do not exist
The end goal is to use the Fedex API to read a spreadsheet of tracking numbers and then update their shipping status via the Fedex API The first step was to attempt to read the status of a tracking number via the API. To accomplish this is am following the Track by Tracking Number documentation that Fedex has provided...
[ "I believe FedEx is only using 12-digit tracking numbers these days. Your number that doesn't work is 15 digits. As I recall, FedEx used to have 15-digit tracking numbers so perhaps the documentation you read is old.\nBTW, though your code uses the FedEx sandbox, it can work with real tracking numbers. I just tried...
[ 0 ]
[]
[]
[ "fedex", "python", "python_requests" ]
stackoverflow_0072324189_fedex_python_python_requests.txt
Q: Make every fields as optional with Pydantic I'm making an API with FastAPI and Pydantic. I would like to have some PATCH endpoints, where 1 or N fields of a record could be edited at once. Moreover, I would like the client to only pass the necessary fields in the payload. Example: class Item(BaseModel): name: ...
Make every fields as optional with Pydantic
I'm making an API with FastAPI and Pydantic. I would like to have some PATCH endpoints, where 1 or N fields of a record could be edited at once. Moreover, I would like the client to only pass the necessary fields in the payload. Example: class Item(BaseModel): name: str description: str price: float tax...
[ "Solution with metaclasses\nI've just come up with the following:\n\nclass AllOptional(pydantic.main.ModelMetaclass):\n def __new__(self, name, bases, namespaces, **kwargs):\n annotations = namespaces.get('__annotations__', {})\n for base in bases:\n annotations.update(base.__annotations...
[ 37, 6, 6, 2, 0, 0 ]
[]
[]
[ "fastapi", "pydantic", "python", "python_3.x" ]
stackoverflow_0067699451_fastapi_pydantic_python_python_3.x.txt
Q: Pandas: Replacing values with np.nan in Column A depending on value in column B I have a dataframe that looks something like this: wavelength normalized flux lof 0 5100.00 0.948305 1 1 5100.07 0.796783 1 2 5100.14 0.696425 1 3 5100.21 0.880586 1 4 5100.28 0.836257 1 ... ... ... ... 42...
Pandas: Replacing values with np.nan in Column A depending on value in column B
I have a dataframe that looks something like this: wavelength normalized flux lof 0 5100.00 0.948305 1 1 5100.07 0.796783 1 2 5100.14 0.696425 1 3 5100.21 0.880586 1 4 5100.28 0.836257 1 ... ... ... ... 4281 5399.67 1.076449 1 4282 5399.74 1.038198 1 4283 5399.81 1.004292 ...
[ "You can just assign\ndf.loc[df['lof']==-1,'flux'] = np.nan\n\n", "df['flux']=df['flux'].mask(df['lof'].eq(-1), np.nan)\ndf\n\n" ]
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074296385_pandas_python.txt
Q: Create new dataframe with JSON objects from another dataframe I have a dataframe that stores a JSON object in one column. I want to process the JSON object to create a new dataframe (different number and type of columns, and each row will generate n new rows from the JSON object). I wrote this logic below that app...
Create new dataframe with JSON objects from another dataframe
I have a dataframe that stores a JSON object in one column. I want to process the JSON object to create a new dataframe (different number and type of columns, and each row will generate n new rows from the JSON object). I wrote this logic below that appends a dictionary (row) to a list while iterating through the origi...
[ "To create a new dataframe using another dataframe with a column that contains JSON objects, one object per row, you can use different approaches depending on the library you are using. In this answer, we will show you two possible solutions: one using pandas and one using PySpark.\nSolution using pandas\nPandas is...
[ 2, 1 ]
[]
[]
[ "dataframe", "json", "pandas", "pyspark", "python" ]
stackoverflow_0074118717_dataframe_json_pandas_pyspark_python.txt
Q: why this code dont refresh the currently minute in real time? the code shows the result only when executed. in the next minute it doesn't update instead it is the same result as the first minute. all the best xP t=datetime.datetime.now() while True: nextminute=t.minute+1 print("next M %s" %nextminute) ...
why this code dont refresh the currently minute in real time?
the code shows the result only when executed. in the next minute it doesn't update instead it is the same result as the first minute. all the best xP t=datetime.datetime.now() while True: nextminute=t.minute+1 print("next M %s" %nextminute) print("M Curre %s" %t.minute) time.sleep(61) print("lo...
[ "This is because the value of the variable \"t\" is only set once before the while loop, meaning every time it is printed it will have the same value. To fix this you would need to put it inside the while loop so it is updated every minute, like so:\nwhile True:\n t=datetime.datetime.now()\n nextminute=t.minu...
[ 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074296343_datetime_python.txt
Q: python pynput handling keyboard i trying make one keyboard handle with this context: listener de keyboard and when f1 is pressed start ( press and release this keys: q w e ) and when f2 is pressed set the status to false for stoping the key press( q w e): from pynput.keyboard import Key, Listener STATUS = True d...
python pynput handling keyboard
i trying make one keyboard handle with this context: listener de keyboard and when f1 is pressed start ( press and release this keys: q w e ) and when f2 is pressed set the status to false for stoping the key press( q w e): from pynput.keyboard import Key, Listener STATUS = True def on_release(key): if key == Key...
[ "Before run the script try to connect to X server using this command\nxhost +\n\nFor example create a bash script (script.bash) like this\nDISPLAY=:0\nxhost +\npython3 yourscript.py\n\nThe run as\nbash script.bash\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0068785806_python_python_3.x.txt
Q: How do I create a tuple of tuple from a tuple of tuples and ints? I have a list of tuples and integers: [((0, 5), 8), ((0, 1), 10), ((1, 4), -4), ((1, 3), 2), ((1, 2), 1), ((2, 3), -2), ((3, 4), -1), ((4, 5), 1)] How would I go about converting something like that to a list of tuples in format: [(0, 5, 8), (0, 1,...
How do I create a tuple of tuple from a tuple of tuples and ints?
I have a list of tuples and integers: [((0, 5), 8), ((0, 1), 10), ((1, 4), -4), ((1, 3), 2), ((1, 2), 1), ((2, 3), -2), ((3, 4), -1), ((4, 5), 1)] How would I go about converting something like that to a list of tuples in format: [(0, 5, 8), (0, 1, 10), (1, 4, -4),..., (4, 5, 1)] I've tried edges = tuple(point for i i...
[ "Try:\nlst = [\n ((0, 5), 8),\n ((0, 1), 10),\n ((1, 4), -4),\n ((1, 3), 2),\n ((1, 2), 1),\n ((2, 3), -2),\n ((3, 4), -1),\n ((4, 5), 1),\n]\n\nout = [(a, b, c) for ((a, b), c) in lst]\nprint(out)\n\nPrints:\n[\n (0, 5, 8),\n (0, 1, 10),\n (1, 4, -4),\n (1, 3, 2),\n (1, 2, 1)...
[ 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0074296433_list_list_comprehension_python.txt
Q: Python pip - ignored .netrc and pip.conf files I want to install packages with pip and not be asked for the credentials and not to store credentials in pip.conf file This is something which is explained previously here Credentials in pip.conf for private PyPI So the steps I did. in /home/jenkins folder I create .n...
Python pip - ignored .netrc and pip.conf files
I want to install packages with pip and not be asked for the credentials and not to store credentials in pip.conf file This is something which is explained previously here Credentials in pip.conf for private PyPI So the steps I did. in /home/jenkins folder I create .netrc file: machine https://artifactory.domain.dev ...
[ "Have a look here where to place the pip.conf: https://pip.pypa.io/en/stable/topics/configuration/#location\nProbably you want to place it here: /home/jenkins/.config/pip/pip.conf\nI do believe that the .netrc should be directly in the home directory, but check that this file is owned by the user that is executing...
[ 1, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0072616685_pip_python.txt
Q: Python: why does x @ y.T not produce the same output as np.outer(x,y)? In python, if x,y are vectors, I expected x @ y.T to give me the outer product of x and y, i.e. to match the result of np.outer(x,y). However, to my surprise, x @ y.T returns a scalar. Why? Are vectors (i.e. one-dimensional arrays) not consi...
Python: why does x @ y.T not produce the same output as np.outer(x,y)?
In python, if x,y are vectors, I expected x @ y.T to give me the outer product of x and y, i.e. to match the result of np.outer(x,y). However, to my surprise, x @ y.T returns a scalar. Why? Are vectors (i.e. one-dimensional arrays) not considered to be column vectors by numpy? For example, the code import numpy as n...
[ "The @ takes the dot product, not the outer product.\nUsing the variables you defined in the code:\n>>> x=np.array([1,2])\n>>> y=np.array([3,4])\n>>> np.dot(x,y)\n11\n\nYou get 11, which is the dot product that was produced using '@'\nEDIT: update from discussion\nBased on this answer as well as digging through the...
[ 1, 0, 0 ]
[]
[]
[ "matrix_multiplication", "numpy", "outer_product", "python" ]
stackoverflow_0074295418_matrix_multiplication_numpy_outer_product_python.txt
Q: yfinance 1 minute bars have 0 volume for its newest bar I created an indicator in python that downloads historical data from yahoo using yfinance. Everything was working perfectly and then suddenly the newest row that gets downloaded for the tickers I use has 0 volume. This volume completely messes up the indicato...
yfinance 1 minute bars have 0 volume for its newest bar
I created an indicator in python that downloads historical data from yahoo using yfinance. Everything was working perfectly and then suddenly the newest row that gets downloaded for the tickers I use has 0 volume. This volume completely messes up the indicators I'm calculating, especially the swap. I know I can delete ...
[ "I believe yahoo finance gives value data only for daily or higher interval.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "python", "yahoo_finance", "yfinance" ]
stackoverflow_0071684726_dataframe_python_yahoo_finance_yfinance.txt
Q: RuntimeError: module compiled against API version a but this version of numpy is 9 Code: import numpy as np import cv Console: >>> runfile('/Users/isaiahnields/.spyder2/temp.py', wdir='/Users/isaiahnields/.spyder2') RuntimeError: module compiled against API version a but this version of numpy is 9 Traceback (most...
RuntimeError: module compiled against API version a but this version of numpy is 9
Code: import numpy as np import cv Console: >>> runfile('/Users/isaiahnields/.spyder2/temp.py', wdir='/Users/isaiahnields/.spyder2') RuntimeError: module compiled against API version a but this version of numpy is 9 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Applications/Spyder-Py2....
[ "Upgrade numpy to the latest version\npip install numpy --upgrade\n\n", "Check the path\nimport numpy\nprint numpy.__path__\n\nFor me this was /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy So I moved it to a temporary place\nsudo mv /System/Library/Frameworks/Python.framework/Ve...
[ 141, 15, 13, 4, 4, 3, 3, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "This works for me:\nMy pip is not work after upgrade, so the first thing I need to do is to fix it with\nsudo gedit /usr/bin/pip\n\nChange the line\nfrom pip import main\n\nto\nfrom pip._internal import main\n\nThen, \n sudo pip install -U numpy\n\n" ]
[ -2 ]
[ "numpy", "opencv", "python", "python_2.7" ]
stackoverflow_0033859531_numpy_opencv_python_python_2.7.txt
Q: number formatting, specific number of digits is there a way to print 6.5646961e-07 in this format 656e-09? I have tried this: x = 6.5646961e-07 print(f"{lamda_balmer:.2e}") which gives 6.56e-07 but I would like to have 656e-09 Is there a way to do this? I couldn't find anything on the internet. Thanks in advance...
number formatting, specific number of digits
is there a way to print 6.5646961e-07 in this format 656e-09? I have tried this: x = 6.5646961e-07 print(f"{lamda_balmer:.2e}") which gives 6.56e-07 but I would like to have 656e-09 Is there a way to do this? I couldn't find anything on the internet. Thanks in advance.
[ "As said in the comments By convention the \"e\" format only has one digit to the left of the decimal place, so it seems that there is no way around to write an own method printing the float in any other special \"e\" format.\nTry:\nx = 656.46961e-09\ndef print_with_shifted_exp(x, ffrmt='5.2f', efrmt='03d', shift=-...
[ 0 ]
[]
[]
[ "number_formatting", "numbers", "printing", "python" ]
stackoverflow_0074296267_number_formatting_numbers_printing_python.txt
Q: CanΒ΄t find python libraries when trying to run a script from a batch file I am trying to run a python script from a batch file but it does not manage to find my installed libraries, the error i get is following: And my batch file code looks like this: @echo off "C:\Users\juliu\AppData\Local\Programs\Python\Python...
CanΒ΄t find python libraries when trying to run a script from a batch file
I am trying to run a python script from a batch file but it does not manage to find my installed libraries, the error i get is following: And my batch file code looks like this: @echo off "C:\Users\juliu\AppData\Local\Programs\Python\Python310\python.exe" "C:\Users\juliu\Desktop\Evolo project\Website_scraper_system_2\...
[ "I typed the console command where python and changed the file location to that and it seems to work.\n" ]
[ 0 ]
[]
[]
[ "batch_file", "batch_processing", "python" ]
stackoverflow_0074295456_batch_file_batch_processing_python.txt
Q: Prevent pandas from interpreting 'NA' as NaN in a string The pandas read_csv() method interprets 'NA' as nan (not a number) instead of a valid string. In the simple case below note that the output in row 1, column 2 (zero based count) is 'nan' instead of 'NA'. sample.tsv (tab delimited) PDB CHAIN SP_PRIMARY ...
Prevent pandas from interpreting 'NA' as NaN in a string
The pandas read_csv() method interprets 'NA' as nan (not a number) instead of a valid string. In the simple case below note that the output in row 1, column 2 (zero based count) is 'nan' instead of 'NA'. sample.tsv (tab delimited) PDB CHAIN SP_PRIMARY RES_BEG RES_END PDB_BEG PDB_END SP_BEG SP_END 5d8b N P60...
[ "You could use parameters keep_default_na and na_values to set all NA values by hand docs:\nimport pandas as pd\nfrom io import StringIO\n\ndata = \"\"\"\nPDB CHAIN SP_PRIMARY RES_BEG RES_END PDB_BEG PDB_END SP_BEG SP_END\n5d8b N P60490 1 146 1 146 1 146\n5d8b NA P80377 _ 126 1 126 1 126\n5d8b O P60491 1 118 1 118 ...
[ 110, 66, 16, 5, 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0033952142_pandas_python.txt
Q: How to sort in non-increasing and lexicographical order in Python How do you sort in non-increasing order a list of team names and scores, and secondly in lexicographical order? I have the following line of Python that I am trying to understand. sigList.sort(key = lambda x : str(len(x)-1) + x[0], reverse= True) F...
How to sort in non-increasing and lexicographical order in Python
How do you sort in non-increasing order a list of team names and scores, and secondly in lexicographical order? I have the following line of Python that I am trying to understand. sigList.sort(key = lambda x : str(len(x)-1) + x[0], reverse= True) From my understanding, this sorts in non-increasing order, but not in le...
[ "Convert the string to a tuple with the fields you want to sort by in that order.\nTo get the highest score first, convert it to a negative number.\nsigList = ['BOB TEAM 9', 'KIM TEAM 3', 'DALE TEAM 7', 'FRED TEAM 3']\nsigList.sort(key = lambda x: (-int(x.split()[-1]), x.split()[:-1]))\nprint(sigList) # ['BOB TEAM ...
[ 0 ]
[]
[]
[ "lexicographic", "python", "sorting" ]
stackoverflow_0074296458_lexicographic_python_sorting.txt
Q: How to make dictionary of column names in PySpark? I am receiving files and for some files columns are named differently. For example: In file 1, column names are: "studentID" , "ADDRESS", "Phone_number". In file 2, column names are: "Common_ID", "Common_Address", "Mobile_number". In file 3, column names are: "S_...
How to make dictionary of column names in PySpark?
I am receiving files and for some files columns are named differently. For example: In file 1, column names are: "studentID" , "ADDRESS", "Phone_number". In file 2, column names are: "Common_ID", "Common_Address", "Mobile_number". In file 3, column names are: "S_StudentID", "S_ADDRESS", "HOME_MOBILE". I want to pass ...
[ "You can have the dictionary as you want and use toDF with a list comprehension in order to rename the columns.\nInput dataframe and column names:\nfrom pyspark.sql import functions as F\n\ndf = spark.createDataFrame([], 'Common_ID string, ADDRESS string, COL3 string')\nprint(df.columns)\n# ['Common_ID', 'ADDRESS',...
[ 1, 1 ]
[]
[]
[ "apache_spark", "dataframe", "dictionary", "pyspark", "python" ]
stackoverflow_0074293003_apache_spark_dataframe_dictionary_pyspark_python.txt
Q: How to write codes from three .py files into one I have 3 .py files that splits a video into frames, apply saliency to those frames and then combine those frames into a video. I would like to have a single .py file that does all the above, instead of running three separate files. I have provided the codes below. 1...
How to write codes from three .py files into one
I have 3 .py files that splits a video into frames, apply saliency to those frames and then combine those frames into a video. I would like to have a single .py file that does all the above, instead of running three separate files. I have provided the codes below. 1. Spliting video.py import cv2 capture = cv2.VideoCa...
[ "Following is the beginning of the combination.\nimport cv2\nfrom glob import glob\nimport os\n\n# globals\ncapture = cv2.VideoCapture('vids/tm_test.mp4')\nsaliency = cv2.saliency.StaticSaliencyFineGrained_create()\nfps = capture.get(cv2.CAP_PROP_FPS)\nsource = r'Output/*.jpg'\npath_to_save = 'images/'\nframeNr = 0...
[ 1 ]
[]
[]
[ "image_processing", "opencv", "python", "video_processing" ]
stackoverflow_0074296466_image_processing_opencv_python_video_processing.txt
Q: python; create file on remote server with variable file name Using the paramiko library in python im trying to touch a file on remote location and able to do so using below code.. ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=serverna...
python; create file on remote server with variable file name
Using the paramiko library in python im trying to touch a file on remote location and able to do so using below code.. ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=servername,username=usr,password=pass) cmd = "touch /home/test/file.txt" s...
[ "This should work:\nimport os\nimport paramiko\n\nssh_client = paramiko.SSHClient()\nssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nssh_client.connect(hostname=servername,username=usr,password=pass)\n\nname_of_file = \"Test.txt\"\n\npath_to_file = os.path.join('/home/test/', name_of_file)\n\ncmd ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0069663005_python.txt
Q: Polars Selecting all columns without NaNs I have a dataframe where a number of the columns only consists of NaNs. I am trying to select only the columns in the dataframe where all the values are not equal to NaNs using Polars. I have tried seeing if I could use a similar syntax to how I would proceed in Pandas e.g...
Polars Selecting all columns without NaNs
I have a dataframe where a number of the columns only consists of NaNs. I am trying to select only the columns in the dataframe where all the values are not equal to NaNs using Polars. I have tried seeing if I could use a similar syntax to how I would proceed in Pandas e.g. df[df.columns[~df.is_null().all()]] However ...
[ "So this is basically subsetting columns with a boolean mask.\nSo first let's create some sample data:\nimport polars as pl\nimport numpy as np\n\ndf = pl.DataFrame(\n {\"a\": [np.nan, np.nan, np.nan, np.nan],\n \"b\": [3,4, np.nan, 5], \n \"c\": [np.nan, np.nan, np.nan, np.nan]\n})\n\nNext we have to get ...
[ 1 ]
[]
[]
[ "pandas", "python", "python_polars" ]
stackoverflow_0074295124_pandas_python_python_polars.txt
Q: How to program a task with a timer in my Python code? I want to execute a task after certain time, so I have tried a countdown timer with a condition of being finished (when countdown variable = 0, the task is performed). The thing is that I don't want to stop the execution of the main program while performing the...
How to program a task with a timer in my Python code?
I want to execute a task after certain time, so I have tried a countdown timer with a condition of being finished (when countdown variable = 0, the task is performed). The thing is that I don't want to stop the execution of the main program while performing the countdown. I have tried this: import time def countdown(n...
[ "Another alternative is by using threading.\nI've got a simple example here with 2 Threads where the working thread is waiting for the countdown thread to finish and starting. The Main is still working fine.\nimport threading\nimport time\n\n\ndef do_something():\n countdown_thread.join()\n print(\"Starting T...
[ 1, 0, 0 ]
[]
[]
[ "countdown", "python", "sleep", "timer" ]
stackoverflow_0072697002_countdown_python_sleep_timer.txt
Q: Django Channels Error - Cannot import BACKEND 'asgi_redis.RedisChannelLayer' I have installed Django-Channels but while running the daphne-server I am getting this error given below: File "/usr/local/lib/python2.7/dist-packages/channels/asgi.py", line 36, in make_backend "Cannot import BACKEND %r specified for %s"...
Django Channels Error - Cannot import BACKEND 'asgi_redis.RedisChannelLayer'
I have installed Django-Channels but while running the daphne-server I am getting this error given below: File "/usr/local/lib/python2.7/dist-packages/channels/asgi.py", line 36, in make_backend "Cannot import BACKEND %r specified for %s" % (self.configs[name]['BACKEND'], name) channels.asgi.InvalidChannelLayerError: ...
[ "In regard to Utkarsh's reply itt's been renamed to:\npip install channels-redis\n\n", "Just needed to install 'asgi_redis'. I was assuming that it would have gotten installed by default while installing Django-Channels, but it doesn't. 'asgiref' gets installed by default and not 'asgi_redis'. So to solve this is...
[ 21, 13, 7, 6, 2, 0, 0, 0 ]
[]
[]
[ "django", "django_channels", "python", "redis" ]
stackoverflow_0037342571_django_django_channels_python_redis.txt
Q: Attribute Error:'NoneType' Object has no attribute 'is_active' in Flask Python Web App Here is the complete error, i have played around with some of the other tabs on this Github, techwithtim- flask web app tutorial around this issue and have not found success being able to sign up a new user. I have tried to add ...
Attribute Error:'NoneType' Object has no attribute 'is_active' in Flask Python Web App
Here is the complete error, i have played around with some of the other tabs on this Github, techwithtim- flask web app tutorial around this issue and have not found success being able to sign up a new user. I have tried to add login_user(user, remember=True) login_user(new_user, remember=True) with no success and trie...
[ "From the comments, the solution was to comment out (or delete) the line\n login_user(user, remember=True)\n\nfrom the sign_up method.\nThis method contains the following code, which I have abbreviated:\n user = User.query.filter_by(email=email).first()\n if user:\n flash('Email ...
[ 0 ]
[]
[]
[ "flask", "flask_login", "python" ]
stackoverflow_0074268816_flask_flask_login_python.txt
Q: Extract string/characters before a number using regex I would like to extract everything that comes before a number using regex. The dataframe below shows an example of what I want to do. I want to extract everything that comes before the first number in the product_name column. The output column is what I want t...
Extract string/characters before a number using regex
I would like to extract everything that comes before a number using regex. The dataframe below shows an example of what I want to do. I want to extract everything that comes before the first number in the product_name column. The output column is what I want to get. Thank you in advance! product_name = ['Cashew Alm Cl...
[ "I might use an str.replace approach here:\ndf[\"output\"] = df[\"product_name\"].str.replace(r'\\s+\\d+/\\d+\\w*g$', '', regex=True)\n\nThis has a slight advantage over using str.extract in that it doesn't require us assuming what content we want to keep. Rather it just specifies to remove any possible units term...
[ 2, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074296626_pandas_python.txt
Q: Concatenate columns of a panda frame into a 1D array I have a pd dataframe consisting of hundreds of columns. I want to contenate all the columns into a 1D array. For instance, supppose the dataframe is something like this: pd df: set1 set2 set3 ... set175 3 5 6 ... 9 4 8 0 ... 22 . ...
Concatenate columns of a panda frame into a 1D array
I have a pd dataframe consisting of hundreds of columns. I want to contenate all the columns into a 1D array. For instance, supppose the dataframe is something like this: pd df: set1 set2 set3 ... set175 3 5 6 ... 9 4 8 0 ... 22 . . . ... . . . . ... . And, I want...
[ "# stack and take the values\n\n# choosing all columns and rows\ndf.T.stack().values\n\narray([3, 4, 5, 8, 6, 0, '...', '...', 9, 22], dtype=object)\n\n# choosing only two columns\ndf.T.iloc[:,1:3].stack().values\n\narray([4, 8, 0, '...', 22], dtype=object)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074296642_dataframe_pandas_python.txt
Q: Downsampling geospatial xarrays too large for memory I have a very large (86400x43200) xarray dataset with geospatial coordinates (lat, lon) and elevation and would like to downsize this map to have one twentieth the resolution per dimension (4320, 2160, which is equivalent to 1/12th degree). I at first used the i...
Downsampling geospatial xarrays too large for memory
I have a very large (86400x43200) xarray dataset with geospatial coordinates (lat, lon) and elevation and would like to downsize this map to have one twentieth the resolution per dimension (4320, 2160, which is equivalent to 1/12th degree). I at first used the interp method directly, but it tries to load the whole data...
[ "I'd recommend using dask in combination with xr.DataArray.coarsen.\nStart by chunking the data on read with a chunking scheme in multiples of your coarsening window (so multiples of 20 on each dim), targeting chunk sizes in the low 100s of MBs. Chunks of (8640 x 4320) float64 data are 285MB, and then would reduce ...
[ 2 ]
[]
[]
[ "geospatial", "interpolation", "python", "python_xarray" ]
stackoverflow_0074296467_geospatial_interpolation_python_python_xarray.txt
Q: speedtest-cli works in console, but not as script I am trying to use the speedtest-cli api. Copied part of the code from official wiki (and removed unused stuff): import speedtest s = speedtest.Speedtest() s.get_best_server() s.download() In python console I get everything ok: >>> import speedtest >>> s = speedte...
speedtest-cli works in console, but not as script
I am trying to use the speedtest-cli api. Copied part of the code from official wiki (and removed unused stuff): import speedtest s = speedtest.Speedtest() s.get_best_server() s.download() In python console I get everything ok: >>> import speedtest >>> s = speedtest.Speedtest() >>> s.get_best_server() {HIDDEN} >>> s.d...
[ "As mentioned in the comments, you have a file with the same name and it is conflicting with the import. Since you have moved the file, restarting the console should work.\nThe code below will also extract the results into a dictionary and make it possible to access the results. \nimport speedtest\ns = speedtest.Sp...
[ 8, 1, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x", "speed_test" ]
stackoverflow_0051854444_python_python_3.x_speed_test.txt
Q: Dunder methods for sets and dicts If I created sets and dictionaries in Python that behave identically, I would need to create my own implementations for the __or__ method, but what about the other ones? For example, would I really need to implement __ror__ and __ior__? A: If you're only working with pairs of yo...
Dunder methods for sets and dicts
If I created sets and dictionaries in Python that behave identically, I would need to create my own implementations for the __or__ method, but what about the other ones? For example, would I really need to implement __ror__ and __ior__?
[ "If you're only working with pairs of your own custom type, or the left-hand operand will always be your custom type and the right-hand type will be a type it knows how to work with, and you don't need in-place mutations, then __or__ would be enough.\nYou need __ror__ if it's possible that someone will do a_real_se...
[ 1 ]
[]
[]
[ "magic_methods", "python" ]
stackoverflow_0074296717_magic_methods_python.txt
Q: Python Numpy: Random Seed num= 100 obs=[] np.random.seed(1) for i in range(num): N=[] CF3_1=[] CF3_2=[] i=2 salvage= np.random.triangular(salvage_min, salvage_mode, salvage_max) inv= np.random.uniform(inv_min, inv_max) for y in range(0,5): gt= 14.747101 + 11.664259 * np.random.beta(0.6...
Python Numpy: Random Seed
num= 100 obs=[] np.random.seed(1) for i in range(num): N=[] CF3_1=[] CF3_2=[] i=2 salvage= np.random.triangular(salvage_min, salvage_mode, salvage_max) inv= np.random.uniform(inv_min, inv_max) for y in range(0,5): gt= 14.747101 + 11.664259 * np.random.beta(0.645868, 0.920589) print(gt) ...
[ "This is to be expected. np.random.triangular and np.random.uniform each consume a random double (64 bits), while np.random.beta consumes two doubles; see source.\nSo after you reset the seed, calling np.random.triangular and np.random.uniform once each will consume two doubles, which means the values returned by ...
[ 1 ]
[]
[]
[ "numpy", "python", "random" ]
stackoverflow_0074296527_numpy_python_random.txt
Q: Apply groupby on multiple columns while taking aggregate in Python I wish to apply a groupby to multiple columns while running an aggregate function. Data country type en start Japan aa 25 8/1/2022 Japan cc 1 9/1/2022 US bb 5 8/1/2022 US bb 5 8/1/2022 ...
Apply groupby on multiple columns while taking aggregate in Python
I wish to apply a groupby to multiple columns while running an aggregate function. Data country type en start Japan aa 25 8/1/2022 Japan cc 1 9/1/2022 US bb 5 8/1/2022 US bb 5 8/1/2022 Desired country type en start Ja...
[ "out=df.groupby(['country','type','start'], as_index=False).agg({'en': sum})\nout\n\ncountry type start en\n0 Japan aa 8/1/2022 25\n1 Japan cc 9/1/2022 1\n2 US bb 8/1/2022 10\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074296720_numpy_pandas_python.txt
Q: Converting dataframe to TimeSeries in Python is giving Invalid type of `time_col` error I am writing Python code in Kaggle. The csv file has 8 columns in which column 0 is 'date' and column1 is 'stringency_index' series = pd.read_csv("<csv path>", na_values=['nan','?'], parse_dates = ...
Converting dataframe to TimeSeries in Python is giving Invalid type of `time_col` error
I am writing Python code in Kaggle. The csv file has 8 columns in which column 0 is 'date' and column1 is 'stringency_index' series = pd.read_csv("<csv path>", na_values=['nan','?'], parse_dates = ['date']) series1 = series.iloc[:, [0,1]] series1 Some of the rows of series1 are: ...
[ "Referring to the API doc, the first argument is the DataFrame, the second argument is the name of the time column, and the third is the name(s) of the value column(s). From the shape of your data, it looks like you should call\nTimeSeries.from_dataframe(series1, time_col='date', value_cols='stringency_index')\n\n"...
[ 0, 0 ]
[]
[]
[ "data_science", "python", "time_series" ]
stackoverflow_0071796390_data_science_python_time_series.txt
Q: How to map nearest values from a dataframe to numpy array efficiently I have created a dataframe with a a column for codes and another for discrete values. I have a numpy array with some experimental values. How do i create a numpy array of codes that are associated to the nearest value defined in the dataframe. ...
How to map nearest values from a dataframe to numpy array efficiently
I have created a dataframe with a a column for codes and another for discrete values. I have a numpy array with some experimental values. How do i create a numpy array of codes that are associated to the nearest value defined in the dataframe. The dataframe that defines the mapping between the codes and values doesn't...
[ "Don't create codes as a list of arrays of manual values; use a reshaped arange.\nDon't create values manually; also use arange.\nAvoid holding inner lists; expand your \"code\" to multiple columns and then an additional dimension in your output array.\nAnd yes, don't loop. Numpy doesn't have anything for this kind...
[ 0 ]
[]
[]
[ "mapping", "numpy", "pandas", "python", "vectorization" ]
stackoverflow_0074294674_mapping_numpy_pandas_python_vectorization.txt
Q: Drake Error: Maximum number of clients reached bad X server connection vtkXOpenGLRenderWindow I am generating new multibody plants in a for loop in my project. If I run it for large number of times, my program crashes with the error: Maximum number of clients reached bad X server connection vtkXOpenGLRenderWindow ...
Drake Error: Maximum number of clients reached bad X server connection vtkXOpenGLRenderWindow
I am generating new multibody plants in a for loop in my project. If I run it for large number of times, my program crashes with the error: Maximum number of clients reached bad X server connection vtkXOpenGLRenderWindow I think the error is in here: scene_graph.AddRenderer(renderer_name, MakeRenderEngineVtk(RenderEng...
[ "Short answer: You can't remove renderers from SceneGraph. Probably a defect that should be addressed.\nLonger answer:\n\nIt's not just copies of SceneGraph that have registered renderers, you also get a copy in each Context that gets allocated. So, number of scene graphs + number of contexts is how many OpenGl con...
[ 1 ]
[]
[]
[ "drake", "python", "renderer", "vtk" ]
stackoverflow_0074295329_drake_python_renderer_vtk.txt
Q: How to interpret explained variance ratio plot from principal components of PCA with sklearn I try to use PCA to reduce the dimension of my data before applying K-means clustering. In the below dataset, I have points, assists and rebounds columns. According to the plot, the first three principal component contains...
How to interpret explained variance ratio plot from principal components of PCA with sklearn
I try to use PCA to reduce the dimension of my data before applying K-means clustering. In the below dataset, I have points, assists and rebounds columns. According to the plot, the first three principal component contains the highest % of the variance. Is there a way to tell what each of the first 3 components corresp...
[ "The PCs are just a new set of axes.\nImagine x, y axes and a cloud of points shaped like an ellipse with the long axis of the ellipse at 45 degrees to the original axes.\nThe first PC will correspond to the long axis. The second and subsequent ones will each be at right angles to the previous ones. The second PC w...
[ 3, 2 ]
[]
[]
[ "pca", "python", "scikit_learn" ]
stackoverflow_0074296474_pca_python_scikit_learn.txt
Q: How do I stop the result from exceeding 25? def multiplication_table(number): multiplier = 1 while multiplier <= 5: result = ___ if ___ : break print(str(number) + "x" + str(multiplier) + "=" + str(result)) ___ += 1 multiplication_table(3) multiplication_tabl...
How do I stop the result from exceeding 25?
def multiplication_table(number): multiplier = 1 while multiplier <= 5: result = ___ if ___ : break print(str(number) + "x" + str(multiplier) + "=" + str(result)) ___ += 1 multiplication_table(3) multiplication_table(5) multiplication_table(8) I'm supposed to ...
[ "I want to preface my answer with the fact that your question is not perfectly clear. Before you provide any code snippets or any attempted solutions, you should first fully define the problem and explain what an acceptable answer entails. Anyway, I will address each of your three attempts:\n\nYou have chosen to br...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074296658_python.txt
Q: How to check each column for value greater than and accept if 3 out of 5 columns has that value I am trying to make a article similarity checker by comparing 6 articles with list of articles that I obtained from an API. I have used cosine similarity to compare each article one by one with the 6 articles that I am ...
How to check each column for value greater than and accept if 3 out of 5 columns has that value
I am trying to make a article similarity checker by comparing 6 articles with list of articles that I obtained from an API. I have used cosine similarity to compare each article one by one with the 6 articles that I am using as baseline. My dataframe now looks like this: id Article cosinesin1 cosinesin2 cosinesin3 ...
[ "In Python, you can treat True and False as integers, 1 and 0, respectively.\nSo if you compare all the similarity metrics to 0.5, you can sum over the resulting Boolean DataFrame along the columns, to get the number of comparisons that resulted in True for each row. Comparing those numbers to 3 yields the column y...
[ 0 ]
[]
[]
[ "cosine_similarity", "numpy", "pandas", "python" ]
stackoverflow_0074296695_cosine_similarity_numpy_pandas_python.txt
Q: How do I use a python dictionary for placing tiles in pygame? for blocks in TileGroup: TileDict=[] lmb,rmb = pygame.mouse.get_pressed()[0],pygame.mouse.get_pressed()[2] mouse_x, mouse_y = pygame.mouse.get_pos() mouse_hover = blocks.rect.collidepoint(mouse_x,mouse_y) if...
How do I use a python dictionary for placing tiles in pygame?
for blocks in TileGroup: TileDict=[] lmb,rmb = pygame.mouse.get_pressed()[0],pygame.mouse.get_pressed()[2] mouse_x, mouse_y = pygame.mouse.get_pos() mouse_hover = blocks.rect.collidepoint(mouse_x,mouse_y) if lmb: if mouse_hover: blocks.kill() ...
[ "\"\"\"\nWithout having more code, I have an initial suggestion, move TileDict =[]\nout of the loop it is being initialized each pass through the loop.\n\"\"\"\nTileDict = []\nfor blocks in TileGroup:\n lmb, rmb = pygame.mouse.get_pressed()[0], pygame.mouse.get_pressed()[2]\n mouse_x, mouse_y = pygame.mouse.g...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074296707_pygame_python.txt
Q: Docker : exec /usr/bin/sh: exec format error Hi guys need some help. I created a custom docker image and push it to docker hub but when I run it in CI/CD it gives me this error. exec /usr/bin/sh: exec format error Where : Dockerfile FROM ubuntu:20.04 RUN apt-get update RUN apt-get install -y software-properties-co...
Docker : exec /usr/bin/sh: exec format error
Hi guys need some help. I created a custom docker image and push it to docker hub but when I run it in CI/CD it gives me this error. exec /usr/bin/sh: exec format error Where : Dockerfile FROM ubuntu:20.04 RUN apt-get update RUN apt-get install -y software-properties-common RUN apt-get install -y python3-pip RUN pip3 i...
[ "The problem is that you built this image for arm64/v8 -- but your runner is using a different architecture.\nIf you run:\ndocker image inspect rethkevin/rf:v1\n\nYou will see this in the output:\n...\n \"Architecture\": \"arm64\",\n \"Variant\": \"v8\",\n \"Os\": \"linux\",\n...\n\nTry buildin...
[ 12, 3 ]
[]
[]
[ "docker", "dockerhub", "gitlab", "python", "robotframework" ]
stackoverflow_0073285601_docker_dockerhub_gitlab_python_robotframework.txt
Q: How do I make matplotlib work in AWS EMR Jupyter notebook? This is very close to this question, but I have added a few details specific to my question: Matplotlib Plotting using AWS-EMR jupyter notebook I would like to find a way to use matplotlib inside my Jupyter notebook. Here is the code-snippet in error, it's...
How do I make matplotlib work in AWS EMR Jupyter notebook?
This is very close to this question, but I have added a few details specific to my question: Matplotlib Plotting using AWS-EMR jupyter notebook I would like to find a way to use matplotlib inside my Jupyter notebook. Here is the code-snippet in error, it's fairly simple: notebook import matplotlib matplotlib.use("agg")...
[ "The answer by @00schneider actually works.\nimport matplotlib.pyplot as plt\n\n# plot data here\nplt.show()\n\nafter \n\nplt.show()\n\nre-run the magic cell that contains the below, and you will see a plot on your AWS EMR Jupyter PySpark notebook\n%matplot plt\n\n", "As you mentioned, matplotlib is not installed...
[ 9, 8, 3, 2, 1, 1 ]
[ "Try below code. FYI we have matplotlib 3.1.1 installed in Python3.6 on emr-5.26.0 and i used PySpark Kernel.\nMake sure that \"%matplotlib inline\" is first line in cell \n%matplotlib inline\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nplt.plot([1,2,3,4])\nplt.show()\n\n" ]
[ -1 ]
[ "amazon_emr", "jupyter_notebook", "matplotlib", "pyspark", "python" ]
stackoverflow_0056264957_amazon_emr_jupyter_notebook_matplotlib_pyspark_python.txt
Q: Python cannot find Boost.Python module I try to create a simple C++ module for python with Boost, but python gives me ModuleNotFoundError: No module named 'MyLib'. The .py file is in the same location as MyLib.dll. UPD: if i change dll to pyd or replace add_library(MyLib MODULE MyLib.cpp) with PYTHON_ADD_MODULE(My...
Python cannot find Boost.Python module
I try to create a simple C++ module for python with Boost, but python gives me ModuleNotFoundError: No module named 'MyLib'. The .py file is in the same location as MyLib.dll. UPD: if i change dll to pyd or replace add_library(MyLib MODULE MyLib.cpp) with PYTHON_ADD_MODULE(MyLib MyLib.cpp) I get another error: ImportEr...
[ "You mention that your binary module is named MyLib.dll. That is the first problem.[1], [2]\nOn Windows, CPython expects binary modules to have extension .pyd.\nEither rename the DLL manually, or (as you mention) use PYTHON_ADD_MODULE instead of add_library to achieve the same automatically.\nOnce you do this, anot...
[ 1 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0074291350_boost_boost_python_c++_python.txt
Q: Infinite POST request on uploading file with Django I try to upload some files to a server through a web interface with Django. HTML : <form method="post" enctype="multipart/form-data" name="upload_file"> {% csrf_token %} <input type="file" name="uploaded_file_list" multiple> <button class="rounded-ful...
Infinite POST request on uploading file with Django
I try to upload some files to a server through a web interface with Django. HTML : <form method="post" enctype="multipart/form-data" name="upload_file"> {% csrf_token %} <input type="file" name="uploaded_file_list" multiple> <button class="rounded-full bg-violet-200 text-violet-700 block p-2" name="upload_f...
[ "According to docs:\n\nyou should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn’t specific to Django; it’s good web development practice in general.\n\nSo the view should be like this:\ndef media_manager(request):\n file_manager = MediaManager.server.FileManager(dj...
[ 1 ]
[]
[]
[ "django", "django_file_upload", "django_templates", "django_views", "python" ]
stackoverflow_0074296115_django_django_file_upload_django_templates_django_views_python.txt
Q: How to enter multiple numpy arrays to a function and return multiple outputs For example, the following works fine: import numpy as np time = np.linspace(0, 3, 4) func = lambda x : x print(func(time)) >>> [0, 1, 2, 3] I want to do the equivalent for functions that take vectors as an input. For example, I want th...
How to enter multiple numpy arrays to a function and return multiple outputs
For example, the following works fine: import numpy as np time = np.linspace(0, 3, 4) func = lambda x : x print(func(time)) >>> [0, 1, 2, 3] I want to do the equivalent for functions that take vectors as an input. For example, I want the following to happen: inps = np.array([[1, 2], [3, 4], [5, 6]]) sum_func = lambda...
[ "Numpy includes tons of functions to manipulate numpy arrays. You should be aware of the documentation. Here is the list of just the mathematical functions.\nThe sum function will come in handy here since we want to sum each row:\nimport numpy as np\n\ninps = np.array([[1, 2], [3, 4], [5, 6]])\nsum_func = lambda x ...
[ 0 ]
[]
[]
[ "arrays", "function", "numpy", "python" ]
stackoverflow_0074296892_arrays_function_numpy_python.txt
Q: How to remove \n and empty string in a column in a dataframe? I have a data frame and one column consists of list value. I have attached the picture in excel format and data frame as well. column "[ ""Hello"" ]" "[ ""Hello"", ""Hi"" ]" "[ ""Hello"", ""Hi"", """" ]" "[ """", ""Hello"", ""Hi"" ]" "[ ""Hello""...
How to remove \n and empty string in a column in a dataframe?
I have a data frame and one column consists of list value. I have attached the picture in excel format and data frame as well. column "[ ""Hello"" ]" "[ ""Hello"", ""Hi"" ]" "[ ""Hello"", ""Hi"", """" ]" "[ """", ""Hello"", ""Hi"" ]" "[ ""Hello"", """" ]" "[ """", ""Hello"" ]" 1][1]The column value looks like ...
[ "I'm not sure how to handle the input data that you have because that is not correctly formatted Python. However, I think there are a couple of ways to solve the problem.\nInput data (as correct Python)\ncolumn = [\n ['\\n \"Hello\" \\n'],\n ['\\n \"Hello\"', '\\n \"Hi\"\\n'],\n ['\\n \"Hello\"',' \\n \"Hi...
[ 0 ]
[]
[]
[ "data_science_experience", "dataframe", "list", "pandas", "python" ]
stackoverflow_0074296739_data_science_experience_dataframe_list_pandas_python.txt
Q: Cannot Scrap li and put result in dict in BS I'm trying to scrape li elements and add results to a dictionary so that my code always get what is inside li and finally I'll be creating df from this dictionary. my code : link = 'https://www.propertyfinder.eg/en/plp/rent/apartment-for-rent-cairo-hay-el-maadi-degla-st...
Cannot Scrap li and put result in dict in BS
I'm trying to scrape li elements and add results to a dictionary so that my code always get what is inside li and finally I'll be creating df from this dictionary. my code : link = 'https://www.propertyfinder.eg/en/plp/rent/apartment-for-rent-cairo-hay-el-maadi-degla-street-207-3455087.html' r = requests.get(link , hea...
[ "You need to get the specific elements that contain the keys and values you want to put into the dictionary. The keys are in the <span> elements, and the values are in <div class=\"property-facts__value\">.\nYou can use a dictionary comprehension to create the dictionary directly, instead of using a list comprehens...
[ 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074296874_python_web_scraping.txt
Q: I can't fix the accents I am having problems with a code created in python, and it is that when I generate some texts in json the accents are not appreciated This is my code that I am using... import requests url = requests.get(f"https://images.habbo.com/habbo-web-news/es/production/front.json") resumen = url.j...
I can't fix the accents
I am having problems with a code created in python, and it is that when I generate some texts in json the accents are not appreciated This is my code that I am using... import requests url = requests.get(f"https://images.habbo.com/habbo-web-news/es/production/front.json") resumen = url.json()[0]['summary'] print(re...
[ "Hope this helps:\nimport html\nimport requests\n\nurl = requests.get(\n f\"https://images.habbo.com/habbo-web-news/es/production/front.json\")\n\ncontent = url.json()\n\nsummary = content[0][\"summary\"]\n\ndecoded = html.unescape(summary)\n\nprint (decoded)\n\n" ]
[ 0 ]
[ "Maybe it has to do with the encoding, please refer to the request documentation in the response content section. The \"content\" key on the json files have a strange format to be spanish, tho.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074296987_python.txt
Q: Why scrapy "FEEDS" not saving the output file? The purpose of this scrapy spider is to check the response status of a bunch of websites. I'm also trying to build a simple desktop GUI app using python tkinter for this spider as an experiment. This app is scraping as I needed but it is not saving the output in a fil...
Why scrapy "FEEDS" not saving the output file?
The purpose of this scrapy spider is to check the response status of a bunch of websites. I'm also trying to build a simple desktop GUI app using python tkinter for this spider as an experiment. This app is scraping as I needed but it is not saving the output in a file. I have asked this question previously but this ti...
[ "There is something wrong with your chosen_feeds variable. I couldn't get your app to work it kept showing a messagebox that I had to fill in all the values even though they were filled.\nBut I was able to get it to work once I commented out a bunch of stuff and set the hardcoded the chosen_feeds variable to json a...
[ 1 ]
[]
[]
[ "python", "scrapy", "tkinter" ]
stackoverflow_0074294691_python_scrapy_tkinter.txt
Q: List in a function I am making a text adventure game: #modules import time import random #setup class hero: def __init__(self, name, health, attack, defence): self.name = Hname self.health = Hhealth self.attack = Hattack self.defence = Hdefence def start(): #name print...
List in a function
I am making a text adventure game: #modules import time import random #setup class hero: def __init__(self, name, health, attack, defence): self.name = Hname self.health = Hhealth self.attack = Hattack self.defence = Hdefence def start(): #name print("welcome, hero." , end=...
[ "You can't access variables in a function like that. The function needs to return the value.\ndef start():\n #name\n print(\"welcome, hero.\" , end='')\n time.sleep(0.3)\n Hname = input(\" And what shall I call you? \")\n print(\"What an amazing name\", Hname+\"!\")\n time.sleep(1)\n print(\"Le...
[ 0 ]
[]
[]
[ "function", "game_development", "list", "python", "python_3.x" ]
stackoverflow_0074296983_function_game_development_list_python_python_3.x.txt
Q: Python3.8 assignment expressions, use in list comprehension or as an expression I recently discovered that assignment expressions exist. And I wanted to refactor some of my code to make use of them. Most of the places I wanted to use it were relatively straightforward to convert. However, I'm not sure of the syn...
Python3.8 assignment expressions, use in list comprehension or as an expression
I recently discovered that assignment expressions exist. And I wanted to refactor some of my code to make use of them. Most of the places I wanted to use it were relatively straightforward to convert. However, I'm not sure of the syntax to use for this particular function. Is there a way I could replace my usage of f...
[ "You don't need assignment expressions here, see this simple list comprehension:\n[sum(i)/len(i) for i in zip(*l)]\n\nexample:\n# input\nl = [[1,2,3], [4,5,6]]\n\n# output\n[2.5, 3.5, 4.5]\n\n", "I just discovered it too, and I must admit it opens new gates to comprehensions and generator expressions (Love it ;-)...
[ 2, 1 ]
[]
[]
[ "python", "python_assignment_expression" ]
stackoverflow_0069402362_python_python_assignment_expression.txt
Q: Django: Catching Integrity Error and showing a customized message using template In my django powered app there is only one obvious case where "IntegrityError" can arise. So, how can I catch that error and display a message using templates? A: Just use try and catch. from django.db import IntegrityError from dja...
Django: Catching Integrity Error and showing a customized message using template
In my django powered app there is only one obvious case where "IntegrityError" can arise. So, how can I catch that error and display a message using templates?
[ "Just use try and catch.\nfrom django.db import IntegrityError\nfrom django.shortcuts import render_to_response\n\ntry:\n # code that produces error\nexcept IntegrityError as e:\n return render_to_response(\"template.html\", {\"message\": e.message})\n\nIf you want you can use the message in your template.\nE...
[ 185, 14, 3, 3, 2, 0, 0 ]
[ "Just import IntegrityError \nfrom django.db import IntegrityError\n\nand use it inside try/Except\ntry:\n //Do what is needed to be done\n except IntegrityError as e:\n //return what is supposed to be returned\n\nThanks @Soren I just Edited my answer\n" ]
[ -3 ]
[ "django", "python" ]
stackoverflow_0011293380_django_python.txt
Q: The command '/bin/sh -c apt-get update' returned a non-zero code: 100 in docker file My DockerFile as follows: FROM python:3.6 RUN wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | apt-key add - RUN echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | tee /...
The command '/bin/sh -c apt-get update' returned a non-zero code: 100 in docker file
My DockerFile as follows: FROM python:3.6 RUN wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | apt-key add - RUN echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.2.list RUN apt-get update RUN apt-get install -y mong...
[ "I have had this already twice. It vanishes when I put the version a step higher. That would mean a change for you from\nFROM python:3.6\nto\nFROM python:3.7\n(to start with). See The command '/bin/sh -c apt-get update' returned a non-zero code: 100\" in a simple Ubuntu12.04 Dockerfile - Ask Ubuntu.\n" ]
[ 0 ]
[]
[]
[ "docker", "dockerfile", "mongodb", "python" ]
stackoverflow_0058498851_docker_dockerfile_mongodb_python.txt
Q: Slick pivot and mapping in Python I wish to create column headers from the type values. Then map the appropriate en value under the newly formed headers. Data country start type en US 8/1/2022 bb 10 Japan 8/1/2022 aa 25 Japan 9/1/2022 cc 1 Desired country start ...
Slick pivot and mapping in Python
I wish to create column headers from the type values. Then map the appropriate en value under the newly formed headers. Data country start type en US 8/1/2022 bb 10 Japan 8/1/2022 aa 25 Japan 9/1/2022 cc 1 Desired country start aa bb cc US 8/1/2022 0 1...
[ "Try:\ndf.pivot(index=['country', 'start'], columns='type', values='en').fillna(0, downcast='int').reset_index()\n\n#Thanks, @Sammywemmy.\nOutput:\ntype country start aa bb cc\n0 Japan 8/1/2022 25 0 0\n1 Japan 9/1/2022 0 0 1\n2 US 8/1/2022 0 10 0\n\nOr,\ndf.groupby(['coun...
[ 2 ]
[]
[]
[ "numpy", "pandas", "pivot", "python" ]
stackoverflow_0074296898_numpy_pandas_pivot_python.txt
Q: GSpread appending to specific column I'm currently using gspread's "append_row" function to append a string of text to the first column in the spreadsheet. However, I'd like to append the text to a different column than column one. ` from oauth2client.service_account import ServiceAccountCredentials import gspread...
GSpread appending to specific column
I'm currently using gspread's "append_row" function to append a string of text to the first column in the spreadsheet. However, I'd like to append the text to a different column than column one. ` from oauth2client.service_account import ServiceAccountCredentials import gspread scope = ['https://spreadsheets.google.co...
[ "I believe your goal is as follows.\n\nYou want to put the value of \"some text\" to the specific column of the next row of the last row using gspread for python.\n\nWhen append_row is used to an empty sheet, range can be used. But, when the values are existing in the sheet, even when range is used, the values cann...
[ 0 ]
[]
[]
[ "google_sheets", "google_sheets_api", "gspread", "python" ]
stackoverflow_0074294615_google_sheets_google_sheets_api_gspread_python.txt
Q: Why is there no text showing up on my screen? No text is showing up on my screen when this is ran, I've tried diffrent methods and everything. My images are loading before the text, and there is an update function global font global S Seconds = 5 Black = (0,0,0) White = (255,255,255) #Story Text Story = [] Story.a...
Why is there no text showing up on my screen?
No text is showing up on my screen when this is ran, I've tried diffrent methods and everything. My images are loading before the text, and there is an update function global font global S Seconds = 5 Black = (0,0,0) White = (255,255,255) #Story Text Story = [] Story.append("You're Going To Try And Turn It Into a Tradi...
[ "The Game Loop was:\nImage()\nUpdate()\nText()\n\nUpdate need to be last\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074297083_pygame_python.txt
Q: Is there a way to save a CSV file that has been modified by another function in Python? I am new to programming in Python, and I am trying to make a CLI that allows users to filther through csv data with some pre-defined commands with Pandas and Click. I currently have the options for users to list the original da...
Is there a way to save a CSV file that has been modified by another function in Python?
I am new to programming in Python, and I am trying to make a CLI that allows users to filther through csv data with some pre-defined commands with Pandas and Click. I currently have the options for users to list the original data and filter the data by color. My list() and color() functions seem to work how I want them...
[ "If I understand you correctly, you want to save the result of color command to a file (or if isn't any file provides, just print it to the screen):\nimport click # imports click for CLI commands\nimport pandas as pd # import for pandas\n\n# sample dataframe:\ndf = pd.DataFrame({\"Name\": [\"Bob\", \"Rex\"], \"Co...
[ 0 ]
[]
[]
[ "csv", "export_to_csv", "filter", "pandas", "python" ]
stackoverflow_0074295841_csv_export_to_csv_filter_pandas_python.txt
Q: Getting a type error while using fori_loop with JAX I'm developing a code using JAX, and I wanted to JIT some parts of that had big loops. I didn't want the code to be unrolled so I used fori_loop, but I'm getting an error and can't figure out what I am doing wrong. The error is: self.arr = self.arr.reshape(new_...
Getting a type error while using fori_loop with JAX
I'm developing a code using JAX, and I wanted to JIT some parts of that had big loops. I didn't want the code to be unrolled so I used fori_loop, but I'm getting an error and can't figure out what I am doing wrong. The error is: self.arr = self.arr.reshape(new_shape+new_shape) TypeError: 'aval_method' object is not c...
[ "The issue is discussed here: https://jax.readthedocs.io/en/latest/pytrees.html#custom-pytrees-and-initialization\nNamely, in JAX pytrees are used as general containers, and are sometimes initialized with abstract values or other place-holders, and so you cannot assume that arguments to a custom PyTree will be of a...
[ 0 ]
[]
[]
[ "jax", "python" ]
stackoverflow_0074296697_jax_python.txt
Q: Replace value in a list of a Pandas DataFrame Assume there is one DataFrame as following import numpy as np import pandas as pd df = pd.DataFrame({'store':range(1,4), 'food':[['fish', 'apple'], ['orange', 'water'], ['egg', 'fish']]}) df ...
Replace value in a list of a Pandas DataFrame
Assume there is one DataFrame as following import numpy as np import pandas as pd df = pd.DataFrame({'store':range(1,4), 'food':[['fish', 'apple'], ['orange', 'water'], ['egg', 'fish']]}) df store food 1 [fish, apple] 2 [orange,...
[ "Here is a one-liner that does it all:\ndf[\"food\"] = df[\"food\"].map(lambda x: list(map(lambda x: x.replace('fish', 'milk'), x)))\n\nEDIT: removed useless code\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074297158_pandas_python.txt
Q: Does it make sense to use Conda + Poetry? Does it make sense to use Conda + Poetry for a Machine Learning project? Allow me to share my (novice) understanding and please correct or enlighten me: As far as I understand, Conda and Poetry have different purposes but are largely redundant: Conda is primarily a enviro...
Does it make sense to use Conda + Poetry?
Does it make sense to use Conda + Poetry for a Machine Learning project? Allow me to share my (novice) understanding and please correct or enlighten me: As far as I understand, Conda and Poetry have different purposes but are largely redundant: Conda is primarily a environment manager (in fact not necessarily Python),...
[ "I have experience with a Conda + Poetry setup, and it's been working fine. The great majority of my dependencies are specified in pyproject.toml, but when there's something that's unavailable in PyPI, or installing it with Conda is easier, I add it to environment.yml. Moreover, Conda is used as a virtual environme...
[ 78, 1 ]
[]
[]
[ "conda", "machine_learning", "package", "python", "python_poetry" ]
stackoverflow_0070851048_conda_machine_learning_package_python_python_poetry.txt
Q: Sympy Set Theory - How to reduce mathematical expressions? Let's say I have n Sympy sets defined. The set sis: s = FiniteSet('red', 'yellow', 'green') Then I have three further sets: a = FiniteSet('red') b = FiniteSet('yellow') c = FiniteSet('green') It is obvious that a, b and c are subsets of s. When I let sym...
Sympy Set Theory - How to reduce mathematical expressions?
Let's say I have n Sympy sets defined. The set sis: s = FiniteSet('red', 'yellow', 'green') Then I have three further sets: a = FiniteSet('red') b = FiniteSet('yellow') c = FiniteSet('green') It is obvious that a, b and c are subsets of s. When I let sympy calculate the Union of those three subsets, I would obtain th...
[ "You might have to have a Gestalt Shift in your expectations. You are working in Python and you have assigned values to variables. Your expection is that when you print a variable d that has the same value as variable s that you will see the variable s -- but that's not what print(variable) does: it prints the valu...
[ 0 ]
[]
[]
[ "logic", "python", "set", "set_theory", "sympy" ]
stackoverflow_0074279013_logic_python_set_set_theory_sympy.txt
Q: PYGAME, check for second press So I want to change the variable from False to True on the first key press, and then on the second press (of the same key for e.g. "g") I want the variable to change back to "False" Here is an example of not working code: ... if event.type == pygame.KEYUP: if event.key == pygame...
PYGAME, check for second press
So I want to change the variable from False to True on the first key press, and then on the second press (of the same key for e.g. "g") I want the variable to change back to "False" Here is an example of not working code: ... if event.type == pygame.KEYUP: if event.key == pygame.K_g: show_location=True if ...
[ "Rather than hard-coding True or False in your assignment, just negate the current value:\nif event.type == pygame.KEYUP:\n if event.key == pygame.K_g:\n show_location = not show_location\n\n" ]
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074296656_pygame_python.txt
Q: Error message: Unable to locate package libatlas3gf-base I tried with the following commands to install scikit-learn package sudo apt-get install build-essential python-dev python-setuptools sudo apt-get install python-numpy python-scipy sudo apt-get install libatlas-dev libatlas3gf-base Got error message Unab...
Error message: Unable to locate package libatlas3gf-base
I tried with the following commands to install scikit-learn package sudo apt-get install build-essential python-dev python-setuptools sudo apt-get install python-numpy python-scipy sudo apt-get install libatlas-dev libatlas3gf-base Got error message Unable to locate package libatlas3gf-base
[ "Ignore message, keep going with command\npip install --user --install-option=\"--prefix=\" -U scikit-learn\n'Disabling all use of wheels due to the use of --build-options --install-options /global-options'. Takes forever to run setup.py install for scikit-learn, but finally installed. \n", "Search for the packag...
[ 3, 0 ]
[]
[]
[ "python", "raspberry_pi3", "scikit_learn" ]
stackoverflow_0050771104_python_raspberry_pi3_scikit_learn.txt
Q: How to separate elements in a list to put them as value in a dictionary I want to display words that have the required character in a dictionary. For example : Write a sentence: Mister Jack, you are a good coder {'a': ['are', 'jack,'], 'b': [], 'c': ['coder', 'jack,'], 'd': ['coder'], 'e': ['coder', 'mister',], '...
How to separate elements in a list to put them as value in a dictionary
I want to display words that have the required character in a dictionary. For example : Write a sentence: Mister Jack, you are a good coder {'a': ['are', 'jack,'], 'b': [], 'c': ['coder', 'jack,'], 'd': ['coder'], 'e': ['coder', 'mister',], 'f': [], 'g': [], 'h': [], 'i': ['mister'], 'j': ['jack,'], 'k': ['jack,'], 'l...
[ "More 'Pythonic' to use list/dictionary comprehensions:\nwords = sentence.split(' ') # Assuming already lowercase\nalphabet_dict = {x: [w for w in words if x in w] for x in ascii_lowercase}\n\nComprehensions are not just more concise but are more declarative rather than imperative, and so in most cases are easier t...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "for_loop", "list", "python", "set" ]
stackoverflow_0074297145_dictionary_for_loop_list_python_set.txt
Q: loop through folder and find files missing python I am trying to loop through a folder for a given date. There will be 3-4 files in a folder everyday. I have to check if each file is present in the folder for a given date. I cannot hardcode the file name because it has sequence number and can vary. I got below sni...
loop through folder and find files missing python
I am trying to loop through a folder for a given date. There will be 3-4 files in a folder everyday. I have to check if each file is present in the folder for a given date. I cannot hardcode the file name because it has sequence number and can vary. I got below snippet from stackoverflow and it works if my filename is ...
[ "Here is how I handle the issue. I grab a list of files from path that contain the date and file type. I then split on any possible delimiter that isn't alphanumeric to create a list of lists. Then flatten to a single list.\nFinally compare lists for matches return boolean.\nimport re\nfrom pathlib import Path\n\n\...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074295723_pandas_python.txt