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: Filter specific word in string using python I got some data like this https://www.travel.taipei/d_upload_ttn/sceneadmin/pic/11000358.jpghttps://www.travel.taipei/d_upload_ttn/sceneadmin/image/a0/b0/c0/d756/e285/f317/2ece2309-3d1c-49da-8d3a-32e0227e7732.jpghttps://www.travel.taipei/d_upload_ttn/sceneadmin/image/a0/...
Filter specific word in string using python
I got some data like this https://www.travel.taipei/d_upload_ttn/sceneadmin/pic/11000358.jpghttps://www.travel.taipei/d_upload_ttn/sceneadmin/image/a0/b0/c0/d756/e285/f317/2ece2309-3d1c-49da-8d3a-32e0227e7732.jpghttps://www.travel.taipei/d_upload_ttn/sceneadmin/image/a0/b0/c1/d379/e118/f25/554586cb-cf2d-40ef-9b6a-55fcf...
[ "Try:\ns = \"\"\"https://www.travel.taipei/d_upload_ttn/sceneadmin/pic/11000358.jpghttps://www.travel.taipei/d_upload_ttn/sceneadmin/image/a0/b0/c0/d756/e285/f317/2ece2309-3d1c-49da-8d3a-32e0227e7732.jpghttps://www.travel.taipei/d_upload_ttn/sceneadmin/image/a0/b0/c1/d379/e118/f25/554586cb-cf2d-40ef-9b6a-55fcf8d9e5...
[ 1, 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074432112_json_python.txt
Q: Trying to get two random samples to have the same matching foreignkey value I am working on a django app that creates random fantasy character names that pull from the following models: class VillagerFirstNames(models.Model): first_name=models.CharField(max_length=30, unique=True) race = models...
Trying to get two random samples to have the same matching foreignkey value
I am working on a django app that creates random fantasy character names that pull from the following models: class VillagerFirstNames(models.Model): first_name=models.CharField(max_length=30, unique=True) race = models.ForeignKey(Race, on_delete=models.CASCADE) def __str__(self): ...
[ "You can do random selection in Race, from there you can select random VillagerFirstNames and VillagerLastNames. For example:\nrace = Race.objects.all().order_by('?').first()\n\nrace_firstname = race.villagerfirstname_set.all().order_by('?').first()\nrace_lastname = race.villagerlastname_set.all().order_by('?').fir...
[ 1 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0074432039_django_django_models_django_views_python.txt
Q: How can I unnest a long column(map) to multiple columns with pandas? I have a dataframe like this: dataframe name: df_test ID Data test-001 {"B":{"1":{"_seconds":1663207410,"_nanoseconds":466000000}},"C":{"1":{"_seconds":1663207409,"_nanoseconds":978000000}},"D":{"1":{"_seconds":1663207417,"_nanoseconds":2310000...
How can I unnest a long column(map) to multiple columns with pandas?
I have a dataframe like this: dataframe name: df_test ID Data test-001 {"B":{"1":{"_seconds":1663207410,"_nanoseconds":466000000}},"C":{"1":{"_seconds":1663207409,"_nanoseconds":978000000}},"D":{"1":{"_seconds":1663207417,"_nanoseconds":231000000}}} test-002 {"B":{"1":{"_seconds":1663202431,"_nanoseconds":134...
[ "Since pd.json_normalize returns an empty dataframe I'd guess that df[\"Data\"] contains strings? If that's the case you could try\nimport json\n\ndf_data = pd.json_normalize(json.loads(\"[\" + \",\".join(df[\"Data\"]) + \"]\"), sep=\"_\")\nres = pd.concat([df[[\"ID\"]], df_data], axis=1).rename(lambda c: c.replac...
[ 0 ]
[]
[]
[ "pandas", "python", "unnest" ]
stackoverflow_0074426871_pandas_python_unnest.txt
Q: How to write unit test ValidationError case in response by use client.post()? I have a model with a time validator raise ValidationError('End time cannot be earlier than start time') So I want to write a unit test using client.post() with data invalid (from_time > to_time), and I expected ValidationError to appear...
How to write unit test ValidationError case in response by use client.post()?
I have a model with a time validator raise ValidationError('End time cannot be earlier than start time') So I want to write a unit test using client.post() with data invalid (from_time > to_time), and I expected ValidationError to appear in this test. raise ValidationError('End time cannot be earlier than start tim...
[ "you can take a look at the document example on how to write test case https://docs.djangoproject.com/en/dev/topics/testing/tools/#example. In your case it would be like so(notice that this is just an example, so modify to fit your case):\nThis is for validating from serializer/api of DRF:\nimport unittest\nfrom dj...
[ 2, 1 ]
[]
[]
[ "django", "django_rest_framework", "django_validation", "python" ]
stackoverflow_0073245753_django_django_rest_framework_django_validation_python.txt
Q: WebScrapping with Selenium and BeaufitulSoup can't find anything I am trying to extract all the description in the links in the class="publication u-padding-xs-ver js-publication" of this website: https://www.sciencedirect.com/browse/journals-and-books?accessType=openAccess&accessType=containsOpenAccess I tried bo...
WebScrapping with Selenium and BeaufitulSoup can't find anything
I am trying to extract all the description in the links in the class="publication u-padding-xs-ver js-publication" of this website: https://www.sciencedirect.com/browse/journals-and-books?accessType=openAccess&accessType=containsOpenAccess I tried both with BeautifulSoup and Selenium but I can't extract anything. You c...
[ "You are missing waits.\nYou have to wait for elements to become visible before accessing them.\nThe best approach to do that is with use of WebDriverWait expected_conditions explicit waits.\nThe following code works\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom seleni...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping", "webdriverwait" ]
stackoverflow_0074432237_python_selenium_selenium_webdriver_web_scraping_webdriverwait.txt
Q: StandardScaler -ValueError: Input contains NaN, infinity or a value too large for dtype('float64') I have the following code X = df_X.as_matrix(header[1:col_num]) scaler = preprocessing.StandardScaler().fit(X) X_nor = scaler.transform(X) And got the following errors: File "/Users/edamame/Library/python_virenv/...
StandardScaler -ValueError: Input contains NaN, infinity or a value too large for dtype('float64')
I have the following code X = df_X.as_matrix(header[1:col_num]) scaler = preprocessing.StandardScaler().fit(X) X_nor = scaler.transform(X) And got the following errors: File "/Users/edamame/Library/python_virenv/lib/python2.7/site-packages/sklearn/utils/validation.py", line 54, in _assert_all_finite " or a valu...
[ "numpy contains various logical element-wise tests for this sort of thing.\nIn your particular case, you will want to use isinf and isnan.\nIn response to your edit: \nYou can pass the result of np.isinf() or np.isnan() to np.where(), which will return the indices where a condition is true. Here's a quick example:\...
[ 6, 1 ]
[]
[]
[ "nan", "python" ]
stackoverflow_0036532497_nan_python.txt
Q: display events from django database to fullcalendar I am on a django project in which I want to display events from the django database to fullcalendar. The problem I'm having is similar to this one FullCalendar not displaying events but I'm not using php and I'm having trouble visualizing what I'm missing (I gues...
display events from django database to fullcalendar
I am on a django project in which I want to display events from the django database to fullcalendar. The problem I'm having is similar to this one FullCalendar not displaying events but I'm not using php and I'm having trouble visualizing what I'm missing (I guess it's the Ajax request given the answer provided). Curre...
[ "It looks like datatest is already a JSON string when you put it inside the appointment property. So you can't loop through appointment the way you're trying to because it's a piece of text, not an array.\nAlso in datatest you can clearly see that the data doesn't have the \"reason\", \"start_date\" or \"end_date\"...
[ 0, 0 ]
[]
[]
[ "ajax", "django", "fullcalendar", "javascript", "python" ]
stackoverflow_0072088812_ajax_django_fullcalendar_javascript_python.txt
Q: AWS boto3 attribute_not_exists currDBraw = table.scan( FilterExpression=Attr('purebetId').gt(0) & "attribute_not_exists(ouline)", ProjectionExpression="event,homeTeam,awayTeam,startDate,purebetId" ) Im new to aws and boto3, with this, i get AND operation cannot be applied to value attribute_not_exists(ouline...
AWS boto3 attribute_not_exists
currDBraw = table.scan( FilterExpression=Attr('purebetId').gt(0) & "attribute_not_exists(ouline)", ProjectionExpression="event,homeTeam,awayTeam,startDate,purebetId" ) Im new to aws and boto3, with this, i get AND operation cannot be applied to value attribute_not_exists(ouline) of type <class 'str'> directly and...
[ "attribute_not_exists is a conditional expression used only in update/insert operations\nConditionExpression='attribute_not_exists(something)\n\nWhat you need to do is just compare to null\ncurrDBraw = table.scan(\n FilterExpression=Attr('purebetId').gt(0) & \"outline = null\",\n ProjectionExpression=\"event,home...
[ 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074432282_amazon_dynamodb_amazon_web_services_boto3_python.txt
Q: Value duplicated in dictionary The following is my code: test = [{'name' : 'one'}, {'name' : 'two'}] a = {} b = [] c = {} for i in test: c['name'] = i['name'] b.append(c) a['items'] = b print(a) This produces the following content of dictionary a, which is wrong: {'items': [{'name': 'two'}, {'name': 't...
Value duplicated in dictionary
The following is my code: test = [{'name' : 'one'}, {'name' : 'two'}] a = {} b = [] c = {} for i in test: c['name'] = i['name'] b.append(c) a['items'] = b print(a) This produces the following content of dictionary a, which is wrong: {'items': [{'name': 'two'}, {'name': 'two'}]} Why does the output dictiona...
[ "You only created one dict named c, so it's name key changes each time through the loop. You want a new dict to append to b each time through the loop: move c = {} into the loop's body.\nfor i in test:\n c = {}\n c['name'] = i['name']\n b.append(c)\n\nor\nfor i in test:\n c = {'name': i['name']}\n b....
[ 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074432469_dictionary_list_python.txt
Q: What am I iterating over? I am practicing pandas dataframes and I'm confused about one thing since I'm still a newbie at Python coming from a strong Java, C family background. for i in dataframe1.columns: dataframe1[i] = np.where(dataframe1[i] == 0, np.nan, dataframe1[i]) I am confused with what I am iteratin...
What am I iterating over?
I am practicing pandas dataframes and I'm confused about one thing since I'm still a newbie at Python coming from a strong Java, C family background. for i in dataframe1.columns: dataframe1[i] = np.where(dataframe1[i] == 0, np.nan, dataframe1[i]) I am confused with what I am iterating over? As I take it, dataframe...
[ "Building up on @ddejohn,\ndata = [\n ['fruit', 'veggies', 0], \n ['0', 0, 'spices']\n ]\ndf=pd.DataFrame(data, columns=['col1','col2','col3'])\ndf\n\n\n col1 col2 col3\n0 fruit veggies 0\n1 0 0 spices\n\nusing replace will give:\nnew_df=df.replace(0,np.nan...
[ 0 ]
[]
[]
[ "data_science", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074426736_data_science_dataframe_numpy_pandas_python.txt
Q: How to send SQS message asynchronously in python? Here's my Python code right now: sqs = boto3.resource('sqs') queue = sqs.get_queue_by_name(Queue='test') msg = 'hello world' for i in range(0,1000): queue.send_message(MessageBody = msg) print("Message Sent") And here is the Node.js version: var sqs = new ...
How to send SQS message asynchronously in python?
Here's my Python code right now: sqs = boto3.resource('sqs') queue = sqs.get_queue_by_name(Queue='test') msg = 'hello world' for i in range(0,1000): queue.send_message(MessageBody = msg) print("Message Sent") And here is the Node.js version: var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var params = { ...
[ "The boto3 library does not support async calls. There is a library that supports S3 with some testing on SQS called aiobotocore. These links have more information:\naiobotocore\nSupport asyncio\n", "I would like to suggest my own Python package for this: it uses just aiohttp and lxml, without any boto-dependenci...
[ 3, 0 ]
[]
[]
[ "amazon_sqs", "amazon_web_services", "asynchronous", "node.js", "python" ]
stackoverflow_0046821113_amazon_sqs_amazon_web_services_asynchronous_node.js_python.txt
Q: I have 3 pythons in my miniconda3/bin, which do I keep? I'm on windows wsl2, and I have 3 pythons. Which one do I keep or should I no touch them? I was reading an article on how to fix import errors and it might be because I have more than 1 python version(more than one pip). When I type python --version and pytho...
I have 3 pythons in my miniconda3/bin, which do I keep?
I'm on windows wsl2, and I have 3 pythons. Which one do I keep or should I no touch them? I was reading an article on how to fix import errors and it might be because I have more than 1 python version(more than one pip). When I type python --version and python3 --version, I get 3.9.12 on both
[ "These are usually symbolic links. It helps resolving the main python interpreter without having to specify the full target version.\nTry running ls -l. It should gives you something similar to this (in my case I ran ls -l /bin/python*):\nlrwxrwxrwx 1 root root 7 Apr 15 2020 /bin/python -> python2\nlrwxrwxrwx 1...
[ 0 ]
[]
[]
[ "python", "python_3.9" ]
stackoverflow_0074431777_python_python_3.9.txt
Q: How to install python libraries in docker file on ubuntu? I want to create a docker image (docker version: 20.10.20)that contains python libraires from a requirement.txt file that contains 50 libraries. Without facing root user permissions how can proceed. Here is the file: From ubuntu:latest RUN apt update RUN a...
How to install python libraries in docker file on ubuntu?
I want to create a docker image (docker version: 20.10.20)that contains python libraires from a requirement.txt file that contains 50 libraries. Without facing root user permissions how can proceed. Here is the file: From ubuntu:latest RUN apt update RUN apt install python3 -y WORKDIR /Destop/DS # COPY requirement.tx...
[ "For me the only problem in your Dockerfile is in the line RUN apt install python -y. This is erroring with Package 'python' has no installation candidate.\nIt is expected since python refers to version 2.x of Python wich is deprecated and no longer present in the default Ubuntu repositories.\nChanging your Dockerf...
[ 3 ]
[]
[]
[ "docker", "dockerfile", "python" ]
stackoverflow_0074432427_docker_dockerfile_python.txt
Q: Replace default loading screen image with custom animation I made an android application using the kivy framework. I noticed that in the buildozer.spec file; There are lines that suggest the possibility of implementing an animation to replace the default loading screen. The lines I'm talking about are... # (string...
Replace default loading screen image with custom animation
I made an android application using the kivy framework. I noticed that in the buildozer.spec file; There are lines that suggest the possibility of implementing an animation to replace the default loading screen. The lines I'm talking about are... # (string) Presplash animation using Lottie format. # see https://lottief...
[ "edit portionIn the buildozer.spec file you have an boolean option android.useandroidx which defaults to false you need to set it to true and further you need to edit the python for android section and change p4a.branch = develop, that should do the work\n", "Make below changes!!\n\nAdd json to the list:\n\nsourc...
[ 0, 0 ]
[]
[]
[ "android", "buildozer", "kivy", "lottie", "python" ]
stackoverflow_0073213831_android_buildozer_kivy_lottie_python.txt
Q: how can i use variables correctly in classes? i made three classes, one to decide the position of a point on a 2d space. and second, a function, to calcule the distance between two points. and a third to calculate wether a point is in a circle close to a point, but this third one just doesnt work and i cant figure...
how can i use variables correctly in classes?
i made three classes, one to decide the position of a point on a 2d space. and second, a function, to calcule the distance between two points. and a third to calculate wether a point is in a circle close to a point, but this third one just doesnt work and i cant figure out why class Point(): """ Represents a point ...
[ "The first parameter of class instance functions, by convention, should be self. It's implicitly added, so you're probably seeing some error like \"2 arguments provided, expected 1\"\ndef inside_circle(self, input_circle)-> bool:\n return distance(self.center, input_circle) <= radius\n\nAlso, I assume you meant ...
[ 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074432497_class_python.txt
Q: Why does a combined call to random.randint and random.sample in a loop lead to a repeating output sequence? I am confused by the behaviour of the following code using random in python: SEED = ... # see below for some examples for _ in range(100): k = random.randint(1, 21) print(k) random.seed(SEED) ...
Why does a combined call to random.randint and random.sample in a loop lead to a repeating output sequence?
I am confused by the behaviour of the following code using random in python: SEED = ... # see below for some examples for _ in range(100): k = random.randint(1, 21) print(k) random.seed(SEED) s = random.sample(population=range(100), k=k) I would expect the first print(k) to output a random number bet...
[ "As Tom pointed out in the comments you're generating k random numbers, which takes at least k calls (Python uses rejection sampling to ensure draws aren't biased) to the underlying RNG.\nYou could fix your example by doing something like:\nimport random\n\nSEED = ... # see below for some examples\nMAX_K = 21\n\nfo...
[ 1 ]
[]
[]
[ "python", "random" ]
stackoverflow_0074430760_python_random.txt
Q: How can I do to access to a foreign key in the other side? I am working a on projects using Django. Here is my models.py : class Owner(models.Model): name = models.CharField(max_length=200) class Cat(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) pseudo = models.CharField(ma...
How can I do to access to a foreign key in the other side?
I am working a on projects using Django. Here is my models.py : class Owner(models.Model): name = models.CharField(max_length=200) class Cat(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) pseudo = models.CharField(max_length=200) I did that : first_owner = Owner.objects.get(id=1...
[ "To get all Cat instances from Owner instance in the view you can do:\nfirst_owner = get_object_or_404(Owner,id=1)\n\nall_instances = first_owner.cat_set.all()\n\nIn the template you can do it as:\n{% for owner in first_owner.cat_set.all %}\n {{owner.psuedo}}\n\n{% endfor %}\n\n", "You can add related_name in y...
[ 2, 2 ]
[]
[]
[ "django", "django_models", "django_queryset", "foreign_keys", "python" ]
stackoverflow_0074432108_django_django_models_django_queryset_foreign_keys_python.txt
Q: Unable to extract tables from tabula or Camelot Tried to extract the below table using Tabula, but it was returning null dataframe. It was working fine for other kinds of similar tables. Tried using Camelot as well but it didn't work as well. Any suggestions about how can I extract these? Attached my code from ta...
Unable to extract tables from tabula or Camelot
Tried to extract the below table using Tabula, but it was returning null dataframe. It was working fine for other kinds of similar tables. Tried using Camelot as well but it didn't work as well. Any suggestions about how can I extract these? Attached my code from tabula import read_pdf from tabulate import tabulate f...
[ "The issue got fixed after adding flavor='stream' and 'guess=False' in tabula.\nfrom tabula import read_pdf \nfrom tabulate import tabulate\nfrom tabula import read_pdf\nimport pandas as pd\n# from tabula.io import read_pdf\n\nPage_No = 1\ntables = read_pdf('/content/page1.pdf',pages=Page_No,guess=False,stream=Tru...
[ 0 ]
[]
[]
[ "dataframe", "python", "python_camelot", "tabula_py" ]
stackoverflow_0074429395_dataframe_python_python_camelot_tabula_py.txt
Q: how does this code work its printing false ? where did i make mistake? def check_22(num_list): for i in range(0, len(num_list)-1): if num_list[i] == 2 and num_list[i+1] == 2: return True else: return False print(check_22([3,2,5,1,2,1,2,2])) How come the output ...
how does this code work its printing false ? where did i make mistake?
def check_22(num_list): for i in range(0, len(num_list)-1): if num_list[i] == 2 and num_list[i+1] == 2: return True else: return False print(check_22([3,2,5,1,2,1,2,2])) How come the output is False when it needs to display True?
[ "What your code does right now is as soon as it gets in checks 3 and 2, they are not both 2 so it returns false. What you want for your purpose is:\nfor i in range(0,len(num_list)-1): \n if num_list[i]==2 and num_list[i+1]==2: \n return True\nreturn False\n\nSo it would return false only after checking the whole ...
[ 0, 0 ]
[ "first of all indentation is important in python:\ndef check_22(num_list): \n#start writing your code here\n for i in range(0,len(num_list)-1):\n if num_list[i]==2 and num_list[i+1]==2: \n return True\n else:\n return False\n\nAt the beginning, the index i is zero, and th...
[ -1 ]
[ "python" ]
stackoverflow_0074432707_python.txt
Q: Why does df.loc not seem to work in a loop (key error) Can anyone tell me why df.loc can't seem to work in a loop like so example_data = { 'ID': [1,2,3,4,5,6], 'score': [10,20,30,40,50,60] } example_data_df = pd.DataFrame(example_data) for row in example_data_df: print(example_data_df.loc[row,'ID']) ...
Why does df.loc not seem to work in a loop (key error)
Can anyone tell me why df.loc can't seem to work in a loop like so example_data = { 'ID': [1,2,3,4,5,6], 'score': [10,20,30,40,50,60] } example_data_df = pd.DataFrame(example_data) for row in example_data_df: print(example_data_df.loc[row,'ID']) and is raising the error "KeyError: 'ID'"? Outside of the ...
[ "If you check 'row' as each step, you'll notice that iterating directly over a DataFrame yields the column names.\nYou want:\nfor idx, row in example_data_df.iterrows():\n print(example_data_df.loc[idx,'ID'])\n\nOr, better:\nfor idx, row in example_data_df.iterrows():\n print(row['ID'])\n\nNow, I don't know w...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074432744_pandas_python.txt
Q: Can I create a Airflow DAG dynamically using REST API? Is it possible to create a Airflow DAG programmatically, by using just REST API? Background We have a collection of models, each model consists of: A collection of SQL files that need to be run for the model We also keep a JSON file for each model which defin...
Can I create a Airflow DAG dynamically using REST API?
Is it possible to create a Airflow DAG programmatically, by using just REST API? Background We have a collection of models, each model consists of: A collection of SQL files that need to be run for the model We also keep a JSON file for each model which defines the dependencies between each SQL file. The scripts are ...
[ "Airflow dags are python objects, so you can create a dags factory and use any external data source (json/yaml file, a database, NFS volume, ...) as source for your dags.\nHere are the steps to achieve your goal:\n\ncreate a python script in your dags folder (assume its name is dags_factory.py)\ncreate a python cla...
[ 1 ]
[]
[]
[ "airflow", "airflow_api", "python" ]
stackoverflow_0074432020_airflow_airflow_api_python.txt
Q: Why is numeric type deleted and list type not, when they are attributes to a class instance (which gets deleted)? In the below code sample I would expect both a and b to be deleted at the end of each loop. What happens is that a is deleted but not b. Why is that? And how can I make sure that b is also deleted at t...
Why is numeric type deleted and list type not, when they are attributes to a class instance (which gets deleted)?
In the below code sample I would expect both a and b to be deleted at the end of each loop. What happens is that a is deleted but not b. Why is that? And how can I make sure that b is also deleted at the end of each loop? class bag: a = 5 b = [] def funcie(self): self.a = self.a + 1 ...
[ "bag.a (a class attribute) is not being overridden, it's being shadowed by the instance's a (an instance attribute) for inst specifically.\nPython's general rule is that reading will read from outer/shadowed scopes if there is no inner/shadowing scope hiding it. An inner/shadowing scope is created by assignment, no...
[ 1, 0 ]
[]
[]
[ "class", "memory", "python", "types" ]
stackoverflow_0074432027_class_memory_python_types.txt
Q: Looking up value in csv file could you help me to solve my problem. I have a csv file with 12000000 lines, I need to search for two values on it and display the third value if it matches. But in the csv file there are values with 14 decimals, and I am searching for a value with 4 decimal places. This is the workin...
Looking up value in csv file
could you help me to solve my problem. I have a csv file with 12000000 lines, I need to search for two values on it and display the third value if it matches. But in the csv file there are values with 14 decimals, and I am searching for a value with 4 decimal places. This is the working code: df2 = dk.read_csv(filename...
[ "The relevant method is .round, which will round your pandas series to the desired precision:\nfrom pandas import DataFrame\ndf = DataFrame({'a': [32.001111111111115, 32.3452, 32.345211111]})\nmask = df['a'].round(4) == 32.3452\nprint(df.loc[mask])\n\nTo be safe, you might want to round the target value also (to av...
[ 0 ]
[]
[]
[ "csv", "dask", "filter", "pandas", "python" ]
stackoverflow_0074431470_csv_dask_filter_pandas_python.txt
Q: Recursively implement the function halves that takes two positive integers a and b, and returns a list containing the value a Recursively implement the function halves that takes two positive integers a and b, and returns a list containing the value a (converted to type float) and all successive halves of a that a...
Recursively implement the function halves that takes two positive integers a and b, and returns a list containing the value a
Recursively implement the function halves that takes two positive integers a and b, and returns a list containing the value a (converted to type float) and all successive halves of a that are greater than b. I tried like this but it's returning an empty list and I don't understand what's going on: def metades(a, b): ...
[ "To handle a list in a recursive function, you must take it into the function's arguments:\ndef metades(a, b, res = None):\n\n res = res or []\n\n if a <= b: return res\n if a > b:\n res.append(a) # put first append and then division to retrieve also first value of 'a'\n a = float(a / 2)\n\n...
[ 2, 0 ]
[]
[]
[ "arrays", "math", "python" ]
stackoverflow_0074432470_arrays_math_python.txt
Q: Searching for certain keywords in pandas dataframe for classification I have a list of keywords based on which I want to categorize the job description. Here are example list of keywords manager = ["manager", "president", "management", "managing"] assistant = ["assistant", "assisting"] engineer = ["engineer", "eng...
Searching for certain keywords in pandas dataframe for classification
I have a list of keywords based on which I want to categorize the job description. Here are example list of keywords manager = ["manager", "president", "management", "managing"] assistant = ["assistant", "assisting"] engineer = ["engineer", "engineering", "scientist", "architect"] If a job description contains any of ...
[ "First I'd suggest to store your classifications in a dictionary, this will make it easier to retrieve the category name.\nThen You can create your own function where you'll iterate over the dictionary items (the dict should be therefore organized by priority), and apply this function to the job_description column:...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074432455_pandas_python.txt
Q: How to dynamically plot multiple subplots in Python? I need to plot a variable number of plots (at least 1 but it isn't known the number max) and I couldn't come up with a way to dynamically create and assign subplots to the given graphs. The code looks like this: check = False if "node_x_9" in names: ...
How to dynamically plot multiple subplots in Python?
I need to plot a variable number of plots (at least 1 but it isn't known the number max) and I couldn't come up with a way to dynamically create and assign subplots to the given graphs. The code looks like this: check = False if "node_x_9" in names: if "node_x_11" in names: plt.plot(df["nod...
[ "I've come across cases like this, you want to generate one plot per case, but don't know how many cases exist until you query the data on the day.\nI used a square layout as an assumption (alter the below if you require a different aspect ratio) then count how many cases you have - find the integer square-root, wh...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074429484_matplotlib_pandas_python.txt
Q: Pig latin string conversion in python I'm trying to create a function that turns text into pig Latin: simple text transformation that modifies each word moving the first character to the end and appending "ay" to the end. But all I get is an empty list. Any tips? def pig_latin(text): say = "" words = text.spli...
Pig latin string conversion in python
I'm trying to create a function that turns text into pig Latin: simple text transformation that modifies each word moving the first character to the end and appending "ay" to the end. But all I get is an empty list. Any tips? def pig_latin(text): say = "" words = text.split() for word in words: endString = st...
[ "def pig_latin(text):\n words = text.split()\n pigged_text = []\n\n for word in words:\n word = word[1:] + word[0] + 'ay'\n pigged_text.append(word)\n\n return ' '.join(pigged_text)\n\nprint(pig_latin(\"hello how are you\"))\n\nOutputs: ellohay owhay reaay ouyay\n", "I tried this and it worked for me\n\...
[ 5, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "def pig_latin(text):\n say = \"\"\n words = text.split()\n for word in words:\n word=word[1:] + word[0] + \"ay\" + \" \"\n say +=word\n return say\n \nprint(pig_latin(\"hello how are you\"))\n\n", "def pig_latin(text):\n say = \"\"\n # Separate the text into words\n words = text.split()\n fo...
[ -1, -1, -1 ]
[ "for_loop", "function", "python" ]
stackoverflow_0060982439_for_loop_function_python.txt
Q: How to filter filter_horizontal in Django admin? I'm looking for a way to use filter_horizontal on the base of a filtered queryset. I've tried to use it with a custom manager: In models.py: class AvailEquipManager(models.Manager): def get_query_set(self): return super(AvailEquipManager, self).get_query...
How to filter filter_horizontal in Django admin?
I'm looking for a way to use filter_horizontal on the base of a filtered queryset. I've tried to use it with a custom manager: In models.py: class AvailEquipManager(models.Manager): def get_query_set(self): return super(AvailEquipManager, self).get_query_set().filter(id=3) class Equipment(models.Model): ...
[ "I found a solution by adapting the answer to a different question which I found in Google Groups\nIt works with a custom ModelForm like so:\nCreate a new forms.py:\nfrom django import forms\nfrom models import Equipment\n\nclass EquipmentModelForm(forms.ModelForm):\n class Meta:\n model = Equipment\n\n ...
[ 27, 5, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0022968631_django_django_admin_python.txt
Q: How to build a hash table with python? I want to build a hash table by linear probing with python I have a list of employeesID and employeesName, I want to put that data in hash table this is my code : employeeID = [107,35,25,13,101,43,98,57,1,2,3,4] employeeName = ["a","b","c","d","e","f","g","h","i","j","k","Er...
How to build a hash table with python?
I want to build a hash table by linear probing with python I have a list of employeesID and employeesName, I want to put that data in hash table this is my code : employeeID = [107,35,25,13,101,43,98,57,1,2,3,4] employeeName = ["a","b","c","d","e","f","g","h","i","j","k","Err"] class HashTable: hashSize = 11 tota...
[ "If employeeID and employeeName are the same lengths, you can do\nemployeeID = [107,35,25,13,101,43,98,57,1,2,3,4]\nemployeeName = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\"]\n\nhash = dict(zip(employeeName,employeeID)\n\n#result\n\n{'a': 107, 'b': 35, 'c': 25, 'd': 13, 'e': 101, 'f': ...
[ 0 ]
[]
[]
[ "hashtable", "python" ]
stackoverflow_0074432817_hashtable_python.txt
Q: Assigning a method to a variable I have a Dictionary paths, and if its not set correctly i want it to call a command import os import platform import logging paths={} def setup_paths(): path_root=get_project_root() paths['root']=path_root paths['documents']=lambda :createError('system',0,'Folder not ...
Assigning a method to a variable
I have a Dictionary paths, and if its not set correctly i want it to call a command import os import platform import logging paths={} def setup_paths(): path_root=get_project_root() paths['root']=path_root paths['documents']=lambda :createError('system',0,'Folder not Found') def createError(sender,level,...
[ "So I have found the answer, and thoroughly think its cool and wanted to share,\nso...\n#you can pass along a Method as a Variable\nm=lambda arg,arg2:_method(arg,arg2)\n\n#then call on it latter\nm()\n\nwith this I can set a method to a value\nif: os.path.exsits(pathTOdoc): path['Document']=pathTOdoc\nelse: path['D...
[ 0 ]
[]
[]
[ "dictionary", "lambda", "python" ]
stackoverflow_0074424012_dictionary_lambda_python.txt
Q: cleverhans, tf2, fgsm - how can i pass my LSTM regression model to the fast gradient method function in cleverhans? (logits) i built and trained my LSTM model for a regression task and everything works fine. i would like to use the fast_gradient_method function from cleverhans (or any other cleverhans function as ...
cleverhans, tf2, fgsm - how can i pass my LSTM regression model to the fast gradient method function in cleverhans? (logits)
i built and trained my LSTM model for a regression task and everything works fine. i would like to use the fast_gradient_method function from cleverhans (or any other cleverhans function as the issue stands for any other attack). i don't understand how am i supposed to pass the model to the function. from cleverhans: :...
[ "to pass a valid model, it should be defined in the following way: \n(it is just an example) \n\"make\" is only needed for model.summary() to work, I found the code in another SO post that I can't seem to find right now\nclass modSubclass(Model):\n def __init__(self):\n super(modSubclass, self).__init__(...
[ 0 ]
[]
[]
[ "cleverhans", "logits", "lstm", "python", "regression" ]
stackoverflow_0074391941_cleverhans_logits_lstm_python_regression.txt
Q: How to convert string range into the float or int dtype of average? I have data as such: datetime range 2022-10-10 50-54 2022-10-12 30-36 range is object dtype. How can I get to: datetime range mean 2022-10-10 50-54 52.0 2022-10-12 30-36 33.0 A: You can split your string on -, th...
How to convert string range into the float or int dtype of average?
I have data as such: datetime range 2022-10-10 50-54 2022-10-12 30-36 range is object dtype. How can I get to: datetime range mean 2022-10-10 50-54 52.0 2022-10-12 30-36 33.0
[ "You can split your string on -, then convert to integer and get the mean per row:\ndf['mean'] = df['range'].str.split('-', expand=True).astype(int).mean(axis=1)\n\nOr use numpy:\nimport numpy as np\ndf['mean'] = np.loadtxt(df['range'], delimiter='-').mean(axis=1)\n\noutput:\n datetime range mean\n0 2022-10-...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074433040_dataframe_pandas_python.txt
Q: Pandas create new column based on a rows in another column I have following classes in pandas column : Married-civilian spouse present ,Never married , Married-spouse absent, Married-A F spouse present ,Divorced, Widowed, Separated . Based on it create new column in where (Married-civilian spouse ...
Pandas create new column based on a rows in another column
I have following classes in pandas column : Married-civilian spouse present ,Never married , Married-spouse absent, Married-A F spouse present ,Divorced, Widowed, Separated . Based on it create new column in where (Married-civilian spouse present ,Never married , Married-spouse absent) will be replaced...
[ "I think you can use isin:\ndf_filtered['is_married'] = df_filtered['marital_status'].isin(['Married-civilian spouse present', 'Married-spouse absent', 'Married-A F spouse present']).astype(int)\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074432962_pandas_python.txt
Q: Django - module 'pymysql._auth' has no attribute 'scramble_old_password' I am trying to connect mysql DB in django application. But it is throwing error- module 'pymysql._auth' has no attribute 'scramble_old_password'. A: Issue: PyMySQL latest version only supports MySQL version >= 5.6 While in my case MySQL ver...
Django - module 'pymysql._auth' has no attribute 'scramble_old_password'
I am trying to connect mysql DB in django application. But it is throwing error- module 'pymysql._auth' has no attribute 'scramble_old_password'.
[ "Issue: PyMySQL latest version only supports MySQL version >= 5.6\nWhile in my case MySQL version was 5.5\nSolution: So I downgraded the version of PyMySQL and everything works fine now.\n" ]
[ 0 ]
[]
[]
[ "django", "mysql", "pymysql", "python" ]
stackoverflow_0073231565_django_mysql_pymysql_python.txt
Q: How to make pyramid of a string? I want to make a pyramid of a string for an exercise. I just don't know how to do it. For example: string = "these***are***just***random***words*" and the pyramid I want to make is: t hes e***a re***ju st***rand om***words* How do I do this?...
How to make pyramid of a string?
I want to make a pyramid of a string for an exercise. I just don't know how to do it. For example: string = "these***are***just***random***words*" and the pyramid I want to make is: t hes e***a re***ju st***rand om***words* How do I do this? def draw_pyramid(string, size): i...
[ "You can use string.center() to get the strings nicely aligned in the center. To get the right characters from l I use a start and an end variable:\ndef draw_pyramid(string, size):\n if size > 15:\n size = 15\n if size < 5:\n size = 5\n length = size * 2 - 1\n l = string * size\n start ...
[ 1, 0 ]
[]
[]
[ "nested_loops", "python" ]
stackoverflow_0074432719_nested_loops_python.txt
Q: Lookup Values in Pandas - 2 search Key I have 2 tables from google sheets. df1 where it has the users completion of different modules. And df2 that consists of user details. df1: df2: I want to merge tables just like the image below. Currently, I am able to achieve this using array vlookup. Sometimes I also use ...
Lookup Values in Pandas - 2 search Key
I have 2 tables from google sheets. df1 where it has the users completion of different modules. And df2 that consists of user details. df1: df2: I want to merge tables just like the image below. Currently, I am able to achieve this using array vlookup. Sometimes I also use index match. But it takes forever because in...
[ "Use pivot to reshape df1, then merge:\ndf2.merge(df1.pivot(index='User Id', columns='Module', values='Status'), on='User Id')\n\n", "You can use set_index and stack do to:\n# sample data \ndf1=pd.DataFrame({'UserId': [1,1,2,2],\n 'Module': ['Lesson1', 'Lesson2', 'Lesson1', 'Lesson2'],\n ...
[ 0, 0 ]
[]
[]
[ "google_colaboratory", "pandas", "python" ]
stackoverflow_0074433089_google_colaboratory_pandas_python.txt
Q: Generate constraints in pyomo with a loop and changing inputs As an input for my optimization model I have a node structure that links variables with each other as in (simplified version): from __future__ import annotations import typing as T import pyomo.environ as po class DummyNode: def __init__(self, nam...
Generate constraints in pyomo with a loop and changing inputs
As an input for my optimization model I have a node structure that links variables with each other as in (simplified version): from __future__ import annotations import typing as T import pyomo.environ as po class DummyNode: def __init__(self, name: str): self.CHILDREN: T.List[DummyNode] = [] sel...
[ "If you change your construct to a ConcreteModel it works as you intended. If you \"bring your own data\", I think the ConcreteModel is by far the best way to go anyhow.\nThat said, A couple of ideas...\n\nI think using the getattr and setattr are confusing and I'm not sure if there are any hidden pitfalls with di...
[ 1 ]
[]
[]
[ "pyomo", "python" ]
stackoverflow_0074428968_pyomo_python.txt
Q: How to pass params to get required value from array of object by filtering I am trying to build a function, which should accept the parameter and return the value by filtering an array by iterating it's value. I start to get some what looping the values. But do not know how to declare the function and get return v...
How to pass params to get required value from array of object by filtering
I am trying to build a function, which should accept the parameter and return the value by filtering an array by iterating it's value. I start to get some what looping the values. But do not know how to declare the function and get return value from the array. not able to get some suitable online reference. code: lst...
[ "What I have done :\n\nstore the user input in a variable (name) before the loop, so it does not ask at each iteration\nprint that we are searching in the list before the loop\niterate over the list items (variable item) instead of its indices\n\nlst = [[\"a\", 45], [\"b\", 40], [\"c\", 18], [\"d\", 17]]\n\nname = ...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074418519_python_python_3.x.txt
Q: Updates to Python pandas dataframe rows do not update the dataframe? I just discovered that iterating the rows of a pandas dataframe, and making updates to each row, does not update the dataframe! Is this expected behaviour, or does one need to do something to the row first so the update reflects in the parent dat...
Updates to Python pandas dataframe rows do not update the dataframe?
I just discovered that iterating the rows of a pandas dataframe, and making updates to each row, does not update the dataframe! Is this expected behaviour, or does one need to do something to the row first so the update reflects in the parent dataframe? I know one could update the dataframe directly in the loop, or wit...
[ "You are storing the changes as row['Price'] but not actually saving it back to the dataframe df, you can go ahead and test this by using:\nid(row) == id(df)\n\nWhich returns False. Also, for better efficiency you shouldn't loop, but rather simply re-assign. Replace the for loop with:\ndf['New Price '] = df['Price'...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074433246_dataframe_pandas_python.txt
Q: How can I locate and measure this object in the picture? I have this image Interest in detecting the long structure from the first image and the expected results are attached in the next image. The expected results I have tried the following procedures thresholding contour detection alignment of the binary imag...
How can I locate and measure this object in the picture?
I have this image Interest in detecting the long structure from the first image and the expected results are attached in the next image. The expected results I have tried the following procedures thresholding contour detection alignment of the binary image to the horizontal (use the angle of rotation) Advice needed ...
[ "Approach:\n\nminAreaRect from convex hull\nsome geometry to establish a local coordinate system\ntaking 1-D samples along the object (warpAffine)\nfinding edges to measure thickness of bars\n\nTo get the midpoint of the center bar exactly, you'd want to go along the object halfway, then scan crosswise for the cent...
[ 0 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074421046_image_processing_opencv_python.txt
Q: choose rows to another dataframe and drop rows by conditional in column pandas I have simple dataframe and i would like separate it. Make Model Year BMW 1 serie 2007 Kia K7 2012 BMW 6 serie 1982 BMW 6 serie 1987 BMW X3 2006 Kia Bongo 2000 i need take cars where (Year >= 2000) and put it to another datafram...
choose rows to another dataframe and drop rows by conditional in column pandas
I have simple dataframe and i would like separate it. Make Model Year BMW 1 serie 2007 Kia K7 2012 BMW 6 serie 1982 BMW 6 serie 1987 BMW X3 2006 Kia Bongo 2000 i need take cars where (Year >= 2000) and put it to another dataframe, at the same time i would like leave the rest of the data (Year < 20...
[ "For your use case you can take advantage of the pandas.DataFrame.query function :\ndf_2000 = df.query(\"Year >= 2000\")\ndf = df.query(\"Year < 2000\")\n\nFor Simple cases it provides easier and cleaner code.\nYou can read more about the pros and cons of query in this answer.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074433116_dataframe_pandas_python.txt
Q: Using for loop to make predictions grouped by I have this time series dataframe which looks like this: Employee_ID Age Start_Date End_Date Profits 111 43 01/07/2020 9:00 30/07/2020 9:04 7772.14 111 43 01/08/2020 9:00 30/08/2020 9:04 4352.46 111 ...
Using for loop to make predictions grouped by
I have this time series dataframe which looks like this: Employee_ID Age Start_Date End_Date Profits 111 43 01/07/2020 9:00 30/07/2020 9:04 7772.14 111 43 01/08/2020 9:00 30/08/2020 9:04 4352.46 111 43 01/09/2020 9:00 30/09/2020 9:00 ...
[ "You can do like:\n# add predictions to test data\nX_test['score'] = metrics.mean_absolute_error(y_test, y_pred)\n\n# calculate agg score metrics for group\nX_test.groupby('Employee_ID')['score'].mean()\n\n" ]
[ 0 ]
[]
[]
[ "for_loop", "pandas", "python", "regression", "scikit_learn" ]
stackoverflow_0074432903_for_loop_pandas_python_regression_scikit_learn.txt
Q: How to produce an output file from 2 input files such a way that output file will contain only results after comparing the given two input files The two input files are given below, input1.txt info="0x101" Data="0x00000000" info="0x1678a1" Data="0x0a56F001" info="0x156A17" Data="0x0003F4a1" info="0x18C550" Data="0...
How to produce an output file from 2 input files such a way that output file will contain only results after comparing the given two input files
The two input files are given below, input1.txt info="0x101" Data="0x00000000" info="0x1678a1" Data="0x0a56F001" info="0x156A17" Data="0x0003F4a1" info="0x18C550" Data="0x00000000" info="0x145673" Data="000C60Fa2" input2.txt //PS name above bit below bit original 1_info 2_info //...
[ "\nthe output file is created in this manner:\nread input2.txt and check 1_info value and if the same info value is\nthere in input1.txt then write this line in input2.txt along with\nadditional column new which will have value of data with respect to\ninfo of input1.txt.\n\nJust follow this.\n\nBefore reading inpu...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074432346_python_python_3.x.txt
Q: Beginner Python surface calculation of a hut I'm trying to make a program to calculate the surface area of ​​a shack with a pitched roof. I've only been in this class for 2 weeks and I'm a bit overwhelmed. The program should ask the user via console for the values ​​and then calculate the values ​​using the defini...
Beginner Python surface calculation of a hut
I'm trying to make a program to calculate the surface area of ​​a shack with a pitched roof. I've only been in this class for 2 weeks and I'm a bit overwhelmed. The program should ask the user via console for the values ​​and then calculate the values ​​using the definition. I'm not asking for the entire code at all. B...
[ "You don't need to import math as basic multiplication is already included. You also don't need to initialize a variable before you assign it so I removed the\nG = 0\nG = a*b\n\nlines and replaced it with a simple\nreturn a*b\n\nYou don't need brackets around a return statement, just a print statement.\nThe final t...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074433327_python.txt
Q: Printing from a for loop with separators between each element but not at the end How can I make sure that there is nothing at the end of the last print statement instead of "-"? for i in range(0, 4,): print(i, end="-") print() for i in range(0, 10, 2): print(i, end="-") A: You can use the join method of ...
Printing from a for loop with separators between each element but not at the end
How can I make sure that there is nothing at the end of the last print statement instead of "-"? for i in range(0, 4,): print(i, end="-") print() for i in range(0, 10, 2): print(i, end="-")
[ "You can use the join method of strings to get your desired output (you need to transform the numbers to strings):\nprint(\"-\".join(str(i) for i in range(0, 4)))\nprint(\"-\".join(str(i) for i in range(0, 10, 2)))\n\nAlternatively you can use the sep argument of the print function and unpack the range:\nprint(*ran...
[ 3, 0 ]
[ "for i in range(0, 4,):\n print(i, sep=\"-\")\nprint()\nfor i in range(0, 10, 2):\n print(i, sep=\"-\")\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074433306_python.txt
Q: Python converting datetime.date to str I have a pandas.DataFrame with columns 'start', 'end', and 'vals_to_sum'. I want to sum all values in the latter column for dates in a list of days in datetime.date format: date_list = [start_date + datetime.timedelta(days=i) for i in range(366)] where start_date is of dateti...
Python converting datetime.date to str
I have a pandas.DataFrame with columns 'start', 'end', and 'vals_to_sum'. I want to sum all values in the latter column for dates in a list of days in datetime.date format: date_list = [start_date + datetime.timedelta(days=i) for i in range(366)] where start_date is of datetime.date. I have a problem where when I try t...
[ "The Pandas dataframes store pointers to each string into the type 'object' (check out the docs at https://pandas.pydata.org/pandasdocs/stable/user_guide/text.html). If you'd like to assign it back to the column, you could do something like:\ndf['column_new'] = df['column'].str.split(',')\n\nSince I'm not sure how ...
[ 0, 0 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074426387_dataframe_datetime_pandas_python.txt
Q: Can't play audio in voice channels, AttributeError: 'VoiceChannel' object has no attribute 'play' vc = bot.get_channel(ctx.author.voice.channel.id) await vc.connect() await vc.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source="assets/a.mp3")) This code was working like 3 months ago, and now it doesn't b...
Can't play audio in voice channels, AttributeError: 'VoiceChannel' object has no attribute 'play'
vc = bot.get_channel(ctx.author.voice.channel.id) await vc.connect() await vc.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source="assets/a.mp3")) This code was working like 3 months ago, and now it doesn't because voice channel object (vc) has no attribute play. Any reason why it stopped working and how to fi...
[ "voice = get(bot.voice_clients, guild=ctx.guild)\nif voice and voice.is_connected:\n await voice.move_to(channel)\nelse:\n voice = await channel.connect()\n\n", "A AttributeError typically means you have the wrong type of object. Like the error says, a VoiceChannel has no attribute play. If you look the API...
[ 1, 0 ]
[]
[]
[ "discord", "discord.py", "python", "python_3.x" ]
stackoverflow_0074432583_discord_discord.py_python_python_3.x.txt
Q: Any conda or pip operation give SSL Error in windows 10 I have tried installing or updating new packages in my windows 10 system wherein I have installed Anaconda3 (2019 version).But everytime I get the same SSL error. I would have suspect it could be company firewall issue , if the I could have accessed that in H...
Any conda or pip operation give SSL Error in windows 10
I have tried installing or updating new packages in my windows 10 system wherein I have installed Anaconda3 (2019 version).But everytime I get the same SSL error. I would have suspect it could be company firewall issue , if the I could have accessed that in Home wifi network. But everywhere I get the same error . Whil...
[ "I was able to solve the issue following THIS instructions.\nBasically:\n* copy the following files from CONDA_PATH\\Library\\bin to CONDA_PATH\\DLLs\nlibcrypto-1_1-x64.*\nlibssl-1_1-x64.*\n\n", "On Miniconda, Win11 Pro x64. Wanted to create a new env and conda install pip and got the same issue suddenly.\n\nUpda...
[ 23, 3, 1, 0, 0 ]
[]
[]
[ "anaconda", "conda", "python" ]
stackoverflow_0055185945_anaconda_conda_python.txt
Q: How to run command if checkbox is ticked I want to execute an extra function in the command if the checkbox is ticked, and if it is not ticked, then i don't want my program to execute it, how can i do that? I.e, I want to execute CreateWallet Function if the checkbox is ticked, however, I don't want to disable the...
How to run command if checkbox is ticked
I want to execute an extra function in the command if the checkbox is ticked, and if it is not ticked, then i don't want my program to execute it, how can i do that? I.e, I want to execute CreateWallet Function if the checkbox is ticked, however, I don't want to disable the addchrome() one! Thanks in advance! from tkin...
[ "Define a wrapper function that can be called by button1 to execute addChrome, and conditionally execute CreateWallet\ndef on_button_press():\n is_checked = var.get()\n addChrome()\n if is_checked:\n CreateWallet()\n\n\nbutton1 = Button(\n root,\n text=\"Start\",\n command=on_button_press ...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074433468_python_tkinter.txt
Q: How to create a list containing random pairs from an original list? I have a list: lst = ['ab', 'cd','ef', 'gh', 'ij', 'mn', 'op', 'qr', 'st', 'uv', 'wx', 'yz'] I would like to take 2 random values from this list and put them in to a new list as pairs until the original list is empty. For example: new_list = [('a...
How to create a list containing random pairs from an original list?
I have a list: lst = ['ab', 'cd','ef', 'gh', 'ij', 'mn', 'op', 'qr', 'st', 'uv', 'wx', 'yz'] I would like to take 2 random values from this list and put them in to a new list as pairs until the original list is empty. For example: new_list = [('ab', 'ef'), ('ij', 'yz') exc. ] lst = [] How can I do this using a while a...
[ "I'm sure there are lots of ways. Here's a simple one.\nlst = ['ab', 'cd','ef', 'gh', 'ij', 'mn', 'op', 'qr', 'st', 'uv', 'wx', 'yz']\nresult = []\nrandom.shuffle(lst)\nfor i in range(0, len(lst), 2):\n result.append((lst[i], lst[i+1]))\n\n", "Try this\nimport random\n\nlst = ['ab', 'cd','ef', 'gh', 'ij', 'mn'...
[ 1, 0, 0, 0 ]
[ "You can try something using np.random.choice:\nnew_list = []\n\nwhile lst:\n tmp=np.random.choice(lst, 2).tolist()\n for t in tmp:\n lst.remove(t)\n new_list.append(tmp)\n \nprint(new_list)\n\n[['op', 'wx'], ['yz', 'cd'], ['ef', 'qr'], ['mn', 'ij'], ['uv', 'gh'], ['ab', 'st']]\n\n" ]
[ -1 ]
[ "arrays", "list", "python" ]
stackoverflow_0074433173_arrays_list_python.txt
Q: Django IndexView does not refresh current date I am using Django IndexView to display main page in my application with some data. The data contains field named date_time. I want to display data for date_time range starting from current time when I visit page to some point in future My code looks like below: class ...
Django IndexView does not refresh current date
I am using Django IndexView to display main page in my application with some data. The data contains field named date_time. I want to display data for date_time range starting from current time when I visit page to some point in future My code looks like below: class IndexView(LoginRequiredMixin, generic.ListView): ...
[ "You need to apply the filter in get_queryset() in order to re-calculate the current timestamp.\nclass IndexView(LoginRequiredMixin, generic.ListView):\n \"\"\"View class for home page\"\"\"\n template_name = 'core/index.html'\n model = Match\n context_object_name = 'match_list'\n\n def get_queryset(...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074433528_django_python.txt
Q: How to create a subset of data with Panda? My task is to select a subset of data to a given region based on a csv files. They gave me a hint to use the module panda but I don't know what function to use to do my task. Here's my code (The task is to give the data frames from any kind of region displayed.) def Creat...
How to create a subset of data with Panda?
My task is to select a subset of data to a given region based on a csv files. They gave me a hint to use the module panda but I don't know what function to use to do my task. Here's my code (The task is to give the data frames from any kind of region displayed.) def CreateSubsetPerRegion(df, region): #TODO Extraire...
[ "First, you probably just want to load your DataFrame once. Then, you can get your per-region DataFrame using a simple mask like this:\npath = os.getcwd()\ndf = pd.read_csv(os.path.join(path, '2020.csv'))\n\neast_asia = df[df[\"Region\"] == \"East Asia\"]\nce_europe = df[df[\"Region\"] == \"Central and Eastern Euro...
[ 0, 0 ]
[]
[]
[ "csv", "dataframe", "display", "pandas", "python" ]
stackoverflow_0074433522_csv_dataframe_display_pandas_python.txt
Q: Correct use of np.reshape() command I have a 1D-array which has the following structure: arr = [x,a,b,c,y,a,b,c] How can I convert that 1D array into a 3D-array like this: arr2 = [[[x,a],[x,b],[x,c]], [[y,a], [y,b], [y,c]]] (3 y-values for each x-value) A: arr = np.array([1, 2, 2, 2, 3, 4, 4, 4, 5, 6, 6, 6]) a...
Correct use of np.reshape() command
I have a 1D-array which has the following structure: arr = [x,a,b,c,y,a,b,c] How can I convert that 1D array into a 3D-array like this: arr2 = [[[x,a],[x,b],[x,c]], [[y,a], [y,b], [y,c]]] (3 y-values for each x-value)
[ "arr = np.array([1, 2, 2, 2, 3, 4, 4, 4, 5, 6, 6, 6])\n\narr = arr.reshape((3, -1))\narr = np.delete(arr, 0, 1)\nprint(arr)\n\nResult:\n[[2 2 2]\n [4 4 4]\n [6 6 6]]\n\n\nAfter the OP's edit, this is the answer\narr = np.array([0, 7, 8, 9, 1, 7, 8, 9])\n\n# Extract the component subarrays\nsub_arr1 = arr[0:-1:4] ...
[ 2, 1 ]
[]
[]
[ "2d", "arrays", "python", "reshape" ]
stackoverflow_0074433538_2d_arrays_python_reshape.txt
Q: BeautifulSoup - extracting text from multiple span elements w/o classes So that's how HTML looks: <p class="details"> <span>detail1</span> <span class="number">1</span> <span>detail2</span> <span>detail3</span> </p> I need to extract detail2 & detail3. But with this piece of code I only get detail1. info = data.f...
BeautifulSoup - extracting text from multiple span elements w/o classes
So that's how HTML looks: <p class="details"> <span>detail1</span> <span class="number">1</span> <span>detail2</span> <span>detail3</span> </p> I need to extract detail2 & detail3. But with this piece of code I only get detail1. info = data.find("p", class_ = "details").span.text How do I extract the needed items? Th...
[ "Select your elements more specific in your case all sibling <span> of <span> with class number:\nsoup.select('span.number ~ span')\n\nExample\nfrom bs4 import BeautifulSoup\nhtml='''<p class=\"details\">\n<span>detail1</span>\n<span class=\"number\">1</span>\n<span>detail2</span>\n<span>detail3</span>\n</p>'''\nso...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0074433559_beautifulsoup_html_python.txt
Q: Check if a numeric string is palindrome in Python Below is my code: def check_palindrome(num): my_str = str(num) my_list1 = list(my_str) my_list2 = list(my_str) my_list2.reverse() if my_list1 == my_list2: return "It's palindrome" else: return "Not a palindrome" print(...
Check if a numeric string is palindrome in Python
Below is my code: def check_palindrome(num): my_str = str(num) my_list1 = list(my_str) my_list2 = list(my_str) my_list2.reverse() if my_list1 == my_list2: return "It's palindrome" else: return "Not a palindrome" print(check_palindrome(232)) print(check_palindrome(235)) If...
[ "You can do it like this:\ndef check_palindrome(num) -> bool:\n my_str = str(num)\n if my_str == my_str[::-1]:\n return True\n return False\n\nEDIT even shorter (and neater): credits @mozway\ndef check_palindrome(num) -> bool:\n my_str = str(num)\n return my_str == my_str[::-1]:\n\nI did not r...
[ 1 ]
[]
[]
[ "function", "palindrome", "python" ]
stackoverflow_0074433613_function_palindrome_python.txt
Q: How to construct a string from letters of each word from list? I am wondering how to construct a string, which takes 1st letter of each word from list. Then it takes 2nd letter from each word etc. For example : Input --> my_list = ['good', 'bad', 'father'] Every word has different length (but the words in the list...
How to construct a string from letters of each word from list?
I am wondering how to construct a string, which takes 1st letter of each word from list. Then it takes 2nd letter from each word etc. For example : Input --> my_list = ['good', 'bad', 'father'] Every word has different length (but the words in the list could have equal length) The output should be: 'gbfoaaodtdher'. I t...
[ "That's a good job for itertools.zip_longest:\nfrom itertools import zip_longest\n\ns = ''.join([c for x in zip_longest(*my_list) for c in x if c])\nprint(s)\n\nOr more_itertools.interleave_longest:\nfrom more_itertools import interleave_longest\n\ns = ''.join(interleave_longest(*my_list))\nprint(s)\n\nOutput: gbfo...
[ 1, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074433383_loops_python.txt
Q: Deterministic hashing in Python 3 I'm using hashing of strings for seeding random states in the following way: context = "string" seed = hash(context) % 4294967295 # This is necessary to keep the hash within allowed seed values np.random.seed(seed) This is unfortunately (for my usage) non-deterministic between ru...
Deterministic hashing in Python 3
I'm using hashing of strings for seeding random states in the following way: context = "string" seed = hash(context) % 4294967295 # This is necessary to keep the hash within allowed seed values np.random.seed(seed) This is unfortunately (for my usage) non-deterministic between runs in Python 3.3 and up. I do know that...
[ "Use a purpose-built hash function. zlib.adler32() is an excellent choice; alternatively, check out the hashlib module for more options.\n", "Forcing Python's built-in hash to be deterministic is intrinsically hacky. If you want to avoid hackitude, use a different hashing function -- see e.g in Python-2: https:/...
[ 12, 4, 3, 0 ]
[]
[]
[ "hash", "python", "python_3.x" ]
stackoverflow_0027954892_hash_python_python_3.x.txt
Q: PyQt5: painting using events I am new on PyQt I am working on a project on which I should implement a feature that make the user able to draw a digit using the mouse (digit recognition system). So what I want is when the mouse button is pressed the app will start to draw till the button is released. I made this so...
PyQt5: painting using events
I am new on PyQt I am working on a project on which I should implement a feature that make the user able to draw a digit using the mouse (digit recognition system). So what I want is when the mouse button is pressed the app will start to draw till the button is released. I made this source code but it is still not work...
[ "Python is sensitive to uppercase and lowercase so be more careful, the method is called paintEvent.\nAlso you should not call paintEvent directly, you must use the function update(), this method will internally call paintEvent().\nBut even correcting that error your problem is not solved, if you want to draw a pat...
[ 4, 0 ]
[]
[]
[ "pyqt", "pyqt5", "python", "qpainter", "qt" ]
stackoverflow_0046633698_pyqt_pyqt5_python_qpainter_qt.txt
Q: How to apply onehot encoder over vectorized dataframe columns? Suppose that we have this data frame: ID CATEGORIES 0 ['A'] 1 ['A', 'C'] 2 ['B', 'C'] And I want to apply one hot encoder to categories column. The result I want is ID A B C 0 1 0 0 1 1 0 1 2 0 1 1 I know it can be easily codded. I just want ...
How to apply onehot encoder over vectorized dataframe columns?
Suppose that we have this data frame: ID CATEGORIES 0 ['A'] 1 ['A', 'C'] 2 ['B', 'C'] And I want to apply one hot encoder to categories column. The result I want is ID A B C 0 1 0 0 1 1 0 1 2 0 1 1 I know it can be easily codded. I just want to know if this function is already implemente...
[ "You can use str.join combined with str.get_dummies:\nout = df[['ID']].join(df['CATEGORIES'].str.join('|').str.get_dummies())\n\nOutput:\n ID A B C\n0 0 1 0 0\n1 1 1 0 1\n2 2 0 1 1\n\nused input:\ndf = pd.DataFrame({'ID': [0, 1, 2],\n 'CATEGORIES': [['A'], ['A', 'C'], ['B', 'C'...
[ 1 ]
[]
[]
[ "one_hot_encoding", "pandas", "python", "scikit_learn" ]
stackoverflow_0074433740_one_hot_encoding_pandas_python_scikit_learn.txt
Q: How to create an array given n-rows and k-columns, with a starting number x and step size y in python So let's say I ask for some input of n-rows and k-columns: rows = n columns = k What I want to do is to create an array of dimensions (rows, columns) and then populate said array with a set of numbers starting fr...
How to create an array given n-rows and k-columns, with a starting number x and step size y in python
So let's say I ask for some input of n-rows and k-columns: rows = n columns = k What I want to do is to create an array of dimensions (rows, columns) and then populate said array with a set of numbers starting from some number x with some step size y such that no matter the inputs for rows and columns it would be able...
[ "Yes you can do that like this:\nimport numpy\nrows = 4\ncolumns = 3\n# Starting number\nx = 1\n# Step size\ny = 2\n\narray = np.arange(x, (rows*columns)*y+x, y).reshape(rows, columns)\n\nPlease look at https://numpy.org/doc/stable/reference/generated/numpy.arange.html and https://numpy.org/doc/stable/reference/gen...
[ 2, 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074433704_python_python_3.x.txt
Q: Using reStructuredText to add some HTML with custom "id" and "class" attributes Using rsStructuredText to generate HTML, I am trying to wrap a paragraph with an extra div element. The must contain an "id" attribute with a value I assign. Also, the must have a "class" attribute with "editable" value. This is wha...
Using reStructuredText to add some HTML with custom "id" and "class" attributes
Using rsStructuredText to generate HTML, I am trying to wrap a paragraph with an extra div element. The must contain an "id" attribute with a value I assign. Also, the must have a "class" attribute with "editable" value. This is what I have so far: .. raw:: html <div id="an_identifier"> .. class:: editable ...
[ "Since release 0.8 (2011-07-07), you can use the container directive with a name option:\n .. container:: test\n :name: my-id\n\n a paragraph\n\nresults in\n <div class=\"test container\" id=\"my-id\">\n a paragraph\n </div>\n\n", "I've been just working on with something similar and I found the solution...
[ 23, 2, 2, 0 ]
[]
[]
[ "python", "restructuredtext" ]
stackoverflow_0003864712_python_restructuredtext.txt
Q: Adding constraints Gurobi Python city=["A","B"] week=[0,1,2,3] S={"A":[5,15,25,35], "B":[80,11,31,30]} model=gp.Model() I = model.addVars(city, week, name="I") model.setObjective(...) # try 1: model.addConstrs(S[c][w] <= I[c][w] for c in city for w in week) # try 2: for c in city: for w in week: mo...
Adding constraints Gurobi Python
city=["A","B"] week=[0,1,2,3] S={"A":[5,15,25,35], "B":[80,11,31,30]} model=gp.Model() I = model.addVars(city, week, name="I") model.setObjective(...) # try 1: model.addConstrs(S[c][w] <= I[c][w] for c in city for w in week) # try 2: for c in city: for w in week: model.addConstr(S[c][w] <= I[c][w]) He...
[ "Note that model.addVars() returns a gurobi tupledict where each key is stored as tuplelist:\n>>> print(I)\nIn [64]: I\nOut[64]:\n{('A', 0): <gurobi.Var I[A,0]>,\n ('A', 1): <gurobi.Var I[A,1]>,\n ('A', 2): <gurobi.Var I[A,2]>,\n ('A', 3): <gurobi.Var I[A,3]>,\n ('B', 0): <gurobi.Var I[B,0]>,\n ('B', 1): <gurobi.Va...
[ 1 ]
[]
[]
[ "constraints", "gurobi", "python" ]
stackoverflow_0074430051_constraints_gurobi_python.txt
Q: Why is this code not clicking EVERY element in list? I am trying to go into every city one by one here but after the program comes back from the first page, it does not go into the next page and displays StaleElementReferenceException error. This is my code: url = "https://www.agoda.com/region/punjab-province-pk.h...
Why is this code not clicking EVERY element in list?
I am trying to go into every city one by one here but after the program comes back from the first page, it does not go into the next page and displays StaleElementReferenceException error. This is my code: url = "https://www.agoda.com/region/punjab-province-pk.html" s=Service(ChromeDriverManager().install()) driver =...
[ "When you going to another page by clicking the city all the web elements initially collected in cities list on the main page are becoming stale. In Selenium Web Element is actually a reference to a physical web element. When you coming back to the main page it is re-rendered so the previously collected references ...
[ 3 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "staleelementreferenceexception", "web_scraping" ]
stackoverflow_0074433649_python_selenium_selenium_webdriver_staleelementreferenceexception_web_scraping.txt
Q: Import errors in telegram bot (python-telegram-bot) I have a telegram bot written using python-telegram-bot that was working fine but after a few weeks, when I start the script, it seems like it cannot find some libraries & modules. As an example, "Update" is widely used in my code and it was working just fine. Bu...
Import errors in telegram bot (python-telegram-bot)
I have a telegram bot written using python-telegram-bot that was working fine but after a few weeks, when I start the script, it seems like it cannot find some libraries & modules. As an example, "Update" is widely used in my code and it was working just fine. But now it cannot be found by python. Here are some of my i...
[ "I don't think there is a good way to transfer environments to production (Correct me if I am wrong), however, you can build a new environment using the exact same packages that are installed in your environment using:\npip freeze > requirements.txt\n\nThis saves every package you used in the development env in a f...
[ 0 ]
[]
[]
[ "python", "python_telegram_bot" ]
stackoverflow_0074431324_python_python_telegram_bot.txt
Q: free memory as I iterate over a list I have a hypothetical question regarding the memory usage of lists in python. I have a long list my_list that consumes multiple gigabytes if it is loaded into memory. I want to loop over that list and use each element only once during the iteration, meaning I could delete them ...
free memory as I iterate over a list
I have a hypothetical question regarding the memory usage of lists in python. I have a long list my_list that consumes multiple gigabytes if it is loaded into memory. I want to loop over that list and use each element only once during the iteration, meaning I could delete them from the list after looping over them. Whi...
[ "Many of your assumptions here are incorrect.\n\nFirst biggie is the assumption that you can delete items as you loop over them with a for loop. You can't. You could with a while loop of the form:\nwhile my_list:\n item=my_list.pop(0)\n process(item)\n # Each my_list[0] element ref_count-- each loop...\n ...
[ 2 ]
[]
[]
[ "list", "memory_management", "python" ]
stackoverflow_0074432327_list_memory_management_python.txt
Q: How to do a temporal linear interpolation of a 3d array (lat,lon,time) for one missing timestep in the 3d array? I want to to a temporal linear interpolation on griddata (= xarray with dimensions: lat,lon, time), meaning that I have one timestep where there is no data but the timesteps before and after have inform...
How to do a temporal linear interpolation of a 3d array (lat,lon,time) for one missing timestep in the 3d array?
I want to to a temporal linear interpolation on griddata (= xarray with dimensions: lat,lon, time), meaning that I have one timestep where there is no data but the timesteps before and after have information. I tried to use scipy.interpolate.griddata where I first created a mask layer for all the nan data and then inte...
[ "xarray has some interpolation tools.\nBelow example opens a netCDF dataset from file location fname and interpolates param1 and param2 on lon, lat and time.\nwith xr.open_dataset(fname) as ds:\n lat = xr.DataArray(your_lat_array, dims='z')\n lon = xr.DataArray(your_lon_array, dims='z')\n time_array = xr.D...
[ 0 ]
[]
[]
[ "interpolation", "numpy", "python", "python_xarray", "scipy" ]
stackoverflow_0074433457_interpolation_numpy_python_python_xarray_scipy.txt
Q: 'ImportError: No module named ...' when trying to import pyx file to Jupyter I have this file em.pyx in the same folder as the Jupyter notebook where I try to import it but it is giving me the error ImportError: No module named em I've tried adding import sys sys.path.insert(0, 'name_of_directory_where_pyxfile_...
'ImportError: No module named ...' when trying to import pyx file to Jupyter
I have this file em.pyx in the same folder as the Jupyter notebook where I try to import it but it is giving me the error ImportError: No module named em I've tried adding import sys sys.path.insert(0, 'name_of_directory_where_pyxfile_is') or sys.path.append('my/path/to/module/folder') as suggested here and here, ...
[ "The import can occur because you are trying to import .pyx directly into python. You need first install Cython which is the container of pyxinstall. This might help.\nBut you can try out the other way. Try to convert pyx file to py file then import the file. The work of yours will be done but will have sacrifice t...
[ 0, 0 ]
[]
[]
[ "cython", "jupyter_notebook", "python", "python_3.x" ]
stackoverflow_0055282877_cython_jupyter_notebook_python_python_3.x.txt
Q: Using regex in python to delete (or replace) parentheses and items inside them I have a csv file that looks like the following: Halley Bailey - 1998 Hayley Orrantia (1994-) American actress, singer, and songwriter Ken Watanabe (actor) etc... I’d like to remove the items in the parentheses, as well as the comma...
Using regex in python to delete (or replace) parentheses and items inside them
I have a csv file that looks like the following: Halley Bailey - 1998 Hayley Orrantia (1994-) American actress, singer, and songwriter Ken Watanabe (actor) etc... I’d like to remove the items in the parentheses, as well as the commas in some of the names that have commas, so that the dataframe looks like this: Hall...
[ "Try with the following '(^[^\\(|^\\-]+)' returning all matches before a - or (:\ndf['Full Name'] = df['Description'].str.extract('(^[^\\(|^\\-]+)')\n\nReturning:\n Description Full Name\n0 Halley Bailey - 1998 Halley Bailey \n1 Hayley...
[ 1, 1 ]
[]
[]
[ "pandas", "python", "replace", "string" ]
stackoverflow_0074430704_pandas_python_replace_string.txt
Q: I have a status code checker for urls that gives me a list with the urls+status code - I want to get a message when status 200 is recieved I use this status checker since some months. Works flawlessly, although I would love to get a message when a status 200 is found and if not it loops itself and start from the b...
I have a status code checker for urls that gives me a list with the urls+status code - I want to get a message when status 200 is recieved
I use this status checker since some months. Works flawlessly, although I would love to get a message when a status 200 is found and if not it loops itself and start from the beginning (thinking of implementing a telegram/discord message). If that is the case, I don't even need a full url list as file, just a file with...
[ "The Response.status_code attribute is an int, so a normal equality check should work:\nif r.status_code == 200:\n pass\n\nIf you wish to accept any status code below 400, however, Response.ok can be used instead.\n" ]
[ 0 ]
[]
[]
[ "alert", "python", "status", "url", "web_crawler" ]
stackoverflow_0074433930_alert_python_status_url_web_crawler.txt
Q: interp is valid for monotonically increasing sample points? I am reading the docs for interp and it says One-dimensional linear interpolation for monotonically increasing sample points. However, how about this code import matplotlib.pyplot as plt import numpy as np #x = np.arange(0, 3 * np.pi, 0.1) #y = np.sin(...
interp is valid for monotonically increasing sample points?
I am reading the docs for interp and it says One-dimensional linear interpolation for monotonically increasing sample points. However, how about this code import matplotlib.pyplot as plt import numpy as np #x = np.arange(0, 3 * np.pi, 0.1) #y = np.sin(x) x = 3.6 #xp = [2, 4, 6] #fp = [1, 3, 5] #xp = [2, 4, 6, 8] ...
[ "You're asking about the behaviour of interp in a regime where the documentation of interp doesn't make any claims about: The idea is that np.interp should only be used if the x-values of the sample points are monotonically increasing. Full stop. It doesn't make any claims of what happens if they are not monotonica...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074433151_numpy_python.txt
Q: Average distance between sample and all group of samples in python I have a set of samples, where each sample is specified by a vector (values), with their cluster number. df = pd.DataFrame({'samples': ['A', 'B', 'C', 'D', 'E'], 'values': [[5, 0, 2, 2],[1, 6, 0, 2],[7, 2, 0, 0],[3, 6, 0, 0],[7, 0, 0, 2]], 'cluster...
Average distance between sample and all group of samples in python
I have a set of samples, where each sample is specified by a vector (values), with their cluster number. df = pd.DataFrame({'samples': ['A', 'B', 'C', 'D', 'E'], 'values': [[5, 0, 2, 2],[1, 6, 0, 2],[7, 2, 0, 0],[3, 6, 0, 0],[7, 0, 0, 2]], 'cluster': [1, 0, 2, 0, 1]}) df output: samples values cluster 0 A [5, 0, ...
[ "Few steps:\n\nYou need to first find the average of each cluster, which is called a centroid. A centroid is the average of each dimension defining the cluster. As an example, let's consider cluster 1:\n\n\n samples values cluster\n0 A [5, 0, 2, 2] 1\n4 E [7, 0, 0, 2] 1\n\n\nThe centroid of clust...
[ 0 ]
[]
[]
[ "cluster_analysis", "distance", "python" ]
stackoverflow_0074424853_cluster_analysis_distance_python.txt
Q: In Django create a model method which determines an id for all objects that share the same foreign key Kind of new to Django and while trying to create my first own project, i stumbled upon a problem. I have two different model classes: Star and Planet. Each planet has a foreignkey which belongs to a Star. Now I w...
In Django create a model method which determines an id for all objects that share the same foreign key
Kind of new to Django and while trying to create my first own project, i stumbled upon a problem. I have two different model classes: Star and Planet. Each planet has a foreignkey which belongs to a Star. Now I would like to have a field for Planet, which is basically the id/pk for its star system that is given on crea...
[ "This is my suggestion (following the comments on you post):\nclass Planet(models.Model):\n name = models.CharField(max_length=200)\n star = models.ForeignKey(Star, on_delete=models.CASCADE, related_name='planets')\n\n # Use property since it's more pythonic\n @property\n def star_system_planet_id(se...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074430516_django_django_models_python.txt
Q: How to extract information in a dictionary in json data = {'gems': [{'name': 'garnet', 'colour': 'red', 'month': 'January'}, {'name': 'emerald', 'colour': 'green', 'month': 'May'}, {'name': "cat's eye", 'colour': 'yellow', 'month': 'June'}, {'name': 'sardonyx', 'colour': 'red', 'month': 'August'}, {'name...
How to extract information in a dictionary in json
data = {'gems': [{'name': 'garnet', 'colour': 'red', 'month': 'January'}, {'name': 'emerald', 'colour': 'green', 'month': 'May'}, {'name': "cat's eye", 'colour': 'yellow', 'month': 'June'}, {'name': 'sardonyx', 'colour': 'red', 'month': 'August'}, {'name': 'peridot', 'colour': 'green', 'month': 'September'}, ...
[ "Because you have dictionaries within a list, you can use a list-comprehension with nested if logic to filter out those values you don't want:\n[x['month'] for x in data['gems'] if x['colour'] == 'red']\n\nReturns:\n['January', 'August', 'December']\n\n", "Assuming that one wants the output as a dataframe, one ca...
[ 1, 0 ]
[]
[]
[ "dictionary", "json", "list", "python", "python_3.x" ]
stackoverflow_0074405846_dictionary_json_list_python_python_3.x.txt
Q: Find element by class name make the error: "Traceback (most recent call last)" I logged in to Instagram and I'm trying to press a button to close a popup but every time get this no matter what I try, *I repleced the username and password only to put the code here.. from selenium import webdriver from selenium.webd...
Find element by class name make the error: "Traceback (most recent call last)"
I logged in to Instagram and I'm trying to press a button to close a popup but every time get this no matter what I try, *I repleced the username and password only to put the code here.. from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.keys import Keys ...
[ "By.CLASS_NAME receives single parameter value while _acan _acao _acas are 3 class names.\nTo locate element based on multiple class names you can use CSS Selector or XPath.\nSo, instead of\nWebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, '_acan _acao _acas')))\n\nTry using\nWebDriver...
[ 1 ]
[]
[]
[ "css_selectors", "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074433890_css_selectors_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Is there a way to create the possible pairs for number neighbors in python? I'm attempting to create a new list with all the possible pairs in a list but only want to have the numbers that are neighbors be possible pairs. For example, I have already created this list from a file: [1, 8, 10, 16, 19, 22, 27, 33, 36,...
Is there a way to create the possible pairs for number neighbors in python?
I'm attempting to create a new list with all the possible pairs in a list but only want to have the numbers that are neighbors be possible pairs. For example, I have already created this list from a file: [1, 8, 10, 16, 19, 22, 27, 33, 36, 40, 47, 52, 56, 61, 63, 71, 72, 75, 81, 81, 84, 88, 96, 98, 103, 110, 113, 118, ...
[ "Use zip() with a slice of the list offset by one place.\nresult = list(zip(newl, newl[1:]))\n\n", "Just use this simple for loop:\nnewl = [1, 8, 10, 16, 19, 22, 27, 33, 36, 40, 47, 52, 56, 61, 63, 71, 72, 75, 81, 81, 84, 88, 96, 98, 103, 110, 113, 118, 124, 128, 129, 134, 134, 139, 148, 157, 157, 160, 162, 164]\...
[ 2, 0 ]
[]
[]
[ "list", "python", "python_itertools", "tuples" ]
stackoverflow_0074434139_list_python_python_itertools_tuples.txt
Q: Node: 'IteratorGetNext' - INVALID_ARGUMENT: Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [5], [batch]: [0] I'm trying to work on the Kaggle Getting Started Natural Language Processing with Disaster Tweets competition as an exam project for my uni deep learning course. I ...
Node: 'IteratorGetNext' - INVALID_ARGUMENT: Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [5], [batch]: [0]
I'm trying to work on the Kaggle Getting Started Natural Language Processing with Disaster Tweets competition as an exam project for my uni deep learning course. I am trying to solve the problem using a multi-input network, where the keyword and location columns are handled by two separate Conv1D networks, and the text...
[ "Nevermind, should have just experimented more. Moving the .batch function from step 3 to step 4 (where I do the dataset zipping) and setting the batch size to 1 has worked and the network is now training, though I am open to better suggestions, if there are any.\nNow I just have to solve the fact that loss is NaN....
[ 0 ]
[]
[]
[ "keras", "nlp", "python", "tensorflow", "transformer_model" ]
stackoverflow_0074433941_keras_nlp_python_tensorflow_transformer_model.txt
Q: Pyspark: TypeError: 'Column' object is not callable --- Using Window Function #Trying to use Window Functions in PySpark from pyspark.sql import Row, functions as F from pyspark.sql.functions import col, row_number from pyspark.sql.window import Window from pyspark.sql import SparkSession Join_transaciones3_df = J...
Pyspark: TypeError: 'Column' object is not callable --- Using Window Function
#Trying to use Window Functions in PySpark from pyspark.sql import Row, functions as F from pyspark.sql.functions import col, row_number from pyspark.sql.window import Window from pyspark.sql import SparkSession Join_transaciones3_df = Join_transaciones3_df.withColumn("row_num", F.row_number().OVER(Window.partitionBy("...
[ "You don't need to wrap the transaction_date in the col method - try this:\nJoin_transaciones3_df = Join_transaciones3_df.withColumn(\"row_num\", F.row_number().over(Window.partitionBy(\"Clave\").orderBy(\"transaction_date\")))\n\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "pyspark", "python" ]
stackoverflow_0074432803_amazon_web_services_pyspark_python.txt
Q: Importing the numpy c-extensions failed in VS Code Getting error with VS Code in installing pkg Numpy and Pandas. Any solution on how we can fix the issue? Thanks. Error: from . import _distributor_init Traceback (most recent call last): File ".\Form_validate.py", line 1, in <module> import pandas as pd File "C:\P...
Importing the numpy c-extensions failed in VS Code
Getting error with VS Code in installing pkg Numpy and Pandas. Any solution on how we can fix the issue? Thanks. Error: from . import _distributor_init Traceback (most recent call last): File ".\Form_validate.py", line 1, in <module> import pandas as pd File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\__init__.p...
[ "There are two solutions.\nThe first is to reinstall numpy, including its architecture tools. Reinstall the package by using the following code in sequence:\npip uninstall -y numpy\n\npip uninstall -y setuptools\n\npip install setuptools\n\npip install numpy\n\nThe second solution is to add the path to the environm...
[ 1, 0 ]
[]
[]
[ "anaconda", "numpy", "pandas", "python", "visual_studio_code" ]
stackoverflow_0072634054_anaconda_numpy_pandas_python_visual_studio_code.txt
Q: extract sub string from column in dataframe, iteratively I have a dataframe that contains multiple columns. The column 'group_email" contains multiple parts of data that's relevant, and I want to extract a specific subtring from the 'group_email' column and create a new column from it for each row. However, there ...
extract sub string from column in dataframe, iteratively
I have a dataframe that contains multiple columns. The column 'group_email" contains multiple parts of data that's relevant, and I want to extract a specific subtring from the 'group_email' column and create a new column from it for each row. However, there are multiple patterns the email follows so I have to first che...
[ ".str.extract() is a pandas.Series method while\ngroup_member_df['group_email'][ind] is a string so it doesn't have the extract() method.\nI would try something like\nprefix_dict = {\"gcp\":'(?:prod-)(.*)-',\"irm\":'^(?:[^-]*\\-){6}([^.]*)'}\nres={}\nfor prefix in prefix_dict.keys():\n mask = group_member_df.loc...
[ 0 ]
[]
[]
[ "extract", "pandas", "parsing", "python" ]
stackoverflow_0074433988_extract_pandas_parsing_python.txt
Q: Redefine categories of a categorical variable ignoring upper and lower case I have a dataset with a categorical variable that is not nicely coded. The same category appears sometimes with upper case letters and sometimes with lower case (and several variations of it). Since I have a large dataset, I would like to ...
Redefine categories of a categorical variable ignoring upper and lower case
I have a dataset with a categorical variable that is not nicely coded. The same category appears sometimes with upper case letters and sometimes with lower case (and several variations of it). Since I have a large dataset, I would like to harmonize the categories taking advantage of the categorical dtype - therefore ex...
[ "You shouldn't try to harmonize after converting to category. This renders the use of a Category pointless as one category per exact string will be created.\nYou can instead harmonize the case with str.capitalize, then convert to categorical:\ns = (pd.Series([\"male\", \"female\",\"Male\", \"FEMALE\", \"MALE\", \"M...
[ 0, 0 ]
[]
[]
[ "categorical_data", "pandas", "python" ]
stackoverflow_0074434168_categorical_data_pandas_python.txt
Q: Decrease docker build size, share conda environment between two images I’m trying to build webapp using AWS. I’ve got a docker-compose.yml that builds two images; a service image (running a flask server script) and a worker image (doing all the calculations sent to it from the flask server). services: worker: ...
Decrease docker build size, share conda environment between two images
I’m trying to build webapp using AWS. I’ve got a docker-compose.yml that builds two images; a service image (running a flask server script) and a worker image (doing all the calculations sent to it from the flask server). services: worker: image: co2gasp/worker:latest build: ./worker_app web: image : co...
[ "You indicate in the comments that the two images are identical, aside from the final command. You can override the image's ENTRYPOINT when you run the container using the Compose entrypoint: directive:\nversion: '3.8'\nservices:\n worker:\n build: .\n web:\n build: .\n entrypoint: conda run --no-captur...
[ 0 ]
[]
[]
[ "amazon_web_services", "conda", "docker", "python" ]
stackoverflow_0074430140_amazon_web_services_conda_docker_python.txt
Q: Resampling of a pandas dataframe with non-equidistant timestamp column as time line I have a pandas DataFrame object representing sensor measurements. The dataframe has a column Timestamp and several columns for the data of the sensors. The timestamps are not equidistant. The problem iam facing is, that i want the...
Resampling of a pandas dataframe with non-equidistant timestamp column as time line
I have a pandas DataFrame object representing sensor measurements. The dataframe has a column Timestamp and several columns for the data of the sensors. The timestamps are not equidistant. The problem iam facing is, that i want the dataframe to be resampled to (if possible) equidistant timestamps by filling the gap bet...
[ "You can use:\n# ensure datetime\ndf['Timestamp'] = pd.to_datetime(df['Timestamp'])\n\nout = (df.set_index('Timestamp') # temporarily set Timestamp as index\n .resample('1min').ffill() # resample and ffill\n .reset_index()[df.columns] # restore index/columns\n )\n\nNB. assuming \"Index\" is...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074434333_dataframe_pandas_python.txt
Q: Write an function that takes a string and returns the number of unique characters in the string I need a function using collections and maps, how can I improve this function using collection methods? The function works but needs to be modified to import collection methods. string = str(input()) check = [] unikal =...
Write an function that takes a string and returns the number of unique characters in the string
I need a function using collections and maps, how can I improve this function using collection methods? The function works but needs to be modified to import collection methods. string = str(input()) check = [] unikal = [] for i in string: if i in unikal: if not (i in check): check.append(i) ...
[ "you can use list method, count() :\nunique = [i for i in input() if string.count(i) == 1]\nprint(len(unique))\n\n" ]
[ 0 ]
[]
[]
[ "collections", "list", "methods", "python", "python_3.x" ]
stackoverflow_0074434232_collections_list_methods_python_python_3.x.txt
Q: program using lists in python So i have a class exercice that i have to make a program that gives me all the information about the youngest person of a group, i could do the age, it gives me the youngest age but with the names and citizen cards could not get what i've wanted. thats the code the way i tried do make...
program using lists in python
So i have a class exercice that i have to make a program that gives me all the information about the youngest person of a group, i could do the age, it gives me the youngest age but with the names and citizen cards could not get what i've wanted. thats the code the way i tried do make it. persons = [] ages = [] numbers...
[ "min is defined differently for different types. The minimum of name is going to return the minimum value lexicographically. You want to access the same person in each of the lists, so you should find the index i of the minimum age, and then the minimum name will be persons[i], and the minimum card number will be n...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074434150_list_python.txt
Q: Text as tooltip, popup or labels in folium choropleth GeoJSON polygons Folium allow to create Markers with tooltip or popup text. I would like to do the same with my GeoJSON polygons. My GeoJSON has a property called "name" (feature.properties.name -> let's assume it is the name of each US state). I would like to ...
Text as tooltip, popup or labels in folium choropleth GeoJSON polygons
Folium allow to create Markers with tooltip or popup text. I would like to do the same with my GeoJSON polygons. My GeoJSON has a property called "name" (feature.properties.name -> let's assume it is the name of each US state). I would like to be able to display this as a label in my choropleth map, in addition to the ...
[ "I've had to use folium's GeoJsonTooltip() and some other steps to get this done in the past. I'm curious to know if someone has a better way\n\nCapture the return value of the Choropleth function\nAdd a value(eg unemployment) to the Chorpleth's underlying geojson obj\nCreate GeoJsonTooltip with that value from st...
[ 9, 0 ]
[]
[]
[ "choropleth", "folium", "leaflet", "python", "python_3.x" ]
stackoverflow_0070471888_choropleth_folium_leaflet_python_python_3.x.txt
Q: How to detect pitch abnormalities in audio stream? I need to extract audio stream from a video and check whether it has any pitch changes or abnormalities. Ideally, we want to quantify any pitch changes in the audio stream. I'm aware that I can use ffmpeg to extract the audio stream from the video. However, what t...
How to detect pitch abnormalities in audio stream?
I need to extract audio stream from a video and check whether it has any pitch changes or abnormalities. Ideally, we want to quantify any pitch changes in the audio stream. I'm aware that I can use ffmpeg to extract the audio stream from the video. However, what tools or programs (python?) can then be used to identify ...
[ "Pitch analysis is not an easy task, luckily there are existing solutions for that. https://pypi.org/project/crepe/ is an example that looks promising.\nYou could read the resulting CSV of pitch data into a Pandas dataframe and perform whatever data analysis you can think of.\nFor example for the pitch change analy...
[ 1 ]
[]
[]
[ "audio", "ffmpeg", "python" ]
stackoverflow_0074434192_audio_ffmpeg_python.txt
Q: How to prepare dataset for segformer? I'm trying to train a segformer for some medical images and therefore following the Fine tuning tutorial as close as possible lnk. The dataset consists of some FMRI images and the specific lesion to segment out, these images are of the same size of the original FMRIs dataset =...
How to prepare dataset for segformer?
I'm trying to train a segformer for some medical images and therefore following the Fine tuning tutorial as close as possible lnk. The dataset consists of some FMRI images and the specific lesion to segment out, these images are of the same size of the original FMRIs dataset = Dataset.from_dict({"image": img, 'label': ...
[ "Your ground truth semantic segmentation map should be a 2D array, that contains a label for each pixel. This means that if you would convert your \"label\" feature (which is of type Image) to a NumPy array, you obtain a 2D array:\nimport numpy as np\n\nnp.array(dataset[0]['label'])\n\nThis could look like the foll...
[ 0 ]
[]
[]
[ "huggingface_datasets", "huggingface_transformers", "python" ]
stackoverflow_0072619260_huggingface_datasets_huggingface_transformers_python.txt
Q: How to install jsonnet on conda I am installing allennlp and it has quite a lot of dependencies. Everything is installing fine but the installalation of Jsonnet is failing. I tried installing jsonnet using pip install jsonnet manually but that isn't working either. A: Try the following: conda install -c conda-fo...
How to install jsonnet on conda
I am installing allennlp and it has quite a lot of dependencies. Everything is installing fine but the installalation of Jsonnet is failing. I tried installing jsonnet using pip install jsonnet manually but that isn't working either.
[ "Try the following:\nconda install -c conda-forge jsonnet\n\n" ]
[ 0 ]
[]
[]
[ "allennlp", "conda", "jsonnet", "python" ]
stackoverflow_0074434129_allennlp_conda_jsonnet_python.txt
Q: Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (32,) I'm trying to train a Keras model where a singular input is a normalized array of floats of length 512. I currently have 539 of these inputs in my training data, but the following error is produce...
Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (32,)
I'm trying to train a Keras model where a singular input is a normalized array of floats of length 512. I currently have 539 of these inputs in my training data, but the following error is produced as soon as the predict() method is called: Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, f...
[ "Well, the model is expecting you the batch_size also try this\nmodel = Sequential()\nmodel.add(Input(shape=(512)))\nmodel.add(Dense(64, activation=tf.nn.relu))\nmodel.add(Dense(1, activation=tf.nn.sigmoid))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics='accuracy')\nmodel.fit(X, y, bat...
[ 2 ]
[]
[]
[ "keras", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074434345_keras_machine_learning_python_tensorflow.txt
Q: How to compose a list of functions in steps in Python using map and reduce Given a list of functions (functions) and an integer n, I'm trying to figure out a way to compose them stepwise, and return a list of each stepwise result as follows: compose_step([lambda x: x+3, lambda x: x+5, lambda x: x+1], 8) --> [8, 11...
How to compose a list of functions in steps in Python using map and reduce
Given a list of functions (functions) and an integer n, I'm trying to figure out a way to compose them stepwise, and return a list of each stepwise result as follows: compose_step([lambda x: x+3, lambda x: x+5, lambda x: x+1], 8) --> [8, 11, 16, 17] So, as of now I have figured out how to compose a list of functions a...
[ "You can use itertools.accumulate with a composition function\nfrom itertools import accumulate\n\ndef compose(f, g):\n return lambda x: f(g(x))\n\nfuncs = [lambda x: x, lambda x: x+3, lambda x: x+5, lambda x: x+1]\n\nprint([f(8) for f in accumulate(funcs, compose)])\n# [8, 11, 16, 17]\n\n", "itertools.accumul...
[ 4, 1, 0 ]
[]
[]
[ "dictionary", "functional_programming", "python", "reduce" ]
stackoverflow_0050011450_dictionary_functional_programming_python_reduce.txt
Q: selecting duplicates by condition python pandas I have a simple dataframe which I would like to separate from each other with some conditions. Car Year Speed Cond BMW 2001 150 X BMW 2000 150 Audi 1997 200 Audi 2000 200 Audi 2012 200 X Fiat 2020 180 Mazda 2022 183 What i have to do is take duplicates to an...
selecting duplicates by condition python pandas
I have a simple dataframe which I would like to separate from each other with some conditions. Car Year Speed Cond BMW 2001 150 X BMW 2000 150 Audi 1997 200 Audi 2000 200 Audi 2012 200 X Fiat 2020 180 Mazda 2022 183 What i have to do is take duplicates to another dataframe and in my main da...
[ "If I understand correctly the desired logic, you can use groupby.idxmax to select the first X per group if any (else the first row of the group), to keep in the main DataFrame. The rest goes in the other DataFrame (df2).\n# get indices of the row with X is any, else of the first one per group\nkeep = df['Cond'].eq...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074434426_dataframe_pandas_python.txt
Q: cv2.imread file with accent (unicode) I am trying to load the following file: 'data/chapter_1/capd_yard_signs\\Dueñas_2020.png' But when I do so, cv2.imread returns an error: imread_('data/chapter_1/capd_yard_signs\Due├▒as_2020.png'): can't open/read file: check file path/integrity load file When I specifie...
cv2.imread file with accent (unicode)
I am trying to load the following file: 'data/chapter_1/capd_yard_signs\\Dueñas_2020.png' But when I do so, cv2.imread returns an error: imread_('data/chapter_1/capd_yard_signs\Due├▒as_2020.png'): can't open/read file: check file path/integrity load file When I specified the file name with os.path.join, I tried ...
[ "This is how I ended up getting it to work:\nfrom PIL import Image\npil = Image.open(f).convert('RGB') # load the image with pillow and make sure it is in RGB\npilCv = np.array(pil) # convert the image to an array\nimg = pilCv[:,:,::-1].copy() # convert the array to be in BGR\n\n" ]
[ 0 ]
[]
[]
[ "diacritics", "opencv", "os.path", "path", "python" ]
stackoverflow_0074433752_diacritics_opencv_os.path_path_python.txt
Q: Calculating from files in python I have a file containing school codes and votes for different cities. The file is like: City: California ADS, 532 SJD, 221 WPE, 239 City: Chicago ADS, 238 SJD, 233 WPE, 456 ... My questions are How to add information to the file? Let's say, I want to add DJF, 204 for Chicago, how...
Calculating from files in python
I have a file containing school codes and votes for different cities. The file is like: City: California ADS, 532 SJD, 221 WPE, 239 City: Chicago ADS, 238 SJD, 233 WPE, 456 ... My questions are How to add information to the file? Let's say, I want to add DJF, 204 for Chicago, how do I do that? How do I calculate the...
[ "Welcome to SO!\nTo achieve what you want, you can basically create a nested dictionary with key and value pair. You can then access the first level of keys and add other information in file such as DJF for Chicago. Then, you can write that dictionary to a file as json object.\nTo get the sum you can basically use ...
[ 0, 0 ]
[]
[]
[ "dictionary", "file", "python" ]
stackoverflow_0074433684_dictionary_file_python.txt
Q: How can I close the sympy plotting window? (python) My code is as below. ....(omission)... sympy.plot(func, (x,-2,20)) Then the plot window successfully pops up but it doesn't close(doesn't terminate). Is there a function similar to plt.close() in sympy plot methods? Thank you. A: Sadly, it's not fully implemen...
How can I close the sympy plotting window? (python)
My code is as below. ....(omission)... sympy.plot(func, (x,-2,20)) Then the plot window successfully pops up but it doesn't close(doesn't terminate). Is there a function similar to plt.close() in sympy plot methods? Thank you.
[ "Sadly, it's not fully implemented. Assuming that you are running your code from a Python or IPython console, to achieve your objective we need to modify a few methods.\nfrom sympy import *\nvar(\"x\")\nfrom sympy.plotting.plot import Plot, MatplotlibBackend\n\ndef show(self):\n self.process_series()\n self.f...
[ 0 ]
[]
[]
[ "plot", "python", "sympy", "terminate", "window" ]
stackoverflow_0074425950_plot_python_sympy_terminate_window.txt
Q: How to create set of sets from dictionary I need help with a problem in python. i have a python dictionary as shownenter image description here. I want to create a set of sets from the dictionary such that each set covers all the keys. for instance, i want an output like this:enter image description here. we see t...
How to create set of sets from dictionary
I need help with a problem in python. i have a python dictionary as shownenter image description here. I want to create a set of sets from the dictionary such that each set covers all the keys. for instance, i want an output like this:enter image description here. we see that each set has exactly one element from each ...
[ "import itertools\n\nset_of_tuples=itertools.product(*original_dict.values())\nlist_of_sets = [set(x) for x in bb]\n\nset_of_tuples contains all of the possible combinations of one value from each key. list_of_sets convert to output format you have a picture of.\n" ]
[ 0 ]
[]
[]
[ "data_structures", "dictionary", "python", "set" ]
stackoverflow_0074434198_data_structures_dictionary_python_set.txt
Q: How to return dictionary keys as a list in Python? With Python 2.7, I can get dictionary keys, values, or items as a list: >>> newdict = {1:0, 2:0, 3:0} >>> newdict.keys() [1, 2, 3] With Python >= 3.3, I get: >>> newdict.keys() dict_keys([1, 2, 3]) How do I get a plain list of keys with Python 3? A: This will ...
How to return dictionary keys as a list in Python?
With Python 2.7, I can get dictionary keys, values, or items as a list: >>> newdict = {1:0, 2:0, 3:0} >>> newdict.keys() [1, 2, 3] With Python >= 3.3, I get: >>> newdict.keys() dict_keys([1, 2, 3]) How do I get a plain list of keys with Python 3?
[ "This will convert the dict_keys object to a list:\nlist(newdict.keys())\n\n\nOn the other hand, you should ask yourself whether or not it matters. It is Pythonic to assume duck typing -- if it looks like a duck and it quacks like a duck, it is a duck. The dict_keys object can be iterated over just like a list. For...
[ 1494, 484, 68, 36, 30, 25, 15, 8, 6, 4, 0 ]
[ "This is the best way to get key List in one line of code\ndict_variable = {1:\"a\",2:\"b\",3:\"c\"} \n[key_val for key_val in dict_variable.keys()]\n\n" ]
[ -1 ]
[ "dictionary", "list", "python", "python_2.x", "python_3.x" ]
stackoverflow_0016819222_dictionary_list_python_python_2.x_python_3.x.txt
Q: splitting a dictionary in python into keys and values How can I take a dictionary and split it into two lists, one of keys, one of values. For example take: {'name': 'Han Solo', 'firstname': 'Han', 'lastname': 'Solo', 'age': 37, 'score': 100, 'yrclass': 10} and split it into: ['name', 'firstname', 'lastname', 'ag...
splitting a dictionary in python into keys and values
How can I take a dictionary and split it into two lists, one of keys, one of values. For example take: {'name': 'Han Solo', 'firstname': 'Han', 'lastname': 'Solo', 'age': 37, 'score': 100, 'yrclass': 10} and split it into: ['name', 'firstname', 'lastname', 'age', 'score', 'yrclass'] # and ['Han Solo', 'Han', 'Solo', 3...
[ "Not that hard, try help(dict) in a console for more info :)\nkeys = dictionary.keys()\nvalues = dictionary.values()\n\nFor both keys and values:\nitems = dictionary.items()\n\nWhich can be used to split them as well:\nkeys, values = zip(*dictionary.items())\n\nNote 0 The order of all of these is consistent within ...
[ 77, 2, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0004019639_dictionary_list_python.txt
Q: Image keeps dissapearing when position is updated I'm making this game in pygame(python) where you have to click the targets, and every time you click the target it's position get's updated. The problem is, that each time new position (code line: 27) is set to the target, it only appears for a split second but imm...
Image keeps dissapearing when position is updated
I'm making this game in pygame(python) where you have to click the targets, and every time you click the target it's position get's updated. The problem is, that each time new position (code line: 27) is set to the target, it only appears for a split second but immediately dissapears. here's the code: import pygame, ra...
[ "spawn_target is only executed once when a new target spawns. So it makes no sense to draw the target in spawn_target. You have to redraw the scene in every frame and draw the the sprite in the Group all_sprites:\nclass Target(pygame.sprite.Sprite):\n # [...]\n\n def spawn_target(self):\n # WIN.blit(se...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074433921_pygame_python.txt
Q: How to convert time format in pandas I tried convert 2018-08-22 11:13:00 (datetime64[ns]) to only 20180822 (object). I have this code: df_ICF_news['date'] = df_ICF_news['date'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d')) but don`t work: ValueError: time data '2022-10-28 11:09:00' does not match forma...
How to convert time format in pandas
I tried convert 2018-08-22 11:13:00 (datetime64[ns]) to only 20180822 (object). I have this code: df_ICF_news['date'] = df_ICF_news['date'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d')) but don`t work: ValueError: time data '2022-10-28 11:09:00' does not match format '%Y%m%d' (match)
[ "Use to_datetime directly on the Series and don't provide a format, then use dt.strftime with your output format:\ndf_ICF_news['date'] = pd.to_datetime(df_ICF_news['date']).dt.strftime('%Y%m%d')\n\n", "Considering that the dataframe is df_ICF_news and that the column date is of datetime64[ns], one option would be...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074434147_pandas_python.txt
Q: Terminate subprocess running in thread on program exit Based on the accepted answer to this question: python-subprocess-callback-when-cmd-exits I am running a subprocess in a separate thread and after the completion of the subprocess a callable is executed. All good, but the problem is that even if running the thr...
Terminate subprocess running in thread on program exit
Based on the accepted answer to this question: python-subprocess-callback-when-cmd-exits I am running a subprocess in a separate thread and after the completion of the subprocess a callable is executed. All good, but the problem is that even if running the thread as a daemon, the subprocess continues to run even after ...
[ "Use Thread.join method, which blocks main thread until this thread exits:\nif __name__ == '__main__':\n popen_with_callback(\n [\n \"bash\", \n \"-c\",\n \"for ((i=0;i<%s;i=i+1)); do echo $i; sleep 1; done\" % sys.argv[1]\n ]).join()\n print 'program ended'\n\n"...
[ 0, 0 ]
[]
[]
[ "multithreading", "python", "subprocess" ]
stackoverflow_0040995102_multithreading_python_subprocess.txt