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: Pyomo dealing with an indexed index Some context to my optimization: I have a warehouse that has stocked products that can be allocated to several retail stores. Each retail store has a monthly demand that needs to be satisifed but I would like to charge each store the highest possible price. So I have a set of st...
Pyomo dealing with an indexed index
Some context to my optimization: I have a warehouse that has stocked products that can be allocated to several retail stores. Each retail store has a monthly demand that needs to be satisifed but I would like to charge each store the highest possible price. So I have a set of stores and a set of products, but these pro...
[ "The piece that I think you are missing is an indexed set that indexes which products are available/priced for particular months. That is essentially the P_t piece that you want. So you can create a \"set of sets\" in pyomo where the inner set is indexed by another set, in this case, you have sets of products tha...
[ 1 ]
[]
[]
[ "mathematical_optimization", "optimization", "pyomo", "python" ]
stackoverflow_0074465104_mathematical_optimization_optimization_pyomo_python.txt
Q: Pyspark For Loop Not Creating Dataframes I have an initial dataframe df that looks like this: +-------+---+-----+------------------+----+-------------------+ |gender| pro|share| prediction|week| forecast_units| +------+----+-----+------------------+----+-------------------+ | Male|Polo| 0.01| 258.40542...
Pyspark For Loop Not Creating Dataframes
I have an initial dataframe df that looks like this: +-------+---+-----+------------------+----+-------------------+ |gender| pro|share| prediction|week| forecast_units| +------+----+-----+------------------+----+-------------------+ | Male|Polo| 0.01| 258.4054260253906| 37| 1809.0| | Male|Pol...
[ "If you assign the result of df.filter(... to data it will be lost (actually, that line has no effect). Try this way:\ndf_wk1, df_wk2, df_wk3, df_wk4 = [\n df.filter(df.week == weeknum).groupBy(['gender', 'pro']).pivot(\"share\").agg(first('forecast_units'))\n for weeknum in [37, 38, 39, 40]\n]\n\nHowever, df...
[ 0 ]
[]
[]
[ "databricks", "dataframe", "loops", "pyspark", "python" ]
stackoverflow_0074464717_databricks_dataframe_loops_pyspark_python.txt
Q: Multiple api calls (in separate functions) Flask, how do I make them asynchronous so they take less time? I am trying to make a Flask app. It has to make calls to different APIs. Each API call is wrapped in a function which gets and processes the response. How do I make these calls asynchronous so my app takes les...
Multiple api calls (in separate functions) Flask, how do I make them asynchronous so they take less time?
I am trying to make a Flask app. It has to make calls to different APIs. Each API call is wrapped in a function which gets and processes the response. How do I make these calls asynchronous so my app takes lesser time to load? Thanks. A sample function is here, I have a bunch of similar functions which make calls to ot...
[ "Use threading.\nfrom threading import Thread\n\ndef api_caller():\n while True:\n api_call()\n\nThread(target=api_caller).start()\napp.run(host='0.0.0.0', port=8080)\n\nHope this helps\n" ]
[ 0 ]
[]
[]
[ "flask", "python", "python_asyncio", "python_requests" ]
stackoverflow_0074463472_flask_python_python_asyncio_python_requests.txt
Q: How to determine whether or not a point is in the first quadrant with a function in python enter image description here Creating a function 'first' with input 'point' in x,y form test whether or not a point is in the first quadrant. I am unable to get the variable 'point' into (x,y) form for the function 'first' t...
How to determine whether or not a point is in the first quadrant with a function in python
enter image description here Creating a function 'first' with input 'point' in x,y form test whether or not a point is in the first quadrant. I am unable to get the variable 'point' into (x,y) form for the function 'first' to determine whether or not the point is in the first quadrant.
[ "Change the problematic line as follows:\nx,y = point\n\n" ]
[ 0 ]
[]
[]
[ "function", "if_statement", "python" ]
stackoverflow_0074466135_function_if_statement_python.txt
Q: How to filter json information into multiple values? I'm looking for a way to filter client information into variables that i can use to send emails. One of the variables im looking for is "nospam1@gmail.com" Can somebody help me with this? The code i tested is: import json with open('notion_data.json') as json_f...
How to filter json information into multiple values?
I'm looking for a way to filter client information into variables that i can use to send emails. One of the variables im looking for is "nospam1@gmail.com" Can somebody help me with this? The code i tested is: import json with open('notion_data.json') as json_file: data = json.load(json_file) if [x for x in data[...
[ "You have to dive through ALL of the intermediate objects. Assuming there are multiple results:\nfor result in data['results']:\n texttype = result['properties']['email_sender']['type']\n email = result['properties']['email_sender'][texttype][0]['text']['content']\n if email == 'nospam2@gmail.com':\n ...
[ 0 ]
[]
[]
[ "json", "python", "python_3.x" ]
stackoverflow_0074451186_json_python_python_3.x.txt
Q: Min function in Teradata unlike Python I am doing sort of a code migration from Python to Teradata: The python code is this: max = min(datetime.today(), date + timedelta(days=90)) where date variable holds a date. However, in Teradata, I know this min function won't work the same way. And, I have to get the 'date'...
Min function in Teradata unlike Python
I am doing sort of a code migration from Python to Teradata: The python code is this: max = min(datetime.today(), date + timedelta(days=90)) where date variable holds a date. However, in Teradata, I know this min function won't work the same way. And, I have to get the 'date' using a select statement. SEL min(SELECT CU...
[ "Were you looking for this one?\nSELECT LEAST(13, 6); \nSELECT LEAST( to_char(date1,'YYYYMMDD'), to_char(date2,'YYYYMMDD') ) ...\n\n", "No reason to convert to VARCHAR. Assuming DTM is TIMESTAMP(0), all you need is:\nSELECT LEAST(CAST(CURRENT_TIMESTAMP(0) AS TIMESTAMP(0)),\n MAX(DTM) + INTERVAL '90' D...
[ 1, 0 ]
[]
[]
[ "python", "sql", "teradata", "teradatasql" ]
stackoverflow_0074464896_python_sql_teradata_teradatasql.txt
Q: Python's for loops Pyhton is new to me and i'm having a little problem with the for loops, Im used to for loop in java where you can set integers as you like in the loops but can't get it right in python. the task i was given is to make a function that return True of False. the function get 3 integers: short rope ...
Python's for loops
Pyhton is new to me and i'm having a little problem with the for loops, Im used to for loop in java where you can set integers as you like in the loops but can't get it right in python. the task i was given is to make a function that return True of False. the function get 3 integers: short rope amount, long rope amount...
[]
[]
[ "The code you posted could not give you that error. On the other hand, the problem you have with the code is that in each iteration you create a new list with the current value (integer) and a string \",\". You need to append values to the list:\ndef wantedLength(short_amount, long_amount, wanted_length):\n shor...
[ -1, -1 ]
[ "python" ]
stackoverflow_0074466125_python.txt
Q: Difference between SQLAlchemy Select and Query API Not sure if this has been asked before, but in the SQLAlchemy docs they talk about introducing select() as part of the new 2.0 style for the ORM. Previously (1.x style), the query() method were used to fetch data. What is the difference between these two? For exam...
Difference between SQLAlchemy Select and Query API
Not sure if this has been asked before, but in the SQLAlchemy docs they talk about introducing select() as part of the new 2.0 style for the ORM. Previously (1.x style), the query() method were used to fetch data. What is the difference between these two? For example, for querying a Users table for a user with email an...
[ "The biggest difference is how the select statement is constructed. The new method creates a select object which is more dynamic since it can be constructed from other select statements, without explicit subquery definition:\n# select from a subqeuery styled query\nq = select(Users).filter_by(name='name', email='ma...
[ 7, 2 ]
[]
[]
[ "orm", "python", "sql", "sqlalchemy" ]
stackoverflow_0072828293_orm_python_sql_sqlalchemy.txt
Q: Concatenate two txt files Python I have two txt files, the first file contains strings separated by space, as follows: M N T F S Q V W V F S D T P S R L P E L M N G A Q A L A N Q I N T F V L N D A D G A Q A I Q L G A N H V W K L N G K P D D N T F S Q V W V F S D T P S R L P E L M N G A Q A L A N Q I N T F V L N D...
Concatenate two txt files Python
I have two txt files, the first file contains strings separated by space, as follows: M N T F S Q V W V F S D T P S R L P E L M N G A Q A L A N Q I N T F V L N D A D G A Q A I Q L G A N H V W K L N G K P D D N T F S Q V W V F S D T P S R L P E L M N G A Q A L A N Q I N T F V L N D A D G A Q A I Q L G A N H V W K L N G...
[ "Just zip the two.\nwith open(\"/home/darteagam/diploma/bert/files/bert_aa10.txt\") as f1,open(\"/home/darteagam/diploma/bert/files/out_bert_10.txt\") as f2:\n for a,b in zip(f1,f2):\n print('\\t'.join([a.strip(), b.strip()])\n\nAs a side note, it's bad practice to embed full pathnames in your code. Some...
[ 3 ]
[]
[]
[ "concatenation", "file", "python", "python_3.x", "string" ]
stackoverflow_0074466246_concatenation_file_python_python_3.x_string.txt
Q: how can implement crunch wordlist generator This is what I wrote... def brute(m,pattern=None): letters = 'abcdefghijklmnopqrstuvwxyz' spec = '#@&$%*()+' upper = letters.upper() number = '1234567890' info = {'@':spec,'^':upper,'%':letters,'*':number} chars = [info.get(p,letters) for _,p in z...
how can implement crunch wordlist generator
This is what I wrote... def brute(m,pattern=None): letters = 'abcdefghijklmnopqrstuvwxyz' spec = '#@&$%*()+' upper = letters.upper() number = '1234567890' info = {'@':spec,'^':upper,'%':letters,'*':number} chars = [info.get(p,letters) for _,p in zip(range(m),pattern or letters)] def inner(m...
[ "Here is an itertools based approach which might do what you want:\nimport itertools, string\n\ndef brute(m,pattern=None):\n if pattern is None:\n pattern = '%'*m\n letters = string.ascii_lowercase\n upper = string.ascii_uppercase\n spec = '#@&$%*()+'\n number = '1234567890'\n info = {'@':s...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074465867_python.txt
Q: FileNotFoundError: [WinError 3] The system cannot find the path specified when the files actually exist I am trying to work on copying files to a different directory based on a specific file name listed in excel. I am using shutil to copy files from one directory to another directory, but it keep showing the FileN...
FileNotFoundError: [WinError 3] The system cannot find the path specified when the files actually exist
I am trying to work on copying files to a different directory based on a specific file name listed in excel. I am using shutil to copy files from one directory to another directory, but it keep showing the FileNotFound. This is the error message: Traceback (most recent call last): File "C:\Python\HellWorld\TestCopyPa...
[ "As mentioned in comments one issue is that you aren't joining the filename to the full filepath (\"input_file\").\nI'm not really familiar with shutil but I believe the function you want to use is shutil.copy not shutil.copytree. It looks like copytree copies the directory structure of a specified source directory...
[ 0 ]
[]
[]
[ "file_copying", "filenotfounderror", "loops", "python", "shutil" ]
stackoverflow_0074463662_file_copying_filenotfounderror_loops_python_shutil.txt
Q: How to interrupt a grpc call gracefully in the client side? I wrote a client which starts multiple connections to a grpc server to request something. I want to stop all the other grpc call once I got a reply. I use an Event to control this process. However, I don't know how to terminate a grpc call gracefully. The...
How to interrupt a grpc call gracefully in the client side?
I wrote a client which starts multiple connections to a grpc server to request something. I want to stop all the other grpc call once I got a reply. I use an Event to control this process. However, I don't know how to terminate a grpc call gracefully. The below is what I did. The code will cause an error: too many open...
[ "You could use the future API on your client calls (https://grpc.github.io/grpc/python/grpc.html#grpc.UnaryUnaryMultiCallable.future) and then call cancel on the futures (https://grpc.github.io/grpc/python/grpc.html#grpc.Future.cancel).\nFull cancellation example in Python: https://github.com/grpc/grpc/tree/master/...
[ 0 ]
[]
[]
[ "grpc_python", "multithreading", "python" ]
stackoverflow_0074384177_grpc_python_multithreading_python.txt
Q: Is it possible to use RPi.GPIO library in docker? I used the official docker image of flask. And installed the rpi.gpio library in the container pip install rpi.gpio It's succeeded: root@e31ba5814e51:/app# pip install rpi.gpio Collecting rpi.gpio Downloading RPi.GPIO-0.7.0.tar.gz (30 kB) Building wheels for col...
Is it possible to use RPi.GPIO library in docker?
I used the official docker image of flask. And installed the rpi.gpio library in the container pip install rpi.gpio It's succeeded: root@e31ba5814e51:/app# pip install rpi.gpio Collecting rpi.gpio Downloading RPi.GPIO-0.7.0.tar.gz (30 kB) Building wheels for collected packages: rpi.gpio Building wheel for rpi.gpio...
[ "First make sure you're running Docker container as \"privileged\" like so:\ndocker run --privileged -it debian:latest\n\nAlso, double check that you're running an image that is meant to run on your processor.\nFor example, if you try to run \"debian:latest\" on your Raspberry Pi 4 it will actually pull \"arm32v7/d...
[ 0, 0 ]
[]
[]
[ "docker", "python", "raspberry_pi4" ]
stackoverflow_0064926963_docker_python_raspberry_pi4.txt
Q: How to insert table name into query as variable? I'm trying to make a query to select a table from database. I created a list of table names and exported it to a list, saved necessary list fields as variables, then inserted these variables into a database query to export data. I do not initially know name of table...
How to insert table name into query as variable?
I'm trying to make a query to select a table from database. I created a list of table names and exported it to a list, saved necessary list fields as variables, then inserted these variables into a database query to export data. I do not initially know name of table but find it through logic and write it to a variable....
[]
[]
[ "This would be the easiest solution I guess:\nsql = \"select * from \" + stroka_uch\ntable = pd.read_sql_query(sql = sql, con = conn)\n" ]
[ -1 ]
[ "python", "sql", "sqlite" ]
stackoverflow_0074465414_python_sql_sqlite.txt
Q: Search and replace all cells with a certain value with openpyxl For my job I have large amount of excel files in which I have to replace certain values. I just started with openpyxl and tried the following code: import openpyxl from openpyxl import load_workbook wb1 = load_workbook(filename = 'testfile.xlsx') ws1 ...
Search and replace all cells with a certain value with openpyxl
For my job I have large amount of excel files in which I have to replace certain values. I just started with openpyxl and tried the following code: import openpyxl from openpyxl import load_workbook wb1 = load_workbook(filename = 'testfile.xlsx') ws1 = wb1.active i = 0 for r in range(1,ws1.max_row+1): for c in ra...
[ "You are trying to iterate through a type which is not iterable in the following:\nor 'NM181841' in s:\n\nWhat this line practically says is: \"find 'NM181841' in 's'\" thus it would required to loop through 's' which is not possible since\nTypeError: argument of type 'NoneType' is not iterable\n\n", "I found my...
[ 1, 0 ]
[]
[]
[ "jupyter_notebook", "openpyxl", "python" ]
stackoverflow_0074466196_jupyter_notebook_openpyxl_python.txt
Q: ModuleNotFoundError: No module named 'pydantic' from pydantic import BaseModel on debug mode with PyCharm also after install pydantic print ModuleNotFoundError: No module named 'pydantic' A: I found the solution: open PyCharm preferences and install from Pycharm the package. A: Try this: sudo pip3 install py...
ModuleNotFoundError: No module named 'pydantic'
from pydantic import BaseModel on debug mode with PyCharm also after install pydantic print ModuleNotFoundError: No module named 'pydantic'
[ "I found the solution: open PyCharm preferences and install from Pycharm the package.\n", "Try this:\nsudo pip3 install pydantic\n\nand it works.\n", "If you are getting the error while using pipenv then you need to install pydantic by using pipenv install pydantic command.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0064257411_python.txt
Q: TypeError: generatecode() takes 0 positional arguments but 1 was given I have the code below: from tkinter import * class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): sel...
TypeError: generatecode() takes 0 positional arguments but 1 was given
I have the code below: from tkinter import * class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.master.title("COD:WWII Codes") self.pack(fill=BOTH, expand=1) ...
[ "When you call a method on a class (such as generatecode() in this case), Python automatically passes self as the first argument to the function. So when you call self.my_func(), it's more like calling MyClass.my_func(self).\nSo when Python tells you \"generatecode() takes 0 positional arguments but 1 was given\", ...
[ 72, 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0043839536_python_tkinter.txt
Q: Converting Dataframe column to datetime doesn't complete I am trying to convert a column of a large dataset (660k rows) into datetime type in Jupyter notebook. I have found two ways to do it: pd.to_datetime(df['local_time'],format='%d/%m/%Y') df['local_time'].astype("datetime64[ns]") but none of them complete ev...
Converting Dataframe column to datetime doesn't complete
I am trying to convert a column of a large dataset (660k rows) into datetime type in Jupyter notebook. I have found two ways to do it: pd.to_datetime(df['local_time'],format='%d/%m/%Y') df['local_time'].astype("datetime64[ns]") but none of them complete even in couple hours. Is there a way to make it faster? It doesn...
[ "I am not sure what was the reason behind it, but I was converting multiple columns at once and the time increased many many times.\ndf[['date_1', 'date_2', 'date_3', 'date_4']] = df[['date_1', 'date_2', 'date_3', 'date_4']].astype('datetime64[ns]')\n\nafter doing everything in separate steps, time became decent\n...
[ 0 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074447407_dataframe_datetime_pandas_python.txt
Q: Add new column with calculated values I want to add a new column called 'NormalizedAnnualCompensation' to my df and populate the column with values from one of three calculations: keep value 2 if value 1 is labeled "Yearly", or multiply it by 12 if labeled "Monthly", or multiply it by 52 if labeled "Weekly." T...
Add new column with calculated values
I want to add a new column called 'NormalizedAnnualCompensation' to my df and populate the column with values from one of three calculations: keep value 2 if value 1 is labeled "Yearly", or multiply it by 12 if labeled "Monthly", or multiply it by 52 if labeled "Weekly." The two existing columns have dtype INT64. ...
[ "Try using DataFrame.replaceto compute the factor for \"CompTotal\":\nimport pandas as pd\n\ndf = pd.DataFrame([\n {\"CompFreq\": \"Yearly\", \"CompTotal\": 100}, \n {\"CompFreq\": \"Monthly\", \"CompTotal\": 10}, \n {\"CompFreq\": \"Weekly\", \"CompTotal\": 1},\n])\n\nfactor = df[\"CompFreq\"].replace({\"...
[ 0 ]
[]
[]
[ "calculated_columns", "python" ]
stackoverflow_0074465142_calculated_columns_python.txt
Q: write multi dimensional numpy array to many files I was wondering if there was a more efficient way of doing the following without using loops. I have a numpy array with the shape (i, x, y, z). Essentially I have i elements of the shape (x, y, z). I want to write each element to a separate file so that I have i fi...
write multi dimensional numpy array to many files
I was wondering if there was a more efficient way of doing the following without using loops. I have a numpy array with the shape (i, x, y, z). Essentially I have i elements of the shape (x, y, z). I want to write each element to a separate file so that I have i files, each with the data from a single element. In my ca...
[ "This sounds very suitable for multiprocessing, as the different elements need to be processed separately and can be save to disk independantly.\nPython has a usefull package for this, called multiprocessing, with a variety of pooling, processing, and other options.\nHere's a simple (and comment-documented) example...
[ 0 ]
[]
[]
[ "arrays", "multidimensional_array", "numpy", "python" ]
stackoverflow_0074466262_arrays_multidimensional_array_numpy_python.txt
Q: multiprocessing: instances unaffected when iterating over them I'm trying to use the multiprocessing module to run in parallel the same method over a list object instances. The closest question that I've found is "apply-a-method-to-a-list-of-objects-in-parallel-using-multi-processing". However the solution given t...
multiprocessing: instances unaffected when iterating over them
I'm trying to use the multiprocessing module to run in parallel the same method over a list object instances. The closest question that I've found is "apply-a-method-to-a-list-of-objects-in-parallel-using-multi-processing". However the solution given there seems to not work in my problem. Here is an example of what I'm...
[ "You can create managed objects from your Foo class just like the multiprocessing.managers.SyncManager instance created with a call to multiptocessing.Manager() can create certain managed objects such as a list or dict. What is returned is a special proxy object that is shareable among processes. When method calls ...
[ 2 ]
[]
[]
[ "multiprocessing", "oop", "python" ]
stackoverflow_0074464496_multiprocessing_oop_python.txt
Q: Open GUI while algo is running in the background I am attempting to keep Output running in the background while having an open GUI. The GUI displays the finding from the Algo just fine. But it does not continue to run in the background. Also, I am trying to get the Output to repeat from new, not continue. Hope you...
Open GUI while algo is running in the background
I am attempting to keep Output running in the background while having an open GUI. The GUI displays the finding from the Algo just fine. But it does not continue to run in the background. Also, I am trying to get the Output to repeat from new, not continue. Hope you can help. Output = Output[Output['Match_Acc.'] >= 1] ...
[ "Window closed after statement sg.Window(\"Overview\", layout).read(close=True). With method window.hide() to hide the window, window.un_hide to show the window again.\nfrom random import randint\nfrom time import sleep\nimport threading\nimport PySimpleGUI as sg\n\ndef algo(window):\n global running\n while ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "pysimplegui", "python", "schedule" ]
stackoverflow_0074466049_dataframe_pandas_pysimplegui_python_schedule.txt
Q: python 3 datetime difference in microseconds giving wrong answer for a long operation I'm doing a delete operation of 3000 elements from a binary search tree of size 6000 ( sorted therefore one sided tree). I need to calculate the time taken for completing all the deletes I did this bst2 = foo.BinarySearchTree...
python 3 datetime difference in microseconds giving wrong answer for a long operation
I'm doing a delete operation of 3000 elements from a binary search tree of size 6000 ( sorted therefore one sided tree). I need to calculate the time taken for completing all the deletes I did this bst2 = foo.BinarySearchTree() #init insert_all_to_tree(bst2,insert_lines) #insert 6000 elements start = dateti...
[ "datetime.now() returns a datetime, so doing math with it doesn't work out. You want to either use time.time() (Python < v3.3), time.perf_counter() (Python v3.3 until v3.7) or time.perf_counter_ns() (Python > v3.7).\ntime.time() and time.perf_counter() both return float, and time.perf_counter_ns() returns int.\n" ]
[ 0 ]
[]
[]
[ "binary_search_tree", "datetime", "python", "python_3.x", "python_datetime" ]
stackoverflow_0074466406_binary_search_tree_datetime_python_python_3.x_python_datetime.txt
Q: How to count sum of prime numbers without a number 3? I have to count the sum of all prime numbers that are less than 1000 and do not contain the digit 3. My code: def primes_sum(lower, upper): total = 0 for num in range(lower, upper + 1): if not num % 3 and num % 10: continue e...
How to count sum of prime numbers without a number 3?
I have to count the sum of all prime numbers that are less than 1000 and do not contain the digit 3. My code: def primes_sum(lower, upper): total = 0 for num in range(lower, upper + 1): if not num % 3 and num % 10: continue elif num > 1: for i in range(2, num): ...
[ "def primes_sum(lower, upper):\n \"\"\"Assume upper>=lower>2\"\"\"\n primes = [2]\n answer = 2\n for num in range(lower, upper+1):\n if any(num%p==0 for p in primes): continue # not a prime\n\n primes.append(num)\n\n if '3' in str(num): continue\n answer += num\n\n return...
[ 0 ]
[]
[]
[ "function", "primes", "python", "python_3.x" ]
stackoverflow_0074466398_function_primes_python_python_3.x.txt
Q: convert nested dictionary into pandas dataframe example dictionary: sample_dict = {'doctor': {'docter_a': 26, 'docter_b': 40, 'docter_c': 42}, 'teacher': {'teacher_x': 21, 'teacher_y': 45, 'teacher_z': 33}} output dataframe: job person age doctor |doctor_a | 26 doctor |doctor_b | 40 doctor...
convert nested dictionary into pandas dataframe
example dictionary: sample_dict = {'doctor': {'docter_a': 26, 'docter_b': 40, 'docter_c': 42}, 'teacher': {'teacher_x': 21, 'teacher_y': 45, 'teacher_z': 33}} output dataframe: job person age doctor |doctor_a | 26 doctor |doctor_b | 40 doctor |doctor_c | 42 teacher|teacher_x| 21 teacher|teacher...
[ "Use a nested list comprehension:\npd.DataFrame([[k1, k2, v]\n for k1,d in sample_dict.items() \n for k2,v in d.items()],\n columns=['job', 'person', 'age'])\n\nOutput:\n job person age\n0 doctor docter_a 26\n1 doctor docter_b 40\n2 doctor docter_c ...
[ 4, 1 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074466086_dataframe_dictionary_pandas_python.txt
Q: How to reduce a fraction within a class? I'm trying to reduce(self) to return fractions which have the lowest value. This is the code I have: class fraction: def __init__(self,numerator,denominator): self.numerator = numerator self.denominator = denominator self.reduce() def get_num...
How to reduce a fraction within a class?
I'm trying to reduce(self) to return fractions which have the lowest value. This is the code I have: class fraction: def __init__(self,numerator,denominator): self.numerator = numerator self.denominator = denominator self.reduce() def get_numerator(self): return self.numerator ...
[]
[]
[ "You can implement reduce() using Greatest Common Divisor. As @NickODell said in comment this GCD algorithm is described in Euclidean Algorithm Wiki. And implemented in my code below:\nTry it online!\nclass fraction:\n def __init__(self, numerator, denominator):\n self.numerator = numerator\n self....
[ -1 ]
[ "python" ]
stackoverflow_0074466397_python.txt
Q: Python: Assign Value if None Exists I am a RoR programmer new to Python. I am trying to find the syntax that will allow me to set a variable to a specific value only if it wasn't previously assigned. Basically I want: # only if var1 has not been previously assigned var1 = 4 A: You should initialize variables to...
Python: Assign Value if None Exists
I am a RoR programmer new to Python. I am trying to find the syntax that will allow me to set a variable to a specific value only if it wasn't previously assigned. Basically I want: # only if var1 has not been previously assigned var1 = 4
[ "You should initialize variables to None and then check it:\nvar1 = None\nif var1 is None:\n var1 = 4\n\nWhich can be written in one line as:\nvar1 = 4 if var1 is None else var1\n\nor using shortcut (but checking against None is recommended)\nvar1 = var1 or 4\n\nalternatively if you will not have anything assign...
[ 151, 55, 37, 26, 17, 7, 4, 0, 0 ]
[]
[]
[ "language_comparisons", "python", "python_2.7", "variable_assignment" ]
stackoverflow_0007338501_language_comparisons_python_python_2.7_variable_assignment.txt
Q: How to plot day in x axis, time in y axis and a heatmap plot for the values in python as shown in the figure? I want a heat map plot as can be seen in the attached image day in x axis, time in y axis and a heatmap plot data- https://1drv.ms/x/s!Av8bxRzsdiR7tEYmXDBWSUKriCSJ?e=m2objJ I tried plotting the data, but i...
How to plot day in x axis, time in y axis and a heatmap plot for the values in python as shown in the figure?
I want a heat map plot as can be seen in the attached image day in x axis, time in y axis and a heatmap plot data- https://1drv.ms/x/s!Av8bxRzsdiR7tEYmXDBWSUKriCSJ?e=m2objJ I tried plotting the data, but its leading to daily plots of the values
[ "Because the data is wrapped by row, you need to do some work to reshape it into the correct structure. For a 2D Contour like you linked, you need a 2D array of data, so after loading in your data-set, all I did was manipulate it into the correct shape, and then plot.\nimport numpy as np\nimport matplotlib.pyplot a...
[ 0 ]
[]
[]
[ "data_analysis", "data_science", "heatmap", "python", "timeserieschart" ]
stackoverflow_0074465808_data_analysis_data_science_heatmap_python_timeserieschart.txt
Q: OpenCV - Reading a 16 bit grayscale image I'm trying to read a 16 bit grayscale image using OpenCV 2.4 in Python, but it seems to be loading it as 8 bit. I'm doing: im = cv2.imread(path,0) print im [[25 25 28 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] ..., How do I get it as 16 bit? A: F...
OpenCV - Reading a 16 bit grayscale image
I'm trying to read a 16 bit grayscale image using OpenCV 2.4 in Python, but it seems to be loading it as 8 bit. I'm doing: im = cv2.imread(path,0) print im [[25 25 28 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] ..., How do I get it as 16 bit?
[ "Figured it out. In case anyone else runs into this problem:\nim = cv2.imread(path,-1)\n\nSetting the flag to 0, to load as grayscale, seems to default to 8 bit. Setting the flag to -1 loads the image as is.\n", "To improve readability use the flag cv2.IMREAD_ANYDEPTH\nimage = cv2.imread( path, cv2.IMREAD_ANYDEPT...
[ 45, 34, 9, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0010969585_opencv_python.txt
Q: How to solve Python TypeError: type not understood I am creating a recommendation system and when I run this code I'm getting an error: from scipy.sparse.linalg import svds # Singular Value Decomposition U, sigma, Vt = svds(pivot_df, k = 10) And I'm getting this error: "TypeError: type not understood". What c...
How to solve Python TypeError: type not understood
I am creating a recommendation system and when I run this code I'm getting an error: from scipy.sparse.linalg import svds # Singular Value Decomposition U, sigma, Vt = svds(pivot_df, k = 10) And I'm getting this error: "TypeError: type not understood". What could be the reason for this error and how should I solve...
[ "svds() takes a sparse matrix or an ndarray as input.\nBut what you are passing is a Dataframe. Check the type by using the below command.\ntype(pivot_df)\n\nHence, you need to convert the Dataframe to np.ndarray while passing it to svds().\nU, sigma, Vt = svds(pivot_df.to_numpy(), k=10)\n\n" ]
[ 0 ]
[]
[]
[ "python", "recommendation_engine", "scipy", "typeerror" ]
stackoverflow_0071941099_python_recommendation_engine_scipy_typeerror.txt
Q: Random indexing of large Json file compressed as Gzip I have a large json file (Wikidata dump, to be more specific) compressed as gzip. What I want to achieve is build an index, such that I can do random access and retrieve the line/entity I desire. The brute force way to find a line (entity) of interest would be:...
Random indexing of large Json file compressed as Gzip
I have a large json file (Wikidata dump, to be more specific) compressed as gzip. What I want to achieve is build an index, such that I can do random access and retrieve the line/entity I desire. The brute force way to find a line (entity) of interest would be: from gzip import GzipFile with GzipFile("path-to-wikidata...
[ "Thanks to the comment by Mark Adler, I was able to resolve the issue by pre-computing and storing two index files on disk. The first one being a dictionary, mentioned in the question, where I can map from each entity id, e.g., Q31, to the offset and length in the latest-all.json.gz file. The second, helps to achie...
[ 0 ]
[]
[]
[ "gzip", "json", "python", "wikidata" ]
stackoverflow_0074460186_gzip_json_python_wikidata.txt
Q: How to get the list of children and grandchildren from a nested structure? Given this dictionary of parent-children relations, { 2: [8, 7], 8: [9, 10], 10: [11], 15: [16, 17], } I'd like to get the list of all children, grandchildren, great-grandchildren, etc. -- e.g. given a parent with an ID 2 I...
How to get the list of children and grandchildren from a nested structure?
Given this dictionary of parent-children relations, { 2: [8, 7], 8: [9, 10], 10: [11], 15: [16, 17], } I'd like to get the list of all children, grandchildren, great-grandchildren, etc. -- e.g. given a parent with an ID 2 I want to get the following list: [8, 7, 9, 10, 11]. The number of nesting levels...
[ "Since cycles aren't possible and the order is not important, the easiest way to do this is with a generator function. Just yield the children and yield from the results of recursion. This will give you a depth first result:\nlinks = {\n 2: [8, 7],\n 8: [9, 10],\n 10: [11],\n 15: [16, 17],\n}\n\ndef get...
[ 1 ]
[]
[]
[ "grandchild", "parent_child", "python", "recursion" ]
stackoverflow_0074466128_grandchild_parent_child_python_recursion.txt
Q: Install MySQL Client in Django Show Error Hi I am trying to install Mysqlclient in Django and I got this message collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collec...
Install MySQL Client in Django Show Error
Hi I am trying to install Mysqlclient in Django and I got this message collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for ...
[ "You have downloaded the wrong wheel. The error message says you tried to install mysqlclient-1.4.2-cp38-cp38m-win_amd64.whl, which is for Python 3.8. \nSince you are using Python 3.7, you should use either mysqlclient‑1.4.2‑cp37‑cp37m‑win32.whl or mysqlclient‑1.4.2‑cp37‑cp37m‑win_amd64.whl depending on whether you...
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0056643488_django_mysql_python.txt
Q: Can you compare strings in python like in Java with .equals? Can you compare strings in Python in any other way apart from ==? Is there anything like .equals in Java? A: There are two ways to do this. The first is to use the operator module, which contains functions for all of the mathematical operators: >>> f...
Can you compare strings in python like in Java with .equals?
Can you compare strings in Python in any other way apart from ==? Is there anything like .equals in Java?
[ "There are two ways to do this. The first is to use the operator module, which contains functions for all of the mathematical operators:\n>>> from operator import eq\n>>> x = \"a\"\n>>> y = \"a\"\n>>> eq(x, y)\nTrue\n>>> y = \"b\"\n>>> eq(x, y)\nFalse\n>>>\n\nThe other is to use the __eq__ method of a string, whic...
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "comparison", "python", "string" ]
stackoverflow_0019965595_comparison_python_string.txt
Q: How can I create a desktop shortcut for Jupyter Notebook(Anaconda) on Mac? I am new to Jupyter Notebook. I mainly use it for my Python class. I installed Jupyter Notebook via Anaconda. So, to open Jupyter Notebook, I have to open the anaconda navigator every time. Is there any way to bypass this in MacOS and open ...
How can I create a desktop shortcut for Jupyter Notebook(Anaconda) on Mac?
I am new to Jupyter Notebook. I mainly use it for my Python class. I installed Jupyter Notebook via Anaconda. So, to open Jupyter Notebook, I have to open the anaconda navigator every time. Is there any way to bypass this in MacOS and open Notebook directly? I have tried making a terminal shell script with the followin...
[ "Jupyter App Issue:\nThere are many ways you might go about doing this. All of them will be more or less complicated to do because Jupyter itself isn't built to be used as a desktop app.\nIf you do want to try a few DIY ways, this one has a few answers that might be helpful: Open an ipython notebook via double-clic...
[ 1 ]
[]
[]
[ "anaconda", "jupyter", "jupyter_notebook", "macos", "python" ]
stackoverflow_0068993034_anaconda_jupyter_jupyter_notebook_macos_python.txt
Q: How to use Python with Selenium to click the "Load More" button on "https://github.com/topics"? I just need to click the load more button once to reveal a bunch more information so that I can scrape more HTML than what is loaded. The following "should" go to github.com/topics and find the one and only button eleme...
How to use Python with Selenium to click the "Load More" button on "https://github.com/topics"?
I just need to click the load more button once to reveal a bunch more information so that I can scrape more HTML than what is loaded. The following "should" go to github.com/topics and find the one and only button element and click it one time. from selenium import webdriver from selenium.webdriver.common.by import By ...
[ "There are several issues with your code:\n\nThe \"Load more\" button is initially out of the view, so you have to scroll the page in order to click it.\nYour locator is bad.\nYou need to wait for elements to appear on the page before accessing them. WebDriverWait expected_conditions explicit waits should be used f...
[ 0, 0 ]
[]
[]
[ "html", "python", "selenium", "selenium_edgedriver", "web_scraping" ]
stackoverflow_0074464469_html_python_selenium_selenium_edgedriver_web_scraping.txt
Q: Replace all cells with "-1" in DataFrame I have a dataframe like so: RANK COUNT '2020-01-01' 100 -1 '2020-01-02' 50 -1 '2020-01-03' -1 75 How can I replace all occurrences of -1 with None and still preserve both the RANK and COUNT as ints? The result should l...
Replace all cells with "-1" in DataFrame
I have a dataframe like so: RANK COUNT '2020-01-01' 100 -1 '2020-01-02' 50 -1 '2020-01-03' -1 75 How can I replace all occurrences of -1 with None and still preserve both the RANK and COUNT as ints? The result should look like: RANK COUNT '2020...
[ "using replace, replace -1 with \"\"\nout = df.replace(-1, \"\")\n\n RANK COUNT\n'2020-01-01' 100 \n'2020-01-02' 50 \n'2020-01-03' 75\n\n" ]
[ 1 ]
[ "df = df.replace(-1, \"\")\n\nSecond Method\ndf['RANK'] = df['RANK'].astype(str)\ndf['COUNT'] = df['COUNT'].astype(str)\ndf = df.replace('-1', \"\")\ndf['RANK'] = df['RANK'].astype(int)\ndf['COUNT'] = df['COUNT'].astype(int)\n\n" ]
[ -2 ]
[ "pandas", "python" ]
stackoverflow_0074466654_pandas_python.txt
Q: How to use multiple exceptions conditions properly? I am working with many files and this is an example of a smaller portion. Imagine I have my file names inside a list like this: filelist = ["file1.csv", "file2.csv", "file3.csv"] I would like to import them as a dataframe. If I am not able to do this condition, ...
How to use multiple exceptions conditions properly?
I am working with many files and this is an example of a smaller portion. Imagine I have my file names inside a list like this: filelist = ["file1.csv", "file2.csv", "file3.csv"] I would like to import them as a dataframe. If I am not able to do this condition, I would try another way... and if I still don't get it, I...
[ "You need a nested try/except for the case where the second file is not found.\nerrorfiles = []\nfor file in filelist:\n try:\n df = pd.read_csv(file)\n except FileNotFoundError:\n try:\n df = pd.read_csv(file + \".csv\")\n except FileNotFoundError:\n errorfiles.appe...
[ 1 ]
[]
[]
[ "python", "try_except" ]
stackoverflow_0074466465_python_try_except.txt
Q: How do I return an array of pixel values using kernel to condense them (blur)? *Python* So, what I'm trying to do is take an image (let's say 100x100) and do a 5x5 kernel over the image: kernel = np.ones((5, 5), np.float32)/25 and then output an array for each iteration of the kernel (like in cv2.filter2D) like: ...
How do I return an array of pixel values using kernel to condense them (blur)? *Python*
So, what I'm trying to do is take an image (let's say 100x100) and do a 5x5 kernel over the image: kernel = np.ones((5, 5), np.float32)/25 and then output an array for each iteration of the kernel (like in cv2.filter2D) like: kernel_vals.append(np.array([[indexOfKernelIteration], [newArrayOfEditedKernelValues]])) Wha...
[ "imread returns an np.array, so if i understand what you want to do, you have the solution in the question. For completeness sake, see the code below.\nimport cv2\n\nimg = cv2.imread(\"image.png\", cv2.IMREAD_GRAYSCALE)\nprint(type(img))\nprint(img[:10, :10])\n\nkernel = np.ones((5, 5), np.float32)/25\nkernel_vals ...
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074466216_opencv_python.txt
Q: Matplotlib print values on bars in subplots Using the above code, I have created 5 five subplots: values = {"x_values" : ["ENN", "CNN", "ENN-CNN"], "eu" : [11, 79.97, 91], "man" : [11, 80, 90], "min3" : [11, 79.70, 90], "min4" : [11, 79.50, 90], "che" : [12, 78, 89]} df = pd.DataFrame(data=values) fig, axs = plt...
Matplotlib print values on bars in subplots
Using the above code, I have created 5 five subplots: values = {"x_values" : ["ENN", "CNN", "ENN-CNN"], "eu" : [11, 79.97, 91], "man" : [11, 80, 90], "min3" : [11, 79.70, 90], "min4" : [11, 79.50, 90], "che" : [12, 78, 89]} df = pd.DataFrame(data=values) fig, axs = plt.subplots(2, 3, figsize=(10,6)) eu = axs[0, 0].b...
[ "Try this using bar_label in matplotlib 3.4.0+:\nvalues = {\"x_values\" : [\"ENN\", \"CNN\", \"ENN-CNN\"],\n\"eu\" : [11, 79.97, 91],\n\"man\" : [11, 80, 90],\n\"min3\" : [11, 79.70, 90],\n\"min4\" : [11, 79.50, 90],\n\"che\" : [12, 78, 89]}\n\ndf = pd.DataFrame(data=values)\n\nfig, axs = plt.subplots(2, 3, figsize...
[ 2, 1 ]
[]
[]
[ "matplotlib", "python", "python_3.x" ]
stackoverflow_0074466407_matplotlib_python_python_3.x.txt
Q: IN clause for Oracle Prepared Statement in Python cx_Oracle I'd like to use the IN clause with a prepared Oracle statement using cx_Oracle in Python. E.g. query - select name from employee where id in ('101', '102', '103') On python side, I have a list [101, 102, 103] which I converted to a string like this ('101'...
IN clause for Oracle Prepared Statement in Python cx_Oracle
I'd like to use the IN clause with a prepared Oracle statement using cx_Oracle in Python. E.g. query - select name from employee where id in ('101', '102', '103') On python side, I have a list [101, 102, 103] which I converted to a string like this ('101', '102', '103') and used the following code in python - import c...
[ "This concept is not supported by Oracle -- and you are definitely not the first person to try this approach either! You must either:\n\ncreate separate bind variables for each in value -- something that is fairly easy and straightforward to do in Python\ncreate a subquery using the cast operator on Oracle types as...
[ 5, 0 ]
[ "Otra opción es dar formato a una cadena con la consulta.\nimport cx_Oracle\nids = [101, 102, 103]\nALL_IDS = \"('{0}')\".format(\"','\".join(map(str, ids)))\nconn = cx_Oracle.connect('username', 'pass', 'schema')\ncursor = conn.cursor()\n\nquery = \"\"\"\nselect name from employee where id in ('{}')\n\"\"\".format...
[ -1, -3 ]
[ "cx_oracle", "oracle", "prepared_statement", "python" ]
stackoverflow_0040954293_cx_oracle_oracle_prepared_statement_python.txt
Q: Calling Stored Procedures is much slower than just calling insert and bulk insert is basically the same, Why? I have a table and a stored procedure like following, CREATE TABLE `inspect_call` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `task_id` bigint(20) unsigned NOT NULL DEFAULT '0', `cc_number` v...
Calling Stored Procedures is much slower than just calling insert and bulk insert is basically the same, Why?
I have a table and a stored procedure like following, CREATE TABLE `inspect_call` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `task_id` bigint(20) unsigned NOT NULL DEFAULT '0', `cc_number` varchar(63) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', `created_at` bigint(20) unsigned NOT NULL DEFAULT '0',...
[ "Your example won't give credit to stored procedure because it won't use any advantages of stored procedure.\nMain advantages of stored procedures are :\n\nit's compiled\nit saves network exchanges (as computations operate on the server side)\n\nImagine you have a logic enough complex not to be operated by UPDATE a...
[ 1, 1 ]
[]
[]
[ "bulkinsert", "mysql", "python", "stored_functions" ]
stackoverflow_0074457656_bulkinsert_mysql_python_stored_functions.txt
Q: 'tuple' object has no attribute 'strip' I want to receive the text australia and trim all the extra characters. I am trying to achive this using strip, but getting an error result = [('australia',)] result = result[0].strip('(') File "./prog.py", line 2, in <module> AttributeError: 'tuple' object has no attribu...
'tuple' object has no attribute 'strip'
I want to receive the text australia and trim all the extra characters. I am trying to achive this using strip, but getting an error result = [('australia',)] result = result[0].strip('(') File "./prog.py", line 2, in <module> AttributeError: 'tuple' object has no attribute 'strip' What is the right way to achieve ...
[ "The ( is not part of a string value; you have a 1-element tuple as the first list item, and you need to index it: result = result[0][0].\n>>> result = [('australia',)]\n>>> result[0]\n('australia',)\n>>> result[0][0]\n'australia'\n\n" ]
[ 1 ]
[]
[]
[ "python", "strip", "tuples" ]
stackoverflow_0074466795_python_strip_tuples.txt
Q: Pandas Specific Pivot of DataFrame I am trying to reshape a given DataFrame ts type value1 value2 0 1 foo 10 16 1 1 bar 11 17 2 2 foo 12 18 3 2 bar 13 19 4 3 foo 14 20 5 3 bar 15 21 into the following shape: foo bar ...
Pandas Specific Pivot of DataFrame
I am trying to reshape a given DataFrame ts type value1 value2 0 1 foo 10 16 1 1 bar 11 17 2 2 foo 12 18 3 2 bar 13 19 4 3 foo 14 20 5 3 bar 15 21 into the following shape: foo bar value1 value2 value1 value2 1 10 ...
[ "here is one way to do it\ndf.set_index(['type','ts']).unstack(0).swaplevel(axis=1).sort_index(axis=1)\n\ntype bar foo\n value1 value2 value1 value2\nts \n1 11 17 10 16\n2 13 19 12 18\n3 15 21 14 20\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074466758_pandas_python.txt
Q: Why does my Django form data not appear in the database? I try to develop a simple input form to save a deposit for a fishing vessel. The vessel and the net are tables in the database. There is no error when the form is submitted but there is nothing happening in the background. I use a PostgreSQL database with Pg...
Why does my Django form data not appear in the database?
I try to develop a simple input form to save a deposit for a fishing vessel. The vessel and the net are tables in the database. There is no error when the form is submitted but there is nothing happening in the background. I use a PostgreSQL database with PgAdmin for insights.I am a little bit stuck since it's my first...
[ "This is more of a troubleshooting suggestion, but hard to show in a comment. Your form might not be validating for some reason or another - add this to see if there are errors:\ndef put_deposit(request):\n if request.POST: \n form = UploadForm(request.POST)\n print(request)\n if form.is...
[ 0, 0 ]
[]
[]
[ "django", "forms", "postgresql", "python" ]
stackoverflow_0074466074_django_forms_postgresql_python.txt
Q: Placing key/value pairs from dict into .set() values in Tkinter In Tkinter, I'm trying to place key/value pairs from a dictionary called 'headers' inside the set() pairs in the set_values tuple below. Before this process I open a json file, deserialize the data into a dictionary called headers. This dictionary is ...
Placing key/value pairs from dict into .set() values in Tkinter
In Tkinter, I'm trying to place key/value pairs from a dictionary called 'headers' inside the set() pairs in the set_values tuple below. Before this process I open a json file, deserialize the data into a dictionary called headers. This dictionary is for API headers in the Tkinter App. The set_value pairs are 5 pairs o...
[ "I'm not 100% clear on what you're after, but if I understand correctly: you want to split up key/value pairs from a JSON dictionary into pairs of tkinter Entry widgets?\nIf that's the case, then here is an example of how to do that in a loop:\nimport tkinter as tk\n\n\nroot = tk.Tk()\n# get your values however you...
[ 1 ]
[]
[]
[ "dictionary", "python", "python_3.x", "tkinter" ]
stackoverflow_0074465596_dictionary_python_python_3.x_tkinter.txt
Q: psycopg2.OperationalError: FATAL: password authentication failed for user "" I am a fairly new to web developement. First I deployed a static website on my vps (Ubuntu 16.04) without problem and then I tried to add a blog app to it. It works well locally with PostgreSQL but I can't make it work on my server. It se...
psycopg2.OperationalError: FATAL: password authentication failed for user ""
I am a fairly new to web developement. First I deployed a static website on my vps (Ubuntu 16.04) without problem and then I tried to add a blog app to it. It works well locally with PostgreSQL but I can't make it work on my server. It seems like it tries to connect to Postgres with my Unix user. Why would my server t...
[ "As per the error, it is clear that the failure is when your Application is trying to postgres and the important part to concentrate is Authentication. \nDo these steps to first understand and reproduce the issue. \nI assume it as a Linux Server and recommend these steps. \nStep 1:\n$ python3\n>>>import psycopg2\n>...
[ 11, 9, 3, 1, 0, 0, 0 ]
[ "Try something like this:\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n" ]
[ -1 ]
[ "django", "postgresql", "python", "ubuntu_16.04" ]
stackoverflow_0048999379_django_postgresql_python_ubuntu_16.04.txt
Q: How can I filter data from a dataframe to show data between several datetimes from a different dataframe? I want to filter df1 to only show data that is between the DatetimeStart and DatetimeEnd datetimes in df2. df1 Estimate datetimeUTC 0 24.870665 2022-05-15 06:05:00+00:00 1 28.534566 2022-05-15 0...
How can I filter data from a dataframe to show data between several datetimes from a different dataframe?
I want to filter df1 to only show data that is between the DatetimeStart and DatetimeEnd datetimes in df2. df1 Estimate datetimeUTC 0 24.870665 2022-05-15 06:05:00+00:00 1 28.534566 2022-05-15 06:10:00+00:00 2 24.412932 2022-05-15 06:15:00+00:00 3 39.325210 2022-05-15 06:20:00+00:00 4 146.33400...
[ "Create new dataframe\nnewdf=pd.DataFrame(data=None, columns=df1.columns)\n\nThen concatenate\nfor i in range(len(df2)):\n newdf=pd.concat([newdf,(df1[df1['datetimeUTC'].between(df2['DatetimeStart'][i],df2['DatetimeEnd'][i])])],ignore_index=True)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074466353_python.txt
Q: Django orm get latest for each group I am using Django 1.6 with Mysql. I have these models: class Student(models.Model): username = models.CharField(max_length=200, unique = True) class Score(models.Model): student = models.ForeignKey(Student) date = models.DateTimeField() score = models.Integ...
Django orm get latest for each group
I am using Django 1.6 with Mysql. I have these models: class Student(models.Model): username = models.CharField(max_length=200, unique = True) class Score(models.Model): student = models.ForeignKey(Student) date = models.DateTimeField() score = models.IntegerField() I want to get the latest score ...
[ "If your DB is postgres which supports distinct() on field you can try\nScore.objects.order_by('student__username', '-date').distinct('student__username')\n\n", "This should work on Django 1.2+ and MySQL:\nScore.objects.annotate(\n max_date=Max('student__score__date')\n).filter(\n date=F('max_date')\n)\n\n", ...
[ 82, 43, 7, 0 ]
[ "Here's an example using Greatest with a secondary annotate. I was facing and issue where annotate was returning duplicate records ( Examples ), but the last_message_time Greatest annotation was causing duplicates.\nqs = (\n Example.objects.filter(\n Q(xyz=xyz)\n )\n ...
[ -1 ]
[ "django", "django_orm", "django_queryset", "python" ]
stackoverflow_0019923877_django_django_orm_django_queryset_python.txt
Q: Read txt file including scientific numbers having D instead of E in python I have a txt file inculding 10 columns and and want to read it as a dataframe. The problem is that the numbers are outputs of Fortran and having a weird notation like 9.677975573367686D+00 and cannot be converted to float. Thank you in adva...
Read txt file including scientific numbers having D instead of E in python
I have a txt file inculding 10 columns and and want to read it as a dataframe. The problem is that the numbers are outputs of Fortran and having a weird notation like 9.677975573367686D+00 and cannot be converted to float. Thank you in advance. The following codes did not worked. data = np.loadtxt('data.txt', converter...
[ "If your code returned an error message it's best to post the whole message which can help others identify what was wrong.\nMy example tsv, the blanks are tabs, '\\t'.\n123.456D78 23.455D+00 456.789\n987.65D3 45D-4 78.9D-03\n9.677975573367686D+00 609.54d+4 123.456\n\nThis code worked to read the above ts...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python", "python_3.x" ]
stackoverflow_0074454899_numpy_pandas_python_python_3.x.txt
Q: Failed to create a virtual environment on MacOS with M1 with PyCharm I just bought a new MacBook Pro with M1 Pro I installed python 3.11 and Pycharm as IDE. I tried to create a new project using virtualenv but it continues to show an error (see below)... I tried using Python 3.10, I tried installing it from Homebr...
Failed to create a virtual environment on MacOS with M1 with PyCharm
I just bought a new MacBook Pro with M1 Pro I installed python 3.11 and Pycharm as IDE. I tried to create a new project using virtualenv but it continues to show an error (see below)... I tried using Python 3.10, I tried installing it from Homebrew, reinstalling it.. nothing changes... Steps to Reproduce Start a new p...
[ "You are trying to create the virtualenv at /Users/test, to which (by default, and unless running as root) you don't have permissions. Try setting the Location field to your own home (somewhere under /Users/antonellobarbone/).\n", "Have you tried creating it via command line? If that works, the problem is Pycharm...
[ 3, 0 ]
[]
[]
[ "apple_m1", "macos", "pycharm", "python", "virtualenv" ]
stackoverflow_0074466791_apple_m1_macos_pycharm_python_virtualenv.txt
Q: How to make this program to displayed the result correctly I'm just learning Python and I don't know how to make this program to display result in label that I want and when I click button again I want to the new result replaces the previous one I want to last class shows result in label or entry when i click 1st ...
How to make this program to displayed the result correctly
I'm just learning Python and I don't know how to make this program to display result in label that I want and when I click button again I want to the new result replaces the previous one I want to last class shows result in label or entry when i click 1st button and when i click it again the new result will replace pre...
[ "If you want to update an existing Label widget, declare a tk.StringVar() to store the label text, then bind that to your Label's textvariable attribute. Then your Label will automatically update whenever you set() the StringVar.\nlabel_var = tk.StringVar(self, 'Default Value') # both of these args are optional\nl...
[ 0 ]
[]
[]
[ "label", "python", "tkinter" ]
stackoverflow_0074466647_label_python_tkinter.txt
Q: How to scrape reviews from chrome web store for a given extension? I am trying to use this python code to scrape chrome web store from lxml import html import requests url = 'https://chrome.google.com/webstore/detail/cookie-editor/hlkenndednhfkekhgcdicdfddnkalmdm' values = {'username': 'myemail@gmail.com', ...
How to scrape reviews from chrome web store for a given extension?
I am trying to use this python code to scrape chrome web store from lxml import html import requests url = 'https://chrome.google.com/webstore/detail/cookie-editor/hlkenndednhfkekhgcdicdfddnkalmdm' values = {'username': 'myemail@gmail.com', 'password': 'mypassword'} page = requests.get(url, data=values) print...
[ "The webpage's contents are loaded by JavaScript. So you have to apply an automation tool something like Selenium to grab the right data.\nExample:\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by im...
[ 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074466480_python_web_scraping.txt
Q: How to use dict.get() with multidimensional dict? I have a multidimensional dict, and I'd like to be able to retrieve a value by a key:key pair, and return 'NA' if the first key doesn't exist. All of the sub-dicts have the same keys. d = { 'a': {'j':1,'k':2}, 'b': {'j':2,'k':3}, 'd': {'j':1,'k':3...
How to use dict.get() with multidimensional dict?
I have a multidimensional dict, and I'd like to be able to retrieve a value by a key:key pair, and return 'NA' if the first key doesn't exist. All of the sub-dicts have the same keys. d = { 'a': {'j':1,'k':2}, 'b': {'j':2,'k':3}, 'd': {'j':1,'k':3} } I know I can use d.get('c','NA') to get the su...
[ "How about\nd.get('a', {'j': 'NA'})['j']\n\n?\nIf not all subdicts have a j key, then\nd.get('a', {}).get('j', 'NA')\n\n \nTo cut down on identical objects created, you can devise something like\nclass DefaultNASubdict(dict):\n class NADict(object):\n def __getitem__(self, k):\n return 'NA'\n\n...
[ 37, 5, 5, 3, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0016003408_dictionary_python.txt
Q: Pandas Multiply 2D by 1D Dataframe Looking for an elegant way to multiply a 2D dataframe by a 1D series where the indices and column names align df1 = Index A B 1 1 5 2 2 6 3 3 7 4 4 8 df2 = Coef A 10 B 100 Something like... df3 = df1.mul(df2) To get : Index A B 1 10 500 2 20 600 3 30 700 4 40 800...
Pandas Multiply 2D by 1D Dataframe
Looking for an elegant way to multiply a 2D dataframe by a 1D series where the indices and column names align df1 = Index A B 1 1 5 2 2 6 3 3 7 4 4 8 df2 = Coef A 10 B 100 Something like... df3 = df1.mul(df2) To get : Index A B 1 10 500 2 20 600 3 30 700 4 40 800
[ "There is no such thing as 1D DataFrame, you need to slice as Series to have 1D, then multiply (by default on axis=1):\ndf3 = df1.mul(df2['Coef'])\n\nOutput:\n A B\n1 10 500\n2 20 600\n3 30 700\n4 40 800\n\nIf Index is a column:\ndf3 = df1.mul(df2['Coef']).combine_first(df1)[df1.columns]\n\nOutput:\n ...
[ 5 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074466909_dataframe_pandas_python.txt
Q: SUMIF equivalent with unique date ranges in Python (Summing if date falls within various date ranges for variable creation) I am looking to create variables that sum based on date ranges unique to different features / categories to automate a current Excel task in Python. It is like a SUMIF in Excel but unique da...
SUMIF equivalent with unique date ranges in Python (Summing if date falls within various date ranges for variable creation)
I am looking to create variables that sum based on date ranges unique to different features / categories to automate a current Excel task in Python. It is like a SUMIF in Excel but unique date ranges for different variables. I`ll try to recreate a similar situation as I cannot share the exact data. At the moment, I ...
[ "# DF: sales (top DF in question)\n# DF2: sales period (second DF in question)\n\n# format the date into datetime\ndf['Week'] = pd.to_datetime(df['Week'], dayfirst=True)\ndf2[['Sale Start Week','Sale End Week']]=df2[['Sale Start Week','Sale End Week']].apply(pd.to_datetime, dayfirst=True)\ndf2\n\n# merge using merg...
[ 0, 0, 0 ]
[]
[]
[ "data_manipulation", "pandas", "python", "sumifs" ]
stackoverflow_0074275891_data_manipulation_pandas_python_sumifs.txt
Q: How to improve the efficiency of this python function? I pass a list (called a) of characters. The characters could be either letters or emojis. Ex: a=['a','b','f','a','g', ''] Then I count the occurrences of each character in the list. This function return just the most frequent character by alphabetical order. e...
How to improve the efficiency of this python function?
I pass a list (called a) of characters. The characters could be either letters or emojis. Ex: a=['a','b','f','a','g', ''] Then I count the occurrences of each character in the list. This function return just the most frequent character by alphabetical order. ex_n.2: if the most frequents characters are 'b' and 'a', it ...
[ "As @TimRoberts commented, one can use collections.Counter. This object will count the number of times each item occurs. Then we can find the most common objects, and in the case of ties, we sort the values.\nIn the example below, b and d both occur three times. But using counter.most_common(n=1) would give us d be...
[ 1, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0074466852_performance_python.txt
Q: I can't get all the html data from beautiful soup Im new in webscraping and i wanted to get just a text from a google page (basically the date of a soccer match), but the soup doesnt get all the html (im gessing beacause of request) so i can't find it, I know it can be beacause of google using javascript and I sho...
I can't get all the html data from beautiful soup
Im new in webscraping and i wanted to get just a text from a google page (basically the date of a soccer match), but the soup doesnt get all the html (im gessing beacause of request) so i can't find it, I know it can be beacause of google using javascript and I should use selenium chromedriver, but the thing is that I ...
[ "Try to set User-Agent header when requesting the page from Google:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\na = \"Newcastle\"\nurl = \"https://www.google.com/search?q=\" + a + \"+next+match&hl=en\"\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:106.0) Gecko/20100101 Fi...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "python_requests", "web_scraping" ]
stackoverflow_0074466121_beautifulsoup_html_python_python_requests_web_scraping.txt
Q: How can I sum user input numbers whilst in a loop? I'm trying to get the sum of numbers that a user inputs in a loop, but I can't get it to include the first number input - here's what I have so far number = int(input("Enter a number")) total = 0 while number != -1: number = int(input("Enter another number")) to...
How can I sum user input numbers whilst in a loop?
I'm trying to get the sum of numbers that a user inputs in a loop, but I can't get it to include the first number input - here's what I have so far number = int(input("Enter a number")) total = 0 while number != -1: number = int(input("Enter another number")) total += number else: print(total) Probably something e...
[ "number = int(input(\"Enter a number\"))\ntotal = 0\nwhile number != -1:\n total += number\n number = int(input(\"Enter another number\"))\nelse:\n print(total)\n\nJust move the summation one line above.\n" ]
[ 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074467095_loops_python.txt
Q: String input inserted as individual characters Trying to insert users into database using Python through input, whenever I type a name like "kai" it takes each individual letter like "k", "a", "i" instead: cr = db.cursor() cr.execute("CREATE TABLE if not exists users (user_id int,name text)") cr.execute("CREATE T...
String input inserted as individual characters
Trying to insert users into database using Python through input, whenever I type a name like "kai" it takes each individual letter like "k", "a", "i" instead: cr = db.cursor() cr.execute("CREATE TABLE if not exists users (user_id int,name text)") cr.execute("CREATE TABLE if not exists skills (name text,progress int, u...
[ "A string is an interable. Read the doc on enumerate. When it iterates a string it processes one character at a time, thus the result you see.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "sql", "sqlite" ]
stackoverflow_0074463890_python_python_3.x_sql_sqlite.txt
Q: How to assign identical random IDs conditionally to "related" rows in pandas? New to Python I'm struggling with the problem to assign some random IDs to "related" rows where the relation is simply their proximity (within 14 days) in consecutive days grouped by user. In that example I chose uuidwithout any specific...
How to assign identical random IDs conditionally to "related" rows in pandas?
New to Python I'm struggling with the problem to assign some random IDs to "related" rows where the relation is simply their proximity (within 14 days) in consecutive days grouped by user. In that example I chose uuidwithout any specific intention. It could be any other random IDs uniquely indentifying conceptually rel...
[ "Taking the idea from Luise, we start with an empty column for related_transaction. Then, we iterate through each row. For each date, we check if it is already part of a transaction. If so, continue. Otherwise, assign a new transaction to that date and all other dates within 15 following days for the same user:\nim...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074466504_pandas_python.txt
Q: Print a specific word when a number is div. by 5 , and another specific word when its div.by 10 On a range 1 to 100, I want to a specific word when the number is divisible by 5 for example "Good" , and another specific word when its divisible by 10 for example "morning" 1,2,3,4,good,6,7,8,9,morning .... etc i mad...
Print a specific word when a number is div. by 5 , and another specific word when its div.by 10
On a range 1 to 100, I want to a specific word when the number is divisible by 5 for example "Good" , and another specific word when its divisible by 10 for example "morning" 1,2,3,4,good,6,7,8,9,morning .... etc i made this code but its only working when its div. by 5 for z in range (0, 101 , 1): if z%5==0: ...
[ "Reverse the conditions for divisible by 10 or 5. If it is divisible by 10, you get \"morning\", then checks for 5, otherwise prints that value.\nAs currently written, all 10 digits will match the 5 condition, and not print further because you're using elif. If you used if twice, it would print both \"good\" and \"...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074467092_python.txt
Q: How do I write the lark grammar for First Order Logic with Equality? According to AIMA (Russell & Norvig, 2010) this is the BNF grammar for FOL with Equality: How do I convert this to a lark grammar? Specifically, how do I represent n-ary predicates using lark grammar? A: I'm going to take this question as aski...
How do I write the lark grammar for First Order Logic with Equality?
According to AIMA (Russell & Norvig, 2010) this is the BNF grammar for FOL with Equality: How do I convert this to a lark grammar? Specifically, how do I represent n-ary predicates using lark grammar?
[ "I'm going to take this question as asking how to specify the syntax of an application of an identifier to a parenthesised, comma-separated list of terms.\nIn syntactic terms, that's similar enough to JSON list syntax to make it worthwhile looking at the first sample grammar (for JSON) in the Lark documentation sit...
[ 1, 0 ]
[]
[]
[ "bnf", "first_order_logic", "lark_parser", "parsing", "python" ]
stackoverflow_0074420733_bnf_first_order_logic_lark_parser_parsing_python.txt
Q: Position frequency matrix for Pandas column with strings I have a pandas Dataframe with a column of peptide sequences and I want to know how many times each each amino acid appears at each position. I have written the following code to create the position frequency matrix: import pandas as pd from itertools import...
Position frequency matrix for Pandas column with strings
I have a pandas Dataframe with a column of peptide sequences and I want to know how many times each each amino acid appears at each position. I have written the following code to create the position frequency matrix: import pandas as pd from itertools import chain def frequency_matrix(df): # Empty position frequen...
[ "Solution\nmini_df['peptide_len'] = mini_df.peptide_len.map(lambda x: range(x))\nmini_df['peptide_alpha'] = mini_df.peptide_alpha.map(list)\nmini_df = mini_df.explode([\"peptide_alpha\", \"peptide_len\"])\n\npd.crosstab(mini_df.peptide_len, mini_df.peptide_alpha)\n\nPerformance\nWith the dataframe\nmini_df = pd.con...
[ 2 ]
[]
[]
[ "frequency", "pandas", "position", "python", "python_3.x" ]
stackoverflow_0074466989_frequency_pandas_position_python_python_3.x.txt
Q: How to edit a message in discord.py I would like to have my bot edit a message if it detects a keyword, i'm not sure how to edit the message though. I've looked through the documentation but can't seem to figure it out. I'm using discord.py with python 3.6. This is the code: @bot.event async def on_message(message...
How to edit a message in discord.py
I would like to have my bot edit a message if it detects a keyword, i'm not sure how to edit the message though. I've looked through the documentation but can't seem to figure it out. I'm using discord.py with python 3.6. This is the code: @bot.event async def on_message(message): if 'test' in message.content: ...
[ "You can use the Message.edit coroutine. The arguments must be passed as keyword arguments content, embed, or delete_after. You may only edit messages that you have sent.\nawait message.edit(content=\"newcontent\")\n\n", "Here's a solution that worked for me.\n@client.command()\nasync def test(ctx):\n message ...
[ 23, 10, 0, 0, 0 ]
[ "Please try to add def to your code like this:\n@bot.event\nasync def on_message(message):\n if 'test' in message.content:\n await edit(message, \"edited !\")\n\n", "This is what I did:\n@bot.event\nasync def on_message(message):\n if message.content == 'test':\n await message.channel.send('Hello Wo...
[ -1, -1 ]
[ "discord.py", "python" ]
stackoverflow_0055711572_discord.py_python.txt
Q: Having trouble with def functions I have been taking this class for a bit with python for a bit and I have stumbled into a problem where any time I try to "def" a function, it says that it is not defined, I have no idea what I am doing wrong and this has become so frustrating. # Define main def main(): MIN = -...
Having trouble with def functions
I have been taking this class for a bit with python for a bit and I have stumbled into a problem where any time I try to "def" a function, it says that it is not defined, I have no idea what I am doing wrong and this has become so frustrating. # Define main def main(): MIN = -100 MAX = 100 LIST_SIZE = 10 #C...
[ "Your MIN, MAX, and LIST_SIZE variables are all being defined locally within def main():\nBy the looks of it, you want the code below those lines to be part of main, so fix the indentation to properly declare it as part of main.\ndef main():\n MIN = -100\n MAX = 100\n LIST_SIZE = 10\n\n #Create empty li...
[ 2, 1 ]
[]
[]
[ "function", "nameerror", "python" ]
stackoverflow_0074467137_function_nameerror_python.txt
Q: QQ Plot for Poisson Distribution in Python I've been trying to make a QQ plot in python for a poisson distribution. Here is what I have so far: import numpy as np import statsmodels.api as sm import scipy.stats as stats pois = np.random.poisson(2.5, 100) #creates random Poisson distribution with mean = 2.5 fig =s...
QQ Plot for Poisson Distribution in Python
I've been trying to make a QQ plot in python for a poisson distribution. Here is what I have so far: import numpy as np import statsmodels.api as sm import scipy.stats as stats pois = np.random.poisson(2.5, 100) #creates random Poisson distribution with mean = 2.5 fig =sm.qqplot(pois, stats.poisson, line = 's') plt.sh...
[ "I had the same error. The following seemed to work for me:\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as stats\ndata=np.random.poisson(2.5, 100)\nstats.probplot(data, dist='poisson', sparams=(2.5,), plot=plt)\nplt.show()\n\n", "It is the end of 2022, and this is still a thing. I not...
[ 5, 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0032983664_numpy_python_scipy.txt
Q: Logic behind Pylint error E1128 (assignment-from-none) Consider the following use case (minimum example): def get_func(param): if param is None: def func(): return None else: def func(): return param return func def process_val(param): func = get_func(par...
Logic behind Pylint error E1128 (assignment-from-none)
Consider the following use case (minimum example): def get_func(param): if param is None: def func(): return None else: def func(): return param return func def process_val(param): func = get_func(param) val = func() # Do stuff with 'val'; *None* is ...
[ "If the function does not always return None, then it's a false positive from pylint not understanding your code well. If the function always return None you have no reason to assign it in a variable, and it means the code is at best is doing a useless assignment, not doing what you think it does, or at worst compl...
[ 1 ]
[]
[]
[ "pylint", "python" ]
stackoverflow_0074467217_pylint_python.txt
Q: How to calculate the number of charging sessions in my data? I have a data set that looks like this: Timestamp Cumulative Energy (kWh) Charging? 2022-08-19 05:45:00 24.9 1 2022-08-19 06:00:00 44.7 1 2022-08-19 06:15:00 53.1 1 2022-08-19 06:30:00 0 0 And so on. The data set represents the usage of an EV charg...
How to calculate the number of charging sessions in my data?
I have a data set that looks like this: Timestamp Cumulative Energy (kWh) Charging? 2022-08-19 05:45:00 24.9 1 2022-08-19 06:00:00 44.7 1 2022-08-19 06:15:00 53.1 1 2022-08-19 06:30:00 0 0 And so on. The data set represents the usage of an EV charger for a couple weeks. I want to be able to calculate ...
[ "I copied the first three rows at the bottom to check the solution. hene two rows in the result\nPlease note I'm still not clear on how you like the dictionary to look like, i.e, what will be the key, I understand the value\n# identify the consecutive charging session\n# take diff of two consecutive rows, first row...
[ 0, 0 ]
[]
[]
[ "data_analysis", "dataframe", "python" ]
stackoverflow_0074465768_data_analysis_dataframe_python.txt
Q: finding sum of fractions n/1 to 1/n I am trying to find the sum n/1 + (n-1)/2 + (n-2)/3 ... + 1/n. I am not getting the correct output This is what I have n = int(input("Please enter a positive integer: ")) sum2 = 0.0 for i in range(1, n-1): sum2 = sum2 + (i/1) print("For n =", n, "the sum n/1 + (n-1)/2 + ....
finding sum of fractions n/1 to 1/n
I am trying to find the sum n/1 + (n-1)/2 + (n-2)/3 ... + 1/n. I am not getting the correct output This is what I have n = int(input("Please enter a positive integer: ")) sum2 = 0.0 for i in range(1, n-1): sum2 = sum2 + (i/1) print("For n =", n, "the sum n/1 + (n-1)/2 + ... 1/n is", sum2) My expected output for...
[ "When talking about the 2nd summation, besides the numerator decreasing one by one, the denominator also needs to increase one by one.\nn = int(input(\"Please enter a positive integer: \"))\n\n\nsum2 = 0\n\nfor i in range(0, n):\n sum2 = sum2 + (n-i)/(i+1)\n\nprint(\"For n =\", n, \"the sum n/1 + (n-1)/2 + ... 1...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074467227_python.txt
Q: How to annotate each lmplot facet by hue group or combined data I'm trying to add annotations to lmplots in a FacetGrid (r and p values for each regression) but the plots have two regression lines because I'm using "hue", and therefore I get two annotations that are stacked on top of each other. I'd like to either...
How to annotate each lmplot facet by hue group or combined data
I'm trying to add annotations to lmplots in a FacetGrid (r and p values for each regression) but the plots have two regression lines because I'm using "hue", and therefore I get two annotations that are stacked on top of each other. I'd like to either specify that they are displayed in different locations or ideally to...
[ "\nThe tips dataset is being used because the sample data in the OP causes scipy to generate ConstantInputWarning: An input array is constant; the correlation coefficient is not defined.\nUse a dict to define the y-position for each hue category\nideally to use the complete dataset\n\nWhen using .map_dataframe, for...
[ 1 ]
[]
[]
[ "facet_grid", "lmplot", "plot_annotations", "python", "seaborn" ]
stackoverflow_0074465966_facet_grid_lmplot_plot_annotations_python_seaborn.txt
Q: How to parse SOAP XML with Python? Goal: Get the values inside <Name> tags and print them out. Simplified XML below. <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-...
How to parse SOAP XML with Python?
Goal: Get the values inside <Name> tags and print them out. Simplified XML below. <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <GetStar...
[ "The issue here is dealing with the XML namespaces:\nimport requests\nfrom xml.etree import ElementTree\n\nresponse = requests.get('http://www.labs.skanetrafiken.se/v2.2/querystation.asp?inpPointfr=yst')\n\n# define namespace mappings to use as shorthand below\nnamespaces = {\n 'soap': 'http://schemas.xmlsoap.or...
[ 26, 9, 2, 0, 0 ]
[]
[]
[ "python", "python_3.x", "soap", "xml", "zeep" ]
stackoverflow_0045250626_python_python_3.x_soap_xml_zeep.txt
Q: Index pandas DataFrame by column numbers, when column names are integers I am trying to keep just certain columns of a DataFrame, and it works fine when column names are strings: In [2]: import numpy as np In [3]: import pandas as pd In [4]: a = np.arange(35).reshape(5,7) In [5]: df = pd.DataFrame(a, ['x', 'y',...
Index pandas DataFrame by column numbers, when column names are integers
I am trying to keep just certain columns of a DataFrame, and it works fine when column names are strings: In [2]: import numpy as np In [3]: import pandas as pd In [4]: a = np.arange(35).reshape(5,7) In [5]: df = pd.DataFrame(a, ['x', 'y', 'u', 'z', 'w'], ['a', 'b', 'c', 'd', 'e', 'f', 'g']) In [6]: df Out[6]: ...
[ "This is exactly the purpose of iloc, see here\nIn [37]: df\nOut[37]: \n 10 11 12 13 14 15 16\nx 0 1 2 3 4 5 6\ny 7 8 9 10 11 12 13\nu 14 15 16 17 18 19 20\nz 21 22 23 24 25 26 27\nw 28 29 30 31 32 33 34\n\nIn [38]: df.iloc[:,[1,3]]\nOut[38]: \n 11 13\nx 1 ...
[ 20, 10, 3, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0027156278_pandas_python.txt
Q: How to slice list based on a condition that every element of another list must appear atleast once? I have two lists : a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2, 1, 3, 5, 7, 0] key = [1, 2, 4, 6] I want to check if all elements in the key have atleast once appeared in the list a and remove the ones after that. desired...
How to slice list based on a condition that every element of another list must appear atleast once?
I have two lists : a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2, 1, 3, 5, 7, 0] key = [1, 2, 4, 6] I want to check if all elements in the key have atleast once appeared in the list a and remove the ones after that. desired output : a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2] here is what i tried: if a[-1] not in key: indx ...
[ "This function slices the list based on the condition that every element of the key must appear at least once in a.\ndef slice_list(a, key):\n for i in range(len(a)): # iterate over the list\n if a[i] in key: # check if the element is in the key\n key.remove(a[i]) # remove the element from t...
[ 0, 0, 0, 0 ]
[]
[]
[ "for_loop", "list", "python", "python_3.x", "slice" ]
stackoverflow_0074467118_for_loop_list_python_python_3.x_slice.txt
Q: How can I stop AWS lambda from recursive invocations I have a lambda function that will read an excel file and do some stuffs and then store the result in a different S3 bucket. def lambda_handler(event, context): try: status = int(event['status']) if status: Reading_Bucket_Name =...
How can I stop AWS lambda from recursive invocations
I have a lambda function that will read an excel file and do some stuffs and then store the result in a different S3 bucket. def lambda_handler(event, context): try: status = int(event['status']) if status: Reading_Bucket_Name = 'read-data-s3' Writing_Bucket_Name = 'write-e...
[ "Given that the Lambda function appears to be running when a new object is created in the Amazon S3 bucket, it would appear that the bucket has been configured with an Event Notification that is triggering the AWS Lambda function.\nTo check this, go the to bucket in the S3 management console, go to the Properties t...
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "python" ]
stackoverflow_0074458771_amazon_s3_amazon_web_services_aws_lambda_python.txt
Q: How to make an inset plot with mollweide projection? I want to make a skymap using the Mollweide projection for a main set of axes and for an inset axes. This is easy for the main axes but not for the inset. I've tried a few different things but it doesn't work for the inset. Please help! Here you can find the lat...
How to make an inset plot with mollweide projection?
I want to make a skymap using the Mollweide projection for a main set of axes and for an inset axes. This is easy for the main axes but not for the inset. I've tried a few different things but it doesn't work for the inset. Please help! Here you can find the latitude and longitude data, and here you can find the sky lo...
[ "To have the axis in the correct way, you can rotate the subplot by using rotate.\nConcerning the fact that your contour are not shown, it is probably because you have to add the transform keyword. If you don't specify it, it is plotted in pixel coordinates by default (https://docs.astropy.org/en/stable/visualizati...
[ 1, 0 ]
[]
[]
[ "insets", "map_projections", "matplotlib", "python", "python_3.x" ]
stackoverflow_0073415539_insets_map_projections_matplotlib_python_python_3.x.txt
Q: Aggregate daily data by month and an additional column I've got a DataFrame storing daily-based data which is as below: Date Product Number Description Revenue 2010-01-04 4219-057 Product A 39.299999 2010-01-04 4219-056 Product A 39.520000 2010-01-04 ...
Aggregate daily data by month and an additional column
I've got a DataFrame storing daily-based data which is as below: Date Product Number Description Revenue 2010-01-04 4219-057 Product A 39.299999 2010-01-04 4219-056 Product A 39.520000 2010-01-04 4219-100 Product B 39.520000 2010-01-04 ...
[ "Convert \"Date\" to datetime, then use groupby and sum:\n# Do this first, if necessary.\ndf['Date'] = pd.to_datetime(df['Date'], errors='coerce')\n\n(df.groupby([pd.Grouper(key='Date', freq='MS'), 'Description'])['Revenue']\n .sum()\n .reset_index())\n\n Date Description Revenue\n0 2010-01-01 ...
[ 0 ]
[ "This is a bit of a workaround but if you simply create a 'Month_Year' variable in a new column using -\ndf['Month_Year'] = df['Date'].dt.to_period('M')\n\nYou can then groupby that column and aggregate as needed, like so -\ndf_agg = df.groupby([\"Month_Year\", \"Description\"])['Revenue'].sum().reset_index()\n\n" ...
[ -1 ]
[ "group_by", "pandas", "pandas_groupby", "python" ]
stackoverflow_0056285925_group_by_pandas_pandas_groupby_python.txt
Q: I can't read date without time from CSV using pandas I have this dataframe: forecasts Out[15]: timestamp 1 2 0 2022-11-08 12:12:15 5679.658691 5400.217773 1 2022-11-08 12:38:49 5679.658691 5400.217773 2 2022-11-09 11:05:53 5863.616699 561...
I can't read date without time from CSV using pandas
I have this dataframe: forecasts Out[15]: timestamp 1 2 0 2022-11-08 12:12:15 5679.658691 5400.217773 1 2022-11-08 12:38:49 5679.658691 5400.217773 2 2022-11-09 11:05:53 5863.616699 5619.101562 3 2022-11-10 10:46:27 6047.025391 571...
[ "you can use:\nforecasts = forecasts[forecasts['timestamp'].dt.strftime('%Y-%m-%d') == '2022-11-11']\n#or\nforecasts = forecasts[forecasts['timestamp'].dt.strftime('%Y-%m-%d') == (str(2022) + '-' + str(11) + '-' + str(11))]\n\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074467355_pandas_python.txt
Q: How to click all the fetched links from a search result in selenium using python? In selenium, I am grabbing some search result URL by XPATH. Now I want to click then one by one which will open then in the same browser one by one where the base URL is opened so that I can switch between then. How can I do that? I ...
How to click all the fetched links from a search result in selenium using python?
In selenium, I am grabbing some search result URL by XPATH. Now I want to click then one by one which will open then in the same browser one by one where the base URL is opened so that I can switch between then. How can I do that? I am giving my code below. import time from selenium import webdriver from selenium.webdr...
[ "You can do that as following:\nGet the list of the links.\nIn a loop click on grabbed links.\nWhen link is opened in a new tab switch the driver to the new opened tab.\nDo there what you want to do (I simulated this by a simple delay of 1 second).\nClose the new tab.\nSwitch back to the first tab.\nCollect the lis...
[ 0 ]
[]
[]
[ "for_loop", "python", "selenium", "selenium_webdriver", "staleelementreferenceexception" ]
stackoverflow_0074466251_for_loop_python_selenium_selenium_webdriver_staleelementreferenceexception.txt
Q: No module named tensorflow in jupyter I have some imports in my jupyter notebook and among them is tensorflow: ImportError Traceback (most recent call last) <ipython-input-2-482704985f85> in <module>() 4 import numpy as np 5 import six.moves.copyreg as copyreg ----> 6 impo...
No module named tensorflow in jupyter
I have some imports in my jupyter notebook and among them is tensorflow: ImportError Traceback (most recent call last) <ipython-input-2-482704985f85> in <module>() 4 import numpy as np 5 import six.moves.copyreg as copyreg ----> 6 import tensorflow as tf 7 from six.moves ...
[ "If you installed a TensorFlow as it said in official documentation: https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#overview\nI mean creating an environment called tensorflow and tested your installation in python, but TensorFlow can not be imported in jupyter, you have to install jupyter in yo...
[ 75, 23, 20, 5, 4, 3, 3, 3, 1, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "jupyter_notebook", "python", "tensorflow" ]
stackoverflow_0038221181_jupyter_notebook_python_tensorflow.txt
Q: Python Pydantic Get JSON Regardless of Validation I have a class in Pydantic that fails validation. I would like to fetch the JSON regardless of failure. Any ideas? from pydantic import BaseModel, Field, ValidationError class Model(BaseModel): a: float = Field(ge=1.0) try: m = Model(a=0.5) print(m.js...
Python Pydantic Get JSON Regardless of Validation
I have a class in Pydantic that fails validation. I would like to fetch the JSON regardless of failure. Any ideas? from pydantic import BaseModel, Field, ValidationError class Model(BaseModel): a: float = Field(ge=1.0) try: m = Model(a=0.5) print(m.json()) except ValidationError as e: data = e.data() ...
[ "You can create a dict manually and then pass it further\nfrom pydantic import BaseModel, Field, ValidationError\n\nclass Model(BaseModel):\n a: float = Field(ge=1.0)\n\ntry:\n d = {'a': 0.5}\n m = Model.parse_obj(d)\n print(m.json())\nexcept ValidationError as e:\n d['errors'] = e.json()\n print(...
[ 0 ]
[]
[]
[ "pydantic", "python" ]
stackoverflow_0074467194_pydantic_python.txt
Q: How to Fix "AssertionError: CUDA unavailable, invalid device 0 requested" I'm trying to use my GPU to run the YOLOR model, and I keep getting the error: Traceback (most recent call last): File "D:\yolor\detect.py", line 198, in <module> detect() File "D:\yolor\detect.py", line 41, in detect device = se...
How to Fix "AssertionError: CUDA unavailable, invalid device 0 requested"
I'm trying to use my GPU to run the YOLOR model, and I keep getting the error: Traceback (most recent call last): File "D:\yolor\detect.py", line 198, in <module> detect() File "D:\yolor\detect.py", line 41, in detect device = select_device(opt.device) File "D:\yolor\utils\torch_utils.py", line 47, in sel...
[ "You forgot to put the == signs between the packages and the version number. According to the PyTorch installation page:\npy -m pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio===0.9.0 -f https://download.pytorch.org/whl/torch_stable.html\n\n", "Ok after 1 week of pain I have founded this solut...
[ 2, 2, 0, 0 ]
[]
[]
[ "deep_learning", "python", "pytorch" ]
stackoverflow_0068562730_deep_learning_python_pytorch.txt
Q: use type error message in pytest parametrize I have a function which raises a TypeError when some conditions are met. def myfunc(..args here...): ... raise TypeError('Message') I want to test this message using pytest parametrize. But, because I am using other arguments also I want to have a setup like t...
use type error message in pytest parametrize
I have a function which raises a TypeError when some conditions are met. def myfunc(..args here...): ... raise TypeError('Message') I want to test this message using pytest parametrize. But, because I am using other arguments also I want to have a setup like this: testdata = [ (..args here..., 'Messag...
[ "You can't expect message error as a normal output of myfunc. There is a special context manager for this - pytest.raises.\nFor example, if you want to expect some error and its message\n\ndef test_raises():\n with pytest.raises(Exception) as excinfo: \n raise Exception('some info') \n assert str(e...
[ 2, 1 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0041936456_pytest_python.txt
Q: If there is no way to put a timeout in pandas read_csv, how to proceed? The CSV files linked to Google Sheets if by any chance there is a problem, it can't finish executing the task and stays in the same place for eternity, so I need to add a timeout in the attempt to import the CSV. I am currently test the situat...
If there is no way to put a timeout in pandas read_csv, how to proceed?
The CSV files linked to Google Sheets if by any chance there is a problem, it can't finish executing the task and stays in the same place for eternity, so I need to add a timeout in the attempt to import the CSV. I am currently test the situation with func-timeout: from func_timeout import func_timeout, FunctionTimedOu...
[ "There's a syntax error here: args=(csv_file) which leads to the FutureWarning down the line. You want a singlet (tuple with 1 value) like this: args=(csv_file, )\nThe comma makes the tuple!\n(Riddle: Why did it say you passed 168 arguments?)\n# it should work with a proper argument tuple.\ndf = func_timeout(30, pd...
[ 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0072750327_pandas_python.txt
Q: Python Django - delaying ValidationError until for loop completes I'm working on an app that simulates a social media site. I currently have a form where users can enter in their friends' emails so they can be invited to join the app. Let's say we have a user who enters in three email addresses to the email form w...
Python Django - delaying ValidationError until for loop completes
I'm working on an app that simulates a social media site. I currently have a form where users can enter in their friends' emails so they can be invited to join the app. Let's say we have a user who enters in three email addresses to the email form which are then saved as a list of strings: emails_to_invite = ["jen@webs...
[ "If you don't want an Exception in a code-block to halt your execution (and hide further exceptions, as you've found), put the susceptible code in a a try/except block to handle the error as you see fit.\nTo later raise the exception, consider using something like:\nraised_exceptions = []\n<loop that might raise ex...
[ 1 ]
[]
[]
[ "error_handling", "for_loop", "if_statement", "python", "validation" ]
stackoverflow_0074467510_error_handling_for_loop_if_statement_python_validation.txt
Q: 'DateField' object has no attribute 'value_from_datadict' I've been researching everywhere for an answer for this, but I'm just trying to add a widget to my DateField created on my models.py, where you can see the actual calendar, as if you were doing it directly through html with an input type=date. Since I have ...
'DateField' object has no attribute 'value_from_datadict'
I've been researching everywhere for an answer for this, but I'm just trying to add a widget to my DateField created on my models.py, where you can see the actual calendar, as if you were doing it directly through html with an input type=date. Since I have a few date fields, this has become a problem because they all n...
[ "You are using the wrong class for the widget. Change\n 'Fecha': forms.DateField(widget=NumberInput(attrs={'type':'date'})),\n\nto\n 'Fecha': forms.DateInput(widget=NumberInput(attrs={'type':'date'})),\n ^^^^^^^^^\n\nforms.DateField is intended for declaring the field...
[ 0 ]
[]
[]
[ "backend", "django", "python" ]
stackoverflow_0074463462_backend_django_python.txt
Q: How to continuously copy new S3 files to another S3 bucket How can I continuously copy one S3 bucket to another? I want to copy the files every time a new file has been added. I've tried using the boto3 copy_object however I require the key each time which won't work if I'm getting a new file each time. A: From ...
How to continuously copy new S3 files to another S3 bucket
How can I continuously copy one S3 bucket to another? I want to copy the files every time a new file has been added. I've tried using the boto3 copy_object however I require the key each time which won't work if I'm getting a new file each time.
[ "From Replicating objects - Amazon Simple Storage Service:\n\nTo automatically replicate new objects as they are written to the bucket use live replication, such as Same-Region Replication (SRR) or Cross-Region Replication (CRR).\n\nS3 Replication will automatically create new objects in another bucket as soon as t...
[ 1, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "python" ]
stackoverflow_0074463875_amazon_s3_amazon_web_services_aws_lambda_python.txt
Q: Extra line generated when writing serial data to file using pyserial I am reading a string from the serial port using pySerial and then writing data to a file with a time stamp. For some reason a new line is written with an empty data entry ( with the time stamp) every time I connect the serial port. I have set t...
Extra line generated when writing serial data to file using pyserial
I am reading a string from the serial port using pySerial and then writing data to a file with a time stamp. For some reason a new line is written with an empty data entry ( with the time stamp) every time I connect the serial port. I have set the write to file as append so that every time I read data from the port I ...
[ "I don't see the problem here, apparently data is either something like 'A' (no newline) or '' (no newline, just an empty string). In either case, .writerow() will write a full row, followed by a newline.\nIf you don't want newlines written to the output file:\nwith open(fileName, \"a\", newline='') as f:\n ...\...
[ 0 ]
[]
[]
[ "csvwriter", "pyserial", "python" ]
stackoverflow_0074467096_csvwriter_pyserial_python.txt
Q: Best Way to Count Occurences of Each Character in a Large Dataset I am trying to count the number of occurrences of each character within a large dateset. For example, if the data was the numpy array ['A', 'AB', 'ABC'] then I would want {'A': 3, 'B': 2, 'C': 1} as the output. I currently have an implementation tha...
Best Way to Count Occurences of Each Character in a Large Dataset
I am trying to count the number of occurrences of each character within a large dateset. For example, if the data was the numpy array ['A', 'AB', 'ABC'] then I would want {'A': 3, 'B': 2, 'C': 1} as the output. I currently have an implementation that looks like this: char_count = {} for c in string.printable: char_...
[ "Another way.\nimport collections\nc = collections.Counter()\nfor thing in data:\n c.update(thing)\n\nSame basic advantage - only iterates the data once.\n", "One approach:\nimport numpy as np\nfrom collections import defaultdict\n\ndata = np.array(['A', 'AB', 'ABC'])\n\ncounts = defaultdict(int)\nfor e in dat...
[ 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074467540_numpy_python.txt
Q: how to access object properties in json using beautifulsoup? python from bs4 import BeautifulSoup import fake_useragent import requests ua = fake_useragent.UserAgent() import soupsieve as sv url = "https://search-maps.yandex.ru/v1/?text=%D0%9F%D0%BE%D1%87%D1%82%D0%B0%20%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D0%B8,%20%D0%...
how to access object properties in json using beautifulsoup? python
from bs4 import BeautifulSoup import fake_useragent import requests ua = fake_useragent.UserAgent() import soupsieve as sv url = "https://search-maps.yandex.ru/v1/?text=%D0%9F%D0%BE%D1%87%D1%82%D0%B0%20%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D0%B8,%20%D0%9A%D1%80%D0%B0%D1%81%D0%BD%D0%BE%D0%B4%D0%B0%D1%80&results=500&type=biz&...
[ "The result from the server is in Json format, so use json parser or .json() method to decode it:\nimport json\nimport requests\n\n\nurl = \"https://search-maps.yandex.ru/v1/?text=%D0%9F%D0%BE%D1%87%D1%82%D0%B0%20%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D0%B8,%20%D0%9A%D1%80%D0%B0%D1%81%D0%BD%D0%BE%D0%B4%D0%B0%D1%80&results=...
[ 0, 0 ]
[]
[]
[ "arrays", "beautifulsoup", "json", "python", "python_requests" ]
stackoverflow_0074467316_arrays_beautifulsoup_json_python_python_requests.txt
Q: What am I doing wrong here (trying to print employee class) Traceback (most recent call last): File "C:/Users/cenni/OneDrive/Desktop/Computer science work and notes/Chapter 11 #1.py", line 20, in <module> main() File "C:/Users/cenni/OneDrive/Desktop/Computer science work and notes/Chapter 11 #1.py", line 1...
What am I doing wrong here (trying to print employee class)
Traceback (most recent call last): File "C:/Users/cenni/OneDrive/Desktop/Computer science work and notes/Chapter 11 #1.py", line 20, in <module> main() File "C:/Users/cenni/OneDrive/Desktop/Computer science work and notes/Chapter 11 #1.py", line 18, in main print('Your name is ' + self.name(), + ' your empl...
[ "self is a local variable in the class methods. Outside the methods, the variable that contains the employee is employee_info, so use that in the print() call.\n__init__() needs to call self.productionWorker() to set self.Snumber and self.pay.\nYou shouldn't have () after employee_info.name, in the print() call. Th...
[ 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074467632_class_python.txt
Q: Converting Multiple .xlsx Files to .csv - Pandas reading only 1 column `` Hello everyone, I am working on a deep learning project. The data I will use for the project consists of multiple excel files. Since I will be using the pd.read_csv command of the Pandas library, I used a VBA code that automatically converts...
Converting Multiple .xlsx Files to .csv - Pandas reading only 1 column
`` Hello everyone, I am working on a deep learning project. The data I will use for the project consists of multiple excel files. Since I will be using the pd.read_csv command of the Pandas library, I used a VBA code that automatically converts all excel files to csv format. Here is the VBA CODE: (xlsx to csv) Sub Work...
[ "Dealing with CSV is a tricky thing (not only in Excel). \"CSV\" stands for \"comma separated values\", and Excel takes this literally: When you use SaveAs FileFormat:=xlCSV, it will put a comma between your values. Except if you are using local setting on your computer that have a different separator defined, then...
[ 1, 1 ]
[]
[]
[ "excel", "file_conversion", "pandas", "python", "vba" ]
stackoverflow_0074431920_excel_file_conversion_pandas_python_vba.txt
Q: Python indexing question - 'IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed' Please can someone tell me why the following code does not work, and what the best work arounds for this are? Choices # variable containing True or False in each element. Choices.shape = (18978,) BestOpt...
Python indexing question - 'IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed'
Please can someone tell me why the following code does not work, and what the best work arounds for this are? Choices # variable containing True or False in each element. Choices.shape = (18978,) BestOption # variable containing 1 or 2 in each element. BestOption.shape = (18978, 1) Choices[BestOption==1] # I want to l...
[ "BestOption is a 1-D \"column vector\" that's actually made up of many rows and is treated like a 2-D matrix. You can simply reshape it back to a 1-D \"row vector\":\nChoices[BestOption.reshape(-1)==1]\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "indexing", "numpy", "python" ]
stackoverflow_0074467609_arrays_indexing_numpy_python.txt
Q: Using multiplication in a pulp constraint I'm trying to solve a problem similar to this simpler example. Target Constraint 12 25 15 50 14 10 8 2 etc I'm trying to maximize the sum of a selection of the target column while keeping the product of the constraint column < a certain number. So for example, if the...
Using multiplication in a pulp constraint
I'm trying to solve a problem similar to this simpler example. Target Constraint 12 25 15 50 14 10 8 2 etc I'm trying to maximize the sum of a selection of the target column while keeping the product of the constraint column < a certain number. So for example, if the constraint was 500, one possible s...
[ "As @AirSquid has pointed out multiplication of variables is not allowed in the objective or constraints of a linear program (this would make it non-linear).\nHowever, the problem you have described can be straight-forwardly and exactly linearised by taking logs. The log of a product of some numbers is equal to the...
[ 0 ]
[]
[]
[ "pulp", "python" ]
stackoverflow_0074304315_pulp_python.txt
Q: How to control number of cores of a method I have the following code: from sklearn_extra.clusters import KMedoids def _compute_medoids(df, k): k_medoids = KMedoids(n_clusters=k, metric='precomputed', init='k-medoids++').fit(df) medoid_index=k_medoids.medoid_indices_ labels=k_medoids.labels_ return...
How to control number of cores of a method
I have the following code: from sklearn_extra.clusters import KMedoids def _compute_medoids(df, k): k_medoids = KMedoids(n_clusters=k, metric='precomputed', init='k-medoids++').fit(df) medoid_index=k_medoids.medoid_indices_ labels=k_medoids.labels_ return medoid_index, labels for k in range(1, 6): ...
[ "The kmedoids package has faster algorithms, including a parallel version of FasterPAM.\nhttps://python-kmedoids.readthedocs.io/en/latest/#kmedoids.fasterpam\ndef _compute_medoids(df, k):\n import kmedoids\n km = kmedoids.fasterpam(df, k)\n return km.medoids, km.labels\n\n" ]
[ 0 ]
[]
[]
[ "joblib", "multiprocessing", "python" ]
stackoverflow_0073977052_joblib_multiprocessing_python.txt
Q: I have two excel list with different PDF's that need to be merged. Is there anyway to merge them using code rather than doing manually (takes hours)? I have two Excel list indicating the path of PDF files that I need to merge- Is there anyway to do this using code? As the manual process takes hours to process. I'v...
I have two excel list with different PDF's that need to be merged. Is there anyway to merge them using code rather than doing manually (takes hours)?
I have two Excel list indicating the path of PDF files that I need to merge- Is there anyway to do this using code? As the manual process takes hours to process. I've tried using VBA but IO don't have access to adobe API, so that's been stuck down. I am thinking python, any thoughts?
[ "Check out PyPDF2\nExample from pypdf2.readthedocs.io\nfrom PyPDF2 import PdfMerger\n\nmerger = PdfMerger()\n\nfor pdf in [\"file1.pdf\", \"file2.pdf\", \"file3.pdf\"]:\n merger.append(pdf)\n\nmerger.write(\"merged-pdf.pdf\")\nmerger.close()\n\n", "Python is the way to go.\nYou can do this quite easily by usin...
[ 1, 0 ]
[]
[]
[ "excel", "pdf", "python" ]
stackoverflow_0074467349_excel_pdf_python.txt
Q: Using pandas I need to create a new column that takes a value from a previous row I have many rows of data and one of the columns is a flag. I have 3 identifiers that need to match between rows. What I have: partnumber, datetime1, previousdatetime1, datetime2, previousdatetime2, flag What I need: partnumber, datet...
Using pandas I need to create a new column that takes a value from a previous row
I have many rows of data and one of the columns is a flag. I have 3 identifiers that need to match between rows. What I have: partnumber, datetime1, previousdatetime1, datetime2, previousdatetime2, flag What I need: partnumber, datetime1, previousdatetime1, datetime2, previousdatetime2, flag, previous_flag I need to fi...
[ "Okay, so assuming you've read this in as a pandas dataframe df1:\n(1) Make a copy of the dataframe:\ndf2=df1.copy()\n\n(2) For sanity, drop some columns in df2\ndf2.drop(['previousdatetime1','previousdatetime2'],axis=1,inplace=True) \n\nNow you have a df2 that has columns:\n['partnumber','datetime1','datetime2','f...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074466651_dataframe_pandas_python.txt
Q: Solve optimization problem with python library which has a logarithmic objective function How can I solve optimization problem: subject to: (I am looking for a library that its objective function can accept logarithms.) I found glpk and gurobipy but they don't seem to be able to do it. A: Based on your comment...
Solve optimization problem with python library which has a logarithmic objective function
How can I solve optimization problem: subject to: (I am looking for a library that its objective function can accept logarithms.) I found glpk and gurobipy but they don't seem to be able to do it.
[ "Based on your comments under the question, I am just going to refer you to one of the more standard libraries to solve this problem. Note the your objective concave and its a maximization problem. So, it is straightforward to rewrite it as a convex minimization problem and your constraints are linear. For such pro...
[ 0 ]
[]
[]
[ "mathematical_optimization", "python" ]
stackoverflow_0074467453_mathematical_optimization_python.txt
Q: Does order of methods within a class matter? My problems or rather my misunderstanding are next. First one: Basically i made my linked list class, and now as you can see in following code in constructor i called append method before it was actually created and the code run without an error, so i am really interes...
Does order of methods within a class matter?
My problems or rather my misunderstanding are next. First one: Basically i made my linked list class, and now as you can see in following code in constructor i called append method before it was actually created and the code run without an error, so i am really interested to know why i didn't encountered any error the...
[ "Functions being defined is different from them being run; in your code, you define __init__ before you define append, but you don't actually call append until later. By the time you call it, it's been defined.\nFor the order of prints, __init__ is called implicitly when you create the LinkedList.\n", "Your defin...
[ 1, 0 ]
[]
[]
[ "constructor", "methods", "oop", "python" ]
stackoverflow_0074467567_constructor_methods_oop_python.txt
Q: How do I screenshot a single monitor using OpenCV? I am trying to devleope a device that changes the RGB led strips according to the colour of my display. To this I am planning on screnshotiing the screen an normalising/taking the mean of the colours of individual pixels in the display. I have figured out how to s...
How do I screenshot a single monitor using OpenCV?
I am trying to devleope a device that changes the RGB led strips according to the colour of my display. To this I am planning on screnshotiing the screen an normalising/taking the mean of the colours of individual pixels in the display. I have figured out how to screenshot a single monitor but want to make it work with...
[ "Using python-mss, we may iterate the list of monitors, and grab a frame from each monitor in a loop (we may place that loop in an endless loop).\n\nExample for iterating the monitors:\nfor monitor_number, mon in enumerate(sct.monitors[1:]):\n\n\nWe are ignoring index 0 (it looks like sct.monitors[0] applies a larg...
[ 2 ]
[]
[]
[ "image_processing", "python", "python_3.x" ]
stackoverflow_0074462726_image_processing_python_python_3.x.txt