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:
Error when pushing to BigQuery tables containing lists and dics
The following code works in Google Colab but not on my local computer.
import pandas as pd
from google.oauth2 import service_account
df = pd.DataFrame()
df['A'] = [[1], [2], [3]]
credentials = service_account.Credentials.from_service_account_info({... | Error when pushing to BigQuery tables containing lists and dics | The following code works in Google Colab but not on my local computer.
import pandas as pd
from google.oauth2 import service_account
df = pd.DataFrame()
df['A'] = [[1], [2], [3]]
credentials = service_account.Credentials.from_service_account_info({--credential infos--},)
df.to_gbq(destination_table='raw.test', proj... | [
"Google BigQuery does not accepts python lists or dictionaries, here is a list of the types it accepts.\nI think you are confusing these types with JSON formatted strings (Note that \"JSON is purely a string with a specified data format — it contains only properties, no methods.\")\nThis:\ndf.DataFrame()\n\ndf['A']... | [
0
] | [] | [] | [
"google_bigquery",
"pandas",
"python"
] | stackoverflow_0074145331_google_bigquery_pandas_python.txt |
Q:
'float' object not iterable, dcc.Upload in Dash
This is a strange error, and one that has been asked before here but unfortunately went unanswered.
I have taken the code from the Dash official documentation here, which allows the user to upload a csv or xls file and view it as a datatable in the dash web app. I've... | 'float' object not iterable, dcc.Upload in Dash | This is a strange error, and one that has been asked before here but unfortunately went unanswered.
I have taken the code from the Dash official documentation here, which allows the user to upload a csv or xls file and view it as a datatable in the dash web app. I've copied and pasted the code below:
import base64
impo... | [
"After long debugging, the problem is that list_of_dates is a float number which represents the last modified for the uploaded file. There is a list comprehension in the callback which iterates through this float number, which does not make sense to iterate through a number, and it eventually throws an error. To so... | [
1
] | [] | [] | [
"csv",
"plotly_dash",
"python"
] | stackoverflow_0074145275_csv_plotly_dash_python.txt |
Q:
Regex-- How to extract the text after the second hyphen for each parenthesis?
I am new to the Regex and the grammar made me confused. Here is the original string field : (f-dqcn-bus1),(f-cdqc-bus2)
I would like to have the new result like bus1,bus2.
There could be one or several parenthesis but the bus name is alw... | Regex-- How to extract the text after the second hyphen for each parenthesis? | I am new to the Regex and the grammar made me confused. Here is the original string field : (f-dqcn-bus1),(f-cdqc-bus2)
I would like to have the new result like bus1,bus2.
There could be one or several parenthesis but the bus name is always after the second hyphen in each parenthesis. I plan to use the str.findall(rege... | [
"I'm not sure if this works for you but I've tried it before and I kinda love .str methods in Pandas!\nimport pandas as pd\n\ndata = [('f-dqcn-bus1'), ('f-cdqc-bus2')]\ndf = pd.DataFrame(data, columns=['column_name'])\ntuple(df['column_name'].str.split('-', n = 2, expand = True)[2])\n\n# ('bus1', 'bus2')\n\n",
"M... | [
3,
0
] | [] | [] | [
"extract",
"pandas",
"python"
] | stackoverflow_0074145711_extract_pandas_python.txt |
Q:
Hot to capture Selenium WebDriver exception using Python Interactive Window in Visual Studio Code?
I receive the Selenium exception NoSuchElementException though I have a try except block.
Here is a reduced version of the code, the stack trace indicates that it is the WebDriverWait line that is causing the Excepti... | Hot to capture Selenium WebDriver exception using Python Interactive Window in Visual Studio Code? | I receive the Selenium exception NoSuchElementException though I have a try except block.
Here is a reduced version of the code, the stack trace indicates that it is the WebDriverWait line that is causing the Exception:
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from... | [
"Accordingly to presented here code, the exception can be cause by row.find_element(By.XPATH, './/td[3]').click() code line.\nThis line is not inside the try block now.\nIf so, you can simply move it into the try block, as following:\nfrom selenium import webdriver\nfrom selenium.webdriver.support import expected_c... | [
1
] | [] | [] | [
"exception",
"python",
"selenium",
"selenium_webdriver",
"try_catch"
] | stackoverflow_0074146133_exception_python_selenium_selenium_webdriver_try_catch.txt |
Q:
Python: better to make new temporary list or make multiple index accesses to same list?
I have a 3d list, and I need to compare each element at the lowest level to the max of the list it's in.
if lst[i][j][k] == max(lst[i][j]): ...
is this bad practice? it's worse on performance, the only alternative I can think... | Python: better to make new temporary list or make multiple index accesses to same list? | I have a 3d list, and I need to compare each element at the lowest level to the max of the list it's in.
if lst[i][j][k] == max(lst[i][j]): ...
is this bad practice? it's worse on performance, the only alternative I can think of is
templst = lst[i][j]
if templst[k] == max(templst): ...
but this is worse on memory af... | [
"\nbut this is worse on memory afaik\n\nI think you assume that the new variable is a copy of the list, but it isn't. When you do templst = lst[i][j], the only additional memory used is for a reference to the existing list.\n"
] | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074145343_list_python.txt |
Q:
tkinter .insert adds lines to two listboxes at once
I'm creating a tkinter GUI and I have two list boxes that are supposed to have the same single line of text inserted into them upon initialization. The listboxes have separate names, but each time I run .insert for either of the listboxes, both of them get the li... | tkinter .insert adds lines to two listboxes at once | I'm creating a tkinter GUI and I have two list boxes that are supposed to have the same single line of text inserted into them upon initialization. The listboxes have separate names, but each time I run .insert for either of the listboxes, both of them get the line added to them and I can't figure out why. The same thi... | [
"You have in effect given both listboxes the same listvariable which forces them to be in sync. When you specify the listvariable option, the string representation of what you give it becomes an internal variable name. Both widgets end up with a variable named \"['+ Add New Condition']\" (eg: str([\"+ Add New Condi... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074146167_python_tkinter.txt |
Q:
Python subtracting one column from all other in dataframe
I have a dataframe with binary variables created using get_dummy(). I am using the method sub() to subtract one column from all others within this dataframe. However, when i do this, in those cases where i should get a value of -1 I instead get 255 as resul... | Python subtracting one column from all other in dataframe | I have a dataframe with binary variables created using get_dummy(). I am using the method sub() to subtract one column from all others within this dataframe. However, when i do this, in those cases where i should get a value of -1 I instead get 255 as result.
Does anybody knows why is this and how can i solve it?
| [
"Because pd.get_dummies returns type of uint8, which is not signed. You should convert them before doing subtraction:\n# ...\ndf_dummy = pd.get_dummies(your_data).astype(int)\n# ...\n\nFor a quick test, you can compare the results of\npd.get_dummies(pd.Series(list('abca')))-1\n\nand\npd.get_dummies(pd.Series(list('... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074145869_python.txt |
Q:
Y axis label not being saved when trying to save a plot as a pdf
currently I am trying to save a matplotlib plot as a PDF, however the Y axis is not being shown in the final figure despite being displayed in the plot. More specifically, I have the following subplots:
import matplotlib.pyplot as plt
from numpy impo... | Y axis label not being saved when trying to save a plot as a pdf | currently I am trying to save a matplotlib plot as a PDF, however the Y axis is not being shown in the final figure despite being displayed in the plot. More specifically, I have the following subplots:
import matplotlib.pyplot as plt
from numpy import random
sizes=22
x1 = random.randint(2000, size=(125))... | [
"Use supxlabel and supylabel. Also, I suggest switching to the object-oriented interface (using fig, axs = plt.subplots()).\nsizes=22\n\nfig, axs = plt.subplots(nrows=2, ncols=3, figsize=(18, 14))\n\ndef my_plot(ax, x1, x2, title):\n ax.plot(x1, color='red', label='Class 1')\n ax.plot(x2, color='blue', label=... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074146162_matplotlib_python.txt |
Q:
Using def to get the dictionary key to use as a variable
I want to change value in a variable in a data frame called 'Communication_language_c' but I don't not want the reference the df column directly. I want to get the variable name from a dictionary key by calling the function name.
import pandas as pd
data= [... | Using def to get the dictionary key to use as a variable | I want to change value in a variable in a data frame called 'Communication_language_c' but I don't not want the reference the df column directly. I want to get the variable name from a dictionary key by calling the function name.
import pandas as pd
data= [["English"]]
df= pd.DataFrame(data,columns=['Communication_Lan... | [
"You can just use .replace like this:\ndf.replace(parsing_map)\n\nAdditional example for clarification:\nIf you have a df like this:\ndata = [[\"English\", \"English\"]]\ndf = pd.DataFrame(data, columns=['Communication_Language__c', 'Communication_Language__d'])\n\nYou can add an additional key:value pair\nparsing_... | [
0
] | [] | [] | [
"dictionary",
"pandas",
"python"
] | stackoverflow_0074146287_dictionary_pandas_python.txt |
Q:
Pairwise join of dataframe rows
I have a dataframe that looks like this- This is just a sample but the actual dataframe has more columns and thousands of rows:
Group ID Loc Dist
A 1 D1 314
A 2 D2 299
A 3 D3 323
A 4 D4 379
B 1 D1 314
B... | Pairwise join of dataframe rows | I have a dataframe that looks like this- This is just a sample but the actual dataframe has more columns and thousands of rows:
Group ID Loc Dist
A 1 D1 314
A 2 D2 299
A 3 D3 323
A 4 D4 379
B 1 D1 314
B 2 D2 299
B 3 ... | [
"You can use a groupby operation with help of itertools.combinations:\nfrom itertools import combinations\n\ndef combine(df):\n a,b = map(list, zip(*combinations(df.index, r=2)))\n return pd.concat([df.loc[a].reset_index(drop=True).add_suffix('_1'),\n df.loc[b].reset_index(drop=True).add_... | [
0
] | [] | [] | [
"dataframe",
"join",
"merge",
"pandas",
"python"
] | stackoverflow_0074144805_dataframe_join_merge_pandas_python.txt |
Q:
Is there a way to plot matrix elements like a heat map?
I'm programming a code where I use a matrix full of 0's and 1's, the idea is to represent a galaxy, so the 0's are like the void and the 1's will be solar systems (for now), later I intend to add more elements. So, I was wondering if there's a way to plot thi... | Is there a way to plot matrix elements like a heat map? | I'm programming a code where I use a matrix full of 0's and 1's, the idea is to represent a galaxy, so the 0's are like the void and the 1's will be solar systems (for now), later I intend to add more elements. So, I was wondering if there's a way to plot this elements sorta like a heat map (1 = red and 0 = blue). I'd ... | [
"Using plt.imshow we can make heat maps you can read more about it here: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nmatrix = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],\n ... | [
1,
0
] | [] | [] | [
"matrix",
"plot",
"python",
"python_3.x"
] | stackoverflow_0074119260_matrix_plot_python_python_3.x.txt |
Q:
CherryPy Python error "No such file or directory"
Im trying to run a python Server using CherryPy for a WebSite but when I run it this error pops up.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/cherrypy/_cpr... | CherryPy Python error "No such file or directory" | Im trying to run a python Server using CherryPy for a WebSite but when I run it this error pops up.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/cherrypy/_cprequest.py", line 638, in respond
self._do_respond(p... | [
"Hard to say without seeing your exact code that this is calling.\nJudging by the Error you are trying to use Sessions.\nThe sessions are looking for\n/var/www/html/cncsessions\nTo place the session files in\nBut it gives an error. It looks like the path might be wrong. There's a double backslash at the end there a... | [
0
] | [] | [] | [
"cherrypy",
"python",
"server"
] | stackoverflow_0074061141_cherrypy_python_server.txt |
Q:
AttributeError: partially initialized module 'posts.views' has no attribute 'SearchMenuPage' (most likely due to a circular import)
I'm attempting to emulate the url routing of StackOverflow when it comes to requesting a URL with the path of search/. As shown, requesting that URL redirects to search?q=.
Yet the f... | AttributeError: partially initialized module 'posts.views' has no attribute 'SearchMenuPage' (most likely due to a circular import) | I'm attempting to emulate the url routing of StackOverflow when it comes to requesting a URL with the path of search/. As shown, requesting that URL redirects to search?q=.
Yet the following error is being raised when running the test to achieve the aforementioned result:
AttributeError: partially initialized module ... | [
"Assigning an interpolated string with the query string added to the url property caused the error to be raised.\nSolution:\nclass SearchMenuPage(RedirectView):\n\n pattern_name = \"posts:search_results\"\n\n def get_redirect_url(self, *args, **kwargs):\n url = reverse(self.pattern_name)\n retur... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074117461_django_python.txt |
Q:
pyinstaller exe file does not open
I made exe file from with pyinstaller. Exe file is 38 MB, it has tkinter but when I click exe file cmd window opens up, CPU works 100%, I waited 10 minutes nothing happened.
How can I resolve it?
COde is below;
import sys, subprocess, pkg_resources
required={'tk'}
installed={pkg... | pyinstaller exe file does not open | I made exe file from with pyinstaller. Exe file is 38 MB, it has tkinter but when I click exe file cmd window opens up, CPU works 100%, I waited 10 minutes nothing happened.
How can I resolve it?
COde is below;
import sys, subprocess, pkg_resources
required={'tk'}
installed={pkg.key for pkg in pkg_resources.working_se... | [
"this part of the code is causing the issue, removing it will fix the issue.\nimport sys, subprocess, pkg_resources\n\nrequired={'tk'}\ninstalled={pkg.key for pkg in pkg_resources.working_set}\nmissing=required - installed\n\nif missing:\n python=sys.executable\n subprocess.check_call([python,'-m','pip','inst... | [
2
] | [] | [] | [
"exe",
"pyinstaller",
"python",
"tkinter"
] | stackoverflow_0074146332_exe_pyinstaller_python_tkinter.txt |
Q:
Update or delete Labels with conditions
i need to delete or change the labels of the function "obtener_info" and i dont know how to update or delete a label with conditions in tkinter. Some one know how to do it?
Here is my code, im working with pyserial and a heartbeat sensor. It's for a school project.
............ | Update or delete Labels with conditions | i need to delete or change the labels of the function "obtener_info" and i dont know how to update or delete a label with conditions in tkinter. Some one know how to do it?
Here is my code, im working with pyserial and a heartbeat sensor. It's for a school project.
......................................................... | [
"I put a label.configure in every condition and now it changes every update of the arduino. Here is the code updated.\nif genero == \"femenino\":\n label_estado = Label(NewWind, text=\"Su estado de salud es \", font=\"Century_Gothic\")\n label_es... | [
0
] | [] | [] | [
"pyserial",
"python",
"tkinter"
] | stackoverflow_0074145422_pyserial_python_tkinter.txt |
Q:
praw, Invalid leading whitespace, reserved character(s), or returncharacter(s) in header value
try:
reddit = praw.Reddit(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, user_agent=USER_AGENT, username=USERNAME, password=PASSWORD)
hot_posts = reddit.subreddit('seriea').hot(limit=30)
for submission in ... | praw, Invalid leading whitespace, reserved character(s), or returncharacter(s) in header value | try:
reddit = praw.Reddit(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, user_agent=USER_AGENT, username=USERNAME, password=PASSWORD)
hot_posts = reddit.subreddit('seriea').hot(limit=30)
for submission in hot_posts: # this is the line that creates the error
print(submission)
except Exception as e... | [
"I corrected CLIENT ID, CLIENT SECRET and credentials, and now it works.\n"
] | [
0
] | [] | [] | [
"exception",
"praw",
"python",
"python_3.x",
"reddit"
] | stackoverflow_0074145180_exception_praw_python_python_3.x_reddit.txt |
Q:
Pylance requiring explicit type on conformant list variables
I define a type as a Union of Literal strings
Color = Literal[
"red",
"green",
"blue",
"yellow",
"orange",
"purple"
]
I have a function that expects a list of strings conforming to the type.
def f(colors: List[Color]):
...
I... | Pylance requiring explicit type on conformant list variables | I define a type as a Union of Literal strings
Color = Literal[
"red",
"green",
"blue",
"yellow",
"orange",
"purple"
]
I have a function that expects a list of strings conforming to the type.
def f(colors: List[Color]):
...
I instantiate a list of conformant strings and pass it to the funct... | [
"Python literals, like 'blue' or 7, have a natural type. 'blue' is a str, and 7 is an int, according to their runtime types. Type Literals can throw a little confusion into this, because while they take specific objects and give them additional semantic meaning (like 'blue' being a Color or 7 being parameter for f(... | [
3
] | [] | [] | [
"pylance",
"pylint",
"python",
"python_typing",
"types"
] | stackoverflow_0074145111_pylance_pylint_python_python_typing_types.txt |
Q:
Numpy "where" with multiple conditions
I try to add a new column "energy_class" to a dataframe "df_energy" which it contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200.
I try ... | Numpy "where" with multiple conditions | I try to add a new column "energy_class" to a dataframe "df_energy" which it contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200.
I try to use np.where from numpy, but I see that ... | [
"Try this:\nUsing the setup from @Maxu\ncol = 'consumption_energy'\nconditions = [ df2[col] >= 400, (df2[col] < 400) & (df2[col]> 200), df2[col] <= 200 ]\nchoices = [ \"high\", 'medium', 'low' ]\n \ndf2[\"energy_class\"] = np.select(conditions, choices, default=np.nan)\n\n\n consumption_energy ener... | [
121,
78,
27,
21,
4,
2,
1,
0
] | [
"myassign[\"assign3\"]=np.where(myassign[\"points\"]>90,\"genius\",(np.where((myassign[\"points\"]>50) & (myassign[\"points\"]<90),\"good\",\"bad\"))\n\nwhen you wanna use only \"where\" method but with multiple condition. we can add more condition by adding more (np.where) by the same method like we did above. and... | [
-1
] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0039109045_dataframe_numpy_pandas_python.txt |
Q:
Why my code is only working on the first object and the summs are not adding up?
Here is my code for Roman to Integer problem
I can not understand why the for loop is only working on the first two elements.
class Solution(object):
def romanToInt(self, S):
ran = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D':... | Why my code is only working on the first object and the summs are not adding up? | Here is my code for Roman to Integer problem
I can not understand why the for loop is only working on the first two elements.
class Solution(object):
def romanToInt(self, S):
ran = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
sum = 0
for i in S:
num = ran[i]
num2 = ran[S... | [
"It's because the \"return\" is inside the for loop, so when the first loop ends, the program ends, to fix it just take the \"return\" out of your for loop.\ndef romanToInt(self, S):\n\n for i in S:\n .......\n .......\n\n return sum\n\n",
"return will break for loop when excute put it after f... | [
2,
0
] | [] | [] | [
"add",
"for_loop",
"python",
"sum"
] | stackoverflow_0074144502_add_for_loop_python_sum.txt |
Q:
AttributeError: module 'moviepy.audio.fx.all' has no attribute 'audio_fadein'
After converting my code to exe either via auto-py-to-exe or pyinstaller, I get the following errors in relation to moviepy. The reason I need moviepy is that I cannot convert to mp4 when using a variable name although I can when set as ... | AttributeError: module 'moviepy.audio.fx.all' has no attribute 'audio_fadein' | After converting my code to exe either via auto-py-to-exe or pyinstaller, I get the following errors in relation to moviepy. The reason I need moviepy is that I cannot convert to mp4 when using a variable name although I can when set as a string in the code seen below. I have all the necessary libraries installed as fa... | [
"You have to use\nfrom moviepy.audio.io.VideoFileClip import VideoFileClip\n\nReplace\nimport moviepy.editor as moviepy\n\n",
"from moviepy.video.VideoClip import VideoClip\nis working for me.\nSource/doc: https://moviepy.readthedocs.io/en/latest/_modules/moviepy/video/io/VideoFileClip.html\n"
] | [
0,
0
] | [] | [] | [
"attributeerror",
"moviepy",
"pyinstaller",
"python",
"traceback"
] | stackoverflow_0067101527_attributeerror_moviepy_pyinstaller_python_traceback.txt |
Q:
I'm getting a letter output instead of the index value printed twice, why is that?
names = ['Amir', 'Bear', 'Charlton', 'Daman']
print(names[-1][-1])
I'd expect it to print Daman twice but it's giving outputting the letter n instead??
A:
If you try
print(names[-1])
you'll see it prints
Daman
then [-1] again ... | I'm getting a letter output instead of the index value printed twice, why is that? | names = ['Amir', 'Bear', 'Charlton', 'Daman']
print(names[-1][-1])
I'd expect it to print Daman twice but it's giving outputting the letter n instead??
| [
"If you try\nprint(names[-1])\n\nyou'll see it prints\nDaman\n\nthen [-1] again (1 from the right)\nit prints\nn\n\n",
"You get position -1 in the list which is 'Daman' and position -1 in 'Daman' which is 'N'.\ndo:\nprint(names[-1]*2)\n\n",
"You aren't indexing names twice; you are indexing names, then indexing... | [
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074146528_python.txt |
Q:
File: file:/C:/Python/HDFS/program1/mapper.py is not readable
I am getting below error while executing starting Hadoop job
File: file:/C:/Python/HDFS/program1/mapper.py is not readable.
Using below command
hadoop jar C:\hadoop\share\hadoop\tools\lib\hadoop-streaming-3.2.0.jar -file C:/Python/HDFS/program1/mapper.p... | File: file:/C:/Python/HDFS/program1/mapper.py is not readable | I am getting below error while executing starting Hadoop job
File: file:/C:/Python/HDFS/program1/mapper.py is not readable.
Using below command
hadoop jar C:\hadoop\share\hadoop\tools\lib\hadoop-streaming-3.2.0.jar -file C:/Python/HDFS/program1/mapper.py -file C:/Python/HDFS/program1/reducer.py -mapper "python mapper.p... | [
"Try to change the version of your hadoop by an oldest version, i had a version 3.2.4 and I've had the same error when I tried to execute the hadoop job command, until I change it by version 2.10.2 the problem was solved.\n"
] | [
1
] | [] | [] | [
"hadoop",
"hdfs",
"python"
] | stackoverflow_0067655356_hadoop_hdfs_python.txt |
Q:
AttributeError Py
New to Python Selenium.
I am trying to create an script to login to my home router and press the button restart.
Running to error, when trying to login to the router, can some on guide on my mistake here.
below is the code and also attaching the .screenshot
from selenium import webdriver
from sel... | AttributeError Py | New to Python Selenium.
I am trying to create an script to login to my home router and press the button restart.
Running to error, when trying to login to the router, can some on guide on my mistake here.
below is the code and also attaching the .screenshot
from selenium import webdriver
from selenium.webdriver.chrome.... | [
"Probably you are using Selenium 4. if so, find_element_by_xpath and all the others find_element_by_* methods are not supported by Selenium 4, you have to use the new syntax and add an essential import, as following:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom seleni... | [
2,
1
] | [] | [] | [
"python",
"selenium",
"selenium4",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074146544_python_selenium_selenium4_selenium_chromedriver_selenium_webdriver.txt |
Q:
Cannot call Python script from macro using xlwings
I am working with xlwings v0.25.0 and have the matching version for the Excel add-in. I am also using Office 365 and Python 3.7.4.
I am trying to run a Python script, testing_xlwings.py from a vba macro in Excel.
import xlwings as xw
def main():
sheet = xw.Bo... | Cannot call Python script from macro using xlwings | I am working with xlwings v0.25.0 and have the matching version for the Excel add-in. I am also using Office 365 and Python 3.7.4.
I am trying to run a Python script, testing_xlwings.py from a vba macro in Excel.
import xlwings as xw
def main():
sheet = xw.Book.caller().sheets[0]
sheet.range('B10').value = 'IT... | [
"I was able to get the macro to the call the Python script by pressing Alt + F11 to bring up the VBA editor. From the toolbar across the top, I selected Tools -> References and I ticked the checkbox for xlwings. After I clicked OK I was able to run the script.\n",
"if you still get error... try to install a previ... | [
0,
0
] | [] | [] | [
"excel",
"python",
"xlwings"
] | stackoverflow_0069847007_excel_python_xlwings.txt |
Q:
How to handle UniqueConstraint failure in Django Meta Class?
I have created a UniqueConstraint Meta Class for my model, and it works when I test it by intentionally creating a duplicate but I am getting an error page instead of being redirected back to the original page. Where do I insert the code to go back to th... | How to handle UniqueConstraint failure in Django Meta Class? | I have created a UniqueConstraint Meta Class for my model, and it works when I test it by intentionally creating a duplicate but I am getting an error page instead of being redirected back to the original page. Where do I insert the code to go back to the page that I was just on?
I assume the issue is in the view, but ... | [
"Your form only requires the field student so it's valid because you haven't given its instance a value for scheduled_class when it gets validated.\nYou should initialise your form with an instance for which scheduled_class is already set. You can do that in get_form_kwargs() or, since that method passes self.objec... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0056464657_django_python.txt |
Q:
How to set up this complicated grid of plots in matplotlib?
I would like to achieve the following grid:
The four plots share their y-axes, and the bottom center duo share their x-axis. How do I achieve this in matplotlib?
A:
You could use plt.GridSpec (see doc here):
import matplotlib.pyplot as plt
fig=plt.fig... | How to set up this complicated grid of plots in matplotlib? | I would like to achieve the following grid:
The four plots share their y-axes, and the bottom center duo share their x-axis. How do I achieve this in matplotlib?
| [
"You could use plt.GridSpec (see doc here):\nimport matplotlib.pyplot as plt\n\nfig=plt.figure()\ngs=plt.GridSpec(12,16)\naxs=[]\naxs.append(plt.subplot(gs[0:6,0:4])) #Top left subplot. WIll be used as a reference to share y axis with the other 3 subplots on top\n[axs.append(plt.subplot(gs[0:6,4*(i+1):4*(i+2)],shar... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074144535_matplotlib_python.txt |
Q:
Column name repetition in pandas data frame
I am trying to read some data but the column names are repeatedly coming.
Here is a sample code:
for i in range(1, len(df_A2C), 1):
A2C_TT= df_A2C.loc[(df_A2C['TO_ID'] == i)].sort_values('DURATION_H').head(1)
if A2C_TT.size > 0:
print (A2C_TT)
Output:
I... | Column name repetition in pandas data frame | I am trying to read some data but the column names are repeatedly coming.
Here is a sample code:
for i in range(1, len(df_A2C), 1):
A2C_TT= df_A2C.loc[(df_A2C['TO_ID'] == i)].sort_values('DURATION_H').head(1)
if A2C_TT.size > 0:
print (A2C_TT)
Output:
I do not need column names. What should I do?
| [
"You may simply call the values method after head:\nfor i in range(1, len(df_A2C), 1):\n A2C_TT= df_A2C.loc[(df_A2C['TO_ID'] == i)].sort_values('DURATION_H').head(1).values\n if A2C_TT.size > 0:\n print (A2C_TT)\n\nEDIT:\nOn a side note, I think that you may get away without iterating over your pandas ... | [
4
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074146575_dataframe_jupyter_notebook_pandas_python_python_3.x.txt |
Q:
AWS S3. Append data in JSON. JSON file visual format
I try to add data to existing in S3 bucket JSON file.
Initial structure:
{
"id": "1",
"name": "test1",
"limit": [20.0, 30.0]
}
I add
{
"id": "2",
"name": "test2",
"limit": [10.0, 20.0]
}
and... | AWS S3. Append data in JSON. JSON file visual format | I try to add data to existing in S3 bucket JSON file.
Initial structure:
{
"id": "1",
"name": "test1",
"limit": [20.0, 30.0]
}
I add
{
"id": "2",
"name": "test2",
"limit": [10.0, 20.0]
}
and rewrite it on bucket.
When I download it from bucket it g... | [
"Your code is doing everything with strings, rather than converting strings into objects.\nThe json.dumps(obj) command converts a Python object into a JSON string.\nTo convert a JSON string into a Python object, use json.loads(str).\nTherefore, your code should be doing something like this (I didn't test it):\ns3 =... | [
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"append",
"json",
"python"
] | stackoverflow_0074143202_amazon_s3_amazon_web_services_append_json_python.txt |
Q:
dataframe, set index from list
Is it possible when creating a dataframe from a list, to set the index as one of the values?
import pandas as pd
tmp = [['a', 'a1'], ['b',' b1']]
df = pd.DataFrame(tmp, columns=["First", "Second"])
First Second
0 a a1
1 b b1
And how I'd like it to l... | dataframe, set index from list | Is it possible when creating a dataframe from a list, to set the index as one of the values?
import pandas as pd
tmp = [['a', 'a1'], ['b',' b1']]
df = pd.DataFrame(tmp, columns=["First", "Second"])
First Second
0 a a1
1 b b1
And how I'd like it to look:
First Second
a ... | [
"Change it to list before assigning it to index\ndf.index = list(df[\"First\"])\n\n",
">>> pd.DataFrame(tmp, columns=[\"First\", \"Second\"]).set_index('First', drop=False)\n First Second\nFirst \na a a1\nb b b1\n\n",
"set_axis\nTo set arbitrary values as the index, best... | [
20,
14,
9,
7,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0039132181_pandas_python.txt |
Q:
Multiplying two elements in a list
How can I multiply two elements in a list?
I am reading a text file, and printing the following:
for i in range(len(listeisotoper)):
print("Isotop type:"+listeisotoper[i][0])
print("Isotopisk masse u: "+listeisotoper[i][1])
print("Naturlig forekomst: "+listeisotoper[i... | Multiplying two elements in a list | How can I multiply two elements in a list?
I am reading a text file, and printing the following:
for i in range(len(listeisotoper)):
print("Isotop type:"+listeisotoper[i][0])
print("Isotopisk masse u: "+listeisotoper[i][1])
print("Naturlig forekomst: "+listeisotoper[i][2])
print("xxx"+"g/mol")
print... | [
"I am assuming your problem is multiplying strings. If so, try this:\nfor i in range(len(listeisotoper)):\n print(\"Isotop type:\"+listeisotoper[i][0])\n print(\"Isotopisk masse u: \"+listeisotoper[i][1])\n print(\"Naturlig forekomst: \"+listeisotoper[i][2])\n print(str(float(listeisotoper[i][1])*float(... | [
0,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074146558_list_python_python_3.x.txt |
Q:
Why do instance variables and class variables return different output for this closure?
I have a closure that is supposed to save the return value of a computationally heavy function for reuse. However, when I run the exact same line of code (_ = cached_readonly_property(lambda: "b")), I get different return value... | Why do instance variables and class variables return different output for this closure? | I have a closure that is supposed to save the return value of a computationally heavy function for reuse. However, when I run the exact same line of code (_ = cached_readonly_property(lambda: "b")), I get different return values based on whether the variable is a class variable (b) or instance variable (c). Why is this... | [
"Property descriptors support binding behavior only on class variables.\nPython runtime transforms the class variable during attribute lookup to the following.\ntype(a).__dict__['b'].__get__(b, type(b))\n\nFor a attribute, you need to make a direct call to read its value.\n print(a.a.__get__(a))\n\n"
] | [
1
] | [] | [] | [
"closures",
"object",
"oop",
"python",
"python_class"
] | stackoverflow_0074143103_closures_object_oop_python_python_class.txt |
Q:
scipy curve_fit give the initial guess values as optimal results when I set the bounds parameter
I'm trying to fit a curve with a Gaussian plus a Lorentzian function, using the curve_fit function from scipy.
def gaussian(x, a, x0, sig):
return a * np.exp(-1/2 * (x - x0)**2 / sig**2)
def lorentzian(x, a, b, c)... | scipy curve_fit give the initial guess values as optimal results when I set the bounds parameter | I'm trying to fit a curve with a Gaussian plus a Lorentzian function, using the curve_fit function from scipy.
def gaussian(x, a, x0, sig):
return a * np.exp(-1/2 * (x - x0)**2 / sig**2)
def lorentzian(x, a, b, c):
return a*c**2/((x-b)**2+c**2)
def decompose(x, z, n, b, *par):
hb_n = gaussian(x, par[0], 4... | [
"This happens due to a combination of the optimization algorithm and its parameters.\nFrom the official documentation:\n\nmethod{‘lm’, ‘trf’, ‘dogbox’}, optional\nMethod to use for optimization. See least_squares for more details.\nDefault is ‘lm’ for unconstrained problems and ‘trf’ if bounds are\nprovided. The me... | [
0
] | [] | [] | [
"curve_fitting",
"python",
"scipy"
] | stackoverflow_0074141267_curve_fitting_python_scipy.txt |
Q:
Merging Pandas Dataframes with unequal rows and columns
i am trying to merge two dataframes with an unequal number of rows and columns.
df1 looks like this:
code, item, size, 2020, 2021, 2022, 2023, 2024
1, i1, 50, 303, 343, 432, 855, 431
1, i2, 50, 763, 555, 988, 499, 691
1, i3, 50, 111, 935, 711, 621, 951
2, i1,... | Merging Pandas Dataframes with unequal rows and columns | i am trying to merge two dataframes with an unequal number of rows and columns.
df1 looks like this:
code, item, size, 2020, 2021, 2022, 2023, 2024
1, i1, 50, 303, 343, 432, 855, 431
1, i2, 50, 763, 555, 988, 499, 691
1, i3, 50, 111, 935, 711, 621, 951
2, i1, 50, 998, 222, 533, 629, 853
2, i2, 50, 345, 345, 222, 908, 1... | [
"You are looking for an outer merge\ndf1 = pd.DataFrame({'code': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2}, ' item': {0: ' i1', 1: ' i2', 2: ' i3', 3: ' i1', 4: ' i2', 5: ' i3'}, ' size': {0: 50, 1: 50, 2: 50, 3: 50, 4: 50, 5: 50}, ' 2020': {0: 303, 1: 763, 2: 111, 3: 998, 4: 345, 5: 777}, ' 2021': {0: 343, 1: 555, 2: 9... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074146612_dataframe_pandas_python.txt |
Q:
how to solve Encoding error in using selenium
I am facing the encoding error how to fix that this is error File "F:\python\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 117-122: ... | how to solve Encoding error in using selenium | I am facing the encoding error how to fix that this is error File "F:\python\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 117-122: character maps to <undefined> bacillay I having e... | [
"Try to enforce utf-8 throughout the program.\ndf_urls = pd.read_csv('D:/selenium/inputs/amazone-asin.csv', encoding='utf-8')\n\nand see if the data file is corrupted.\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074146670_python_selenium_web_scraping.txt |
Q:
Counting number of permutations in permutation
A permutation of size n is a sequence of n integers in which each of the values from 1 to n occurs exactly once. For example, the sequences [3, 1, 2], [1], and [1, 2, 3, 4] are permutations, while [2], [4, 1, 2], [3, 1] are not.
So i recieve 2 inputs: 1 - number of ... | Counting number of permutations in permutation | A permutation of size n is a sequence of n integers in which each of the values from 1 to n occurs exactly once. For example, the sequences [3, 1, 2], [1], and [1, 2, 3, 4] are permutations, while [2], [4, 1, 2], [3, 1] are not.
So i recieve 2 inputs: 1 - number of numbers in permutation,2 - the permutation by itself... | [
"l = [6, 3, 4, 1, 2, 7, 5]\n\nleft_bound = right_bound = l.index(1)\n\npermutations = []\n\nfor i in range(1,len(l)+1):\n new_index = l.index(i)\n\n # special case if i == 1\n if new_index == left_bound == right_bound:\n pass\n\n # if new index if further to the left, update the left index\n e... | [
1,
0
] | [] | [] | [
"algorithm",
"permutation",
"python",
"r"
] | stackoverflow_0074146246_algorithm_permutation_python_r.txt |
Q:
How can I detect if a value in a DataFrame crosses another value in the DataFrame
This is a sample of my DataFrame which is quite large. It is candlestick OHLC data with some additional columns 'Target' etc.
Open High ... Target
Close Time ... | How can I detect if a value in a DataFrame crosses another value in the DataFrame | This is a sample of my DataFrame which is quite large. It is candlestick OHLC data with some additional columns 'Target' etc.
Open High ... Target
Close Time ...
2022-05-23 06:59:59.999 30301.46 30655.00 ... NaN ... | [
"The following should work, assuming you also have a \"Low\" column.\n## generate example dataframe ##\nfrom numpy import nan\nd = {'Open': {'06:59:59.999': 30301.46, '07:59:59.999': 30487.77, '08:59:59.999': 30457.01, '09:59:59.999': 30345.73, '10:59:59.999': 30441.94}, \n 'High': {'06:59:59.999': 30655.0, '07... | [
1
] | [] | [] | [
"candlestick_chart",
"pandas",
"python"
] | stackoverflow_0074146482_candlestick_chart_pandas_python.txt |
Q:
How to debug a custom loss function during model fitting?
I would like to see what is happening in my loss function during model fitting.
However, I cannot figure out how to do that.
This is what I am trying but it does not work:
def custom_loss(label : tf.Tensor, pred : tf.Tensor) -> tf.Tensor:
mask = label !... | How to debug a custom loss function during model fitting? | I would like to see what is happening in my loss function during model fitting.
However, I cannot figure out how to do that.
This is what I am trying but it does not work:
def custom_loss(label : tf.Tensor, pred : tf.Tensor) -> tf.Tensor:
mask = label != 0
loss_object = tf.keras.losses.BinaryCrossentropy(from_l... | [
"In TF 2 Keras, it can be done by training the model in eager mode, i.e run_eagerly=True with model.fit. It's an argument avilable in model.compile method. From doc.\n\nrun_eagerly: Bool. Defaults to False. If True, this Model's logic will not be wrapped in a tf.function.\n\n\nNow, the end-to-end solution can be ac... | [
1
] | [] | [] | [
"loss_function",
"python",
"tensorflow"
] | stackoverflow_0074146034_loss_function_python_tensorflow.txt |
Q:
Format Pandas Dataframe from 2D Array
I have a problem where I am taking a 2D array and want to convert it to a pandas Dataframe. I will be taking this Dataframe and displaying in an excel spreadsheet.
I created my Dataframe like this: df = pd.DataFrame("twoDArray"). The 2D array I am transforming into a Dataframe... | Format Pandas Dataframe from 2D Array | I have a problem where I am taking a 2D array and want to convert it to a pandas Dataframe. I will be taking this Dataframe and displaying in an excel spreadsheet.
I created my Dataframe like this: df = pd.DataFrame("twoDArray"). The 2D array I am transforming into a Dataframe is of length 8, and I named all the column... | [
"The following code solves your question:\nlst = [[\"hello\", 1, 2], [\"World\", 3], [\"Goodbye\", 5,6,7,\"test\"]]\ndf = pd.DataFrame(lst).T\n\nBecause the .T represents transposing the dataframe, which is what you were trying to do, instead of your lists being rows, they should be columns, and the remaining value... | [
2
] | [] | [] | [
"dataframe",
"json",
"matrix",
"pandas",
"python"
] | stackoverflow_0074146502_dataframe_json_matrix_pandas_python.txt |
Q:
How efficient is pytail as compared to a shell tail running as subprocess (['tail','-f','filename.txt']) in a python script?
How efficient is pytail as compared to a shell tail running as subprocess in a python script?
subprocess.Popen(['tail','-f','filename.txt'])
A:
I just got pytail working and as far as I c... | How efficient is pytail as compared to a shell tail running as subprocess (['tail','-f','filename.txt']) in a python script? | How efficient is pytail as compared to a shell tail running as subprocess in a python script?
subprocess.Popen(['tail','-f','filename.txt'])
| [
"I just got pytail working and as far as I can tell there is no option to follow a file as it grows so it's basically pointless in most use cases. Just prints the last X lines.\nTo answer your question, not very.\n"
] | [
1
] | [] | [] | [
"python",
"tail"
] | stackoverflow_0050487511_python_tail.txt |
Q:
scrape data using keyword Python
I have this code using Python Requests library:
import requests
test_URL = "https://www.gasbuddy.com/station/194205"
def get_data(link):
hdr = {'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 M... | scrape data using keyword Python | I have this code using Python Requests library:
import requests
test_URL = "https://www.gasbuddy.com/station/194205"
def get_data(link):
hdr = {'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Mobile Safari/537.36'}
req = reques... | [
"The website has a few mechanisms inplace to prevent webscraping (or to make it harder):\nYou can use bs4 to analyse the response you get with requests.\n(pip install beautifulsoup4 https://pypi.org/project/beautifulsoup4/)\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.gasbuddy.com/station/... | [
0
] | [] | [] | [
"python",
"python_requests",
"scrape",
"web_scraping"
] | stackoverflow_0074132895_python_python_requests_scrape_web_scraping.txt |
Q:
CSV causing problems with 'nan' when formatting. What should I do?
I was trying to build a machine learning following this tutorial which worked fine with the iris dataset, however, when I tried to use my own CSV (for a project), it gave me an error. When I tried to use a different, unrelated method the same thing... | CSV causing problems with 'nan' when formatting. What should I do? | I was trying to build a machine learning following this tutorial which worked fine with the iris dataset, however, when I tried to use my own CSV (for a project), it gave me an error. When I tried to use a different, unrelated method the same thing occurred. (the rest of the details are at the bottom)
here is my code:
... | [
"Not all rows in your CSV have data on all columns (10). When there's missing data, it is represented as NaN (short for not-a-number).\nIn [42]: df = pd.read_csv(\"/tmp/energy.csv\", header=None)\nIn [43]: df\nOut[43]: \n 0 1 2 3 4 5 6 7 8 9\... | [
1
] | [] | [] | [
"csv",
"numpy",
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074146782_csv_numpy_pandas_python_scikit_learn.txt |
Q:
if elif is giving the wrong result
It's only giving me the result of the first operation which is multiplied even if my input was the addition.
print('Calculator')
operation = input('Choose:\n Mltiply(*)\n Divise\(/)\n Add(+)\n Subbstract(-)\n ')
if operation == 'mutiply' or 'Multiply' or 'MULTIPLY' or '*':
nu... | if elif is giving the wrong result | It's only giving me the result of the first operation which is multiplied even if my input was the addition.
print('Calculator')
operation = input('Choose:\n Mltiply(*)\n Divise\(/)\n Add(+)\n Subbstract(-)\n ')
if operation == 'mutiply' or 'Multiply' or 'MULTIPLY' or '*':
num1 = input('Write Your number :')
nu... | [
"Use the in operator\nelif operation in {'DIVISE', 'divise', 'Divise', '/'}:\n\nfor every if/else block.\nEDIT:\nYou can find a good explanation here:\nWhy does \"a == x or y or z\" always evaluate to True? How can I compare \"a\" to all of those?\n",
"Use in\nprint('Calculator')\noperation = input('Choose:\\n Ml... | [
1,
1
] | [] | [] | [
"calculator",
"python"
] | stackoverflow_0074146913_calculator_python.txt |
Q:
iPython notebook plantuml extension
How can we use plantuml UML tool in iPython notebook? It should helpful for us since UML figure is frequently used during paper work.
After some google from internet, I have found one excellent reference for Using Asymptote in iPython notebook, then I have created a plantuml ext... | iPython notebook plantuml extension | How can we use plantuml UML tool in iPython notebook? It should helpful for us since UML figure is frequently used during paper work.
After some google from internet, I have found one excellent reference for Using Asymptote in iPython notebook, then I have created a plantuml extension for iPython notebook. Below is det... | [
"Plantuml UML tool in iPython notebook is a great idea!\nInstead of adding the jar, you can also use the web service. You can get the error message this way. \nBased on the javascript API, I wrote a small python encoder to send strings to the plantUML server.\nNow, the extension looks like this\n\nimport urllib\n... | [
6,
4,
0
] | [] | [] | [
"ipython_notebook",
"plantuml",
"python",
"tikz",
"uml"
] | stackoverflow_0020303335_ipython_notebook_plantuml_python_tikz_uml.txt |
Q:
Can I use a single python script to create a virtualenv and install requirements.txt?
I am trying to create a script where i create a virtualenv if it has not been made, and then install requirements.txt in it.
I can't call the normal source /env/bin/activate and activate it, then use pip to install requirements.t... | Can I use a single python script to create a virtualenv and install requirements.txt? | I am trying to create a script where i create a virtualenv if it has not been made, and then install requirements.txt in it.
I can't call the normal source /env/bin/activate and activate it, then use pip to install requirements.txt. Is there a way to activate the virtualenv and then install my requirements from a singl... | [
"source is a shell builtin command, not a program. It cannot and shouldn't be executed with subprocess. You can activate your fresh virtual env by executing activate_this.py in the current process:\nif not os.path.exists(env_path):\n call(['virtualenv', env_path])\n activate_this = os.path.join(env_path, 'bin... | [
4,
1,
1
] | [] | [] | [
"python",
"subprocess",
"virtualenv"
] | stackoverflow_0049040017_python_subprocess_virtualenv.txt |
Q:
ModuleNotFoundError: No module named 'tastypie'
I am new to Django and coding in general.
When I try to use the django-tastypie (0.14.4) in my virtual env using pipenv, I get the following error when I try to launch the server ModuleNotFoundError: No module named 'tastypie'.
I tried the solutions in here and in he... | ModuleNotFoundError: No module named 'tastypie' | I am new to Django and coding in general.
When I try to use the django-tastypie (0.14.4) in my virtual env using pipenv, I get the following error when I try to launch the server ModuleNotFoundError: No module named 'tastypie'.
I tried the solutions in here and in here
Here is my models.py of my api app:
from tastypie.... | [
"confirm if you have installed django-tastypie in your virtual environment by: pipenv graph\nand enable the virtual environment using: pipenv shell\nnow try to run your command.....\n"
] | [
0
] | [] | [] | [
"api",
"django",
"modulenotfounderror",
"python",
"tastypie"
] | stackoverflow_0072405353_api_django_modulenotfounderror_python_tastypie.txt |
Q:
Getting NaN when using pandas groupby
I have a dataframe like so:
index date symbol stock_id open high low close volume vwap
0 0 2021-10-11 BVN 13 7.69 7.98 7.5600 7.61 879710 7.782174
1 1 2021-10-12 BVN 13 7.67 8.08 7.5803 8... | Getting NaN when using pandas groupby | I have a dataframe like so:
index date symbol stock_id open high low close volume vwap
0 0 2021-10-11 BVN 13 7.69 7.98 7.5600 7.61 879710 7.782174
1 1 2021-10-12 BVN 13 7.67 8.08 7.5803 8.02 794436 7.967061
2 2 202... | [
"You could do it like this:\ndef is_consolidating(grp, window=2, minp=2, percentage=0.95):\n\n rolling_min = pd.Series(grp).rolling(window=window, min_periods=minp).min()\n rolling_max = pd.Series(grp).rolling(window=window, min_periods=minp).max()\n consolidation = np.where( (rolling_min / rolling_max) >=... | [
1
] | [] | [] | [
"numpy",
"ohlc",
"pandas",
"python",
"stock"
] | stackoverflow_0074146516_numpy_ohlc_pandas_python_stock.txt |
Q:
Secondary window gets hidden behind main window when using new file dialog
I have a main window that's a normal window (not set on top or anything). There's an option in one of the menus that opens a secondary window (again a regular window) that has a text field where I need to display the filename I get from a f... | Secondary window gets hidden behind main window when using new file dialog | I have a main window that's a normal window (not set on top or anything). There's an option in one of the menus that opens a secondary window (again a regular window) that has a text field where I need to display the filename I get from a file dialog. My problem is that when the file dialog is opened, the secondary win... | [
"In any case, the self argument of widgets represents the parent widget, which, for dialogs, indicates the window for which the dialog is modal. Since you're using self, and open_select is a member of MainWindow, the result is that you're making it modal to that.\nThe easy solution would be to change that to the ac... | [
1
] | [] | [] | [
"pyqt",
"pyqt5",
"python"
] | stackoverflow_0074146768_pyqt_pyqt5_python.txt |
Q:
Function to split strings into multiline strings
Question:
Write the function wordWrap(text, width) which takes a string text containing only lowercase letters or spaces and a positive integer width, and returns a possibly-multiline string that matches the original string, only with line wrapping at the given widt... | Function to split strings into multiline strings | Question:
Write the function wordWrap(text, width) which takes a string text containing only lowercase letters or spaces and a positive integer width, and returns a possibly-multiline string that matches the original string, only with line wrapping at the given width. For example, wordWrap('abc', 3) just returns 'abc',... | [
"When completing the second line, the state of your code is:\nline == 'c-de'\nresult == 'a-b-\\n'\ni == 'e'\nwidth == 4\n\nWhat then executes:\nif len(line) == width: # this is True\n result += line # result is now 'a-b-\\nc-de'\n line = ''\n a = text.index(i) # a is now 7\n if (a + 1) != len(text): ... | [
0,
0
] | [] | [] | [
"loops",
"python",
"string"
] | stackoverflow_0074146651_loops_python_string.txt |
Q:
Is there a way to do Type Hinting for List Indices in Python?
I'm really enjoying python types, but can't seem to figure out how you might type a list with known length and indices.
Let's say for working with bounding boxes (which contain a lot of information) we want to just store data in a list to reduce the siz... | Is there a way to do Type Hinting for List Indices in Python? | I'm really enjoying python types, but can't seem to figure out how you might type a list with known length and indices.
Let's say for working with bounding boxes (which contain a lot of information) we want to just store data in a list to reduce the size of the data structure... (as compared to storing in a dict)
For e... | [
"Lists are generally meant to be variable-size and homogeneous. What you're describing (fixed length, heterogeneous) is more like a tuple, or, since the fields are labelled, a NamedTuple or dataclass, but, where your data is 2D, a Pandas DataFrame might make more sense. For example:\nimport pandas as pd\n\ndf = pd.... | [
3,
0
] | [] | [] | [
"python",
"python_typing"
] | stackoverflow_0074146457_python_python_typing.txt |
Q:
calculate relative frequency by personId
I've got data with columns: date, personId, label (True/False)
date personId label
-----------------------------
2022-07-20 1023 False
2022-07-30 1023 False
2022-08-05 1023 True
2022-09-11 1001 False
...
some rows may have zero Tru... | calculate relative frequency by personId | I've got data with columns: date, personId, label (True/False)
date personId label
-----------------------------
2022-07-20 1023 False
2022-07-30 1023 False
2022-08-05 1023 True
2022-09-11 1001 False
...
some rows may have zero True labels, some have zero False labels.
need to... | [
"This does it, using pandas .groupby, then post-processing those counts.\nfrom collections import defaultdict\nimport pandas as pd\n\ndata = [\n ['2022-07-20', 1, False],\n ['2022-07-22', 2, False],\n ['2022-07-24', 1, True],\n ['2022-08-02', 2, False],\n ['2022-08-04', 1, False],\n ['2022-08-06',... | [
0
] | [] | [] | [
"count",
"dataframe",
"frequency",
"python"
] | stackoverflow_0074146769_count_dataframe_frequency_python.txt |
Q:
Django aggregation. How to render its value into the template?
I have came across on one of the weirdest problem which I literally can't understand. Well I was following This, but nothing helped.
As the question says, I just want to render the result into the template. Below is my code.
Views.py
...
invoice ... | Django aggregation. How to render its value into the template? | I have came across on one of the weirdest problem which I literally can't understand. Well I was following This, but nothing helped.
As the question says, I just want to render the result into the template. Below is my code.
Views.py
...
invoice = lead.invoice_set.all()
total_invoice = invoice.aggregate(total... | [
"If you aggregate, you obtain a dictionary. Indeed, you see:\n{'total': 70000}\n\nYou can access the value that corresponds to a key by using {{ variable_name.key }} in the Django template.\nSo if you pass it with:\n …\n total_invoice = invoice.aggregate(total_invoice=Sum('amount'))\n …\n render(request... | [
1,
0
] | [] | [] | [
"django",
"django_aggregation",
"django_templates",
"python"
] | stackoverflow_0060468057_django_django_aggregation_django_templates_python.txt |
Q:
Gaussian fitting of a sharply peaked curve
I have data points distributed in this manner:
Now, I want to fit a smooth Gaussian over it. Can anyone tell me what would be the best way to fit a smooth Gaussian for these data points
A:
There can't be. It is obviously not a gaussian at all.
You have to find another m... | Gaussian fitting of a sharply peaked curve | I have data points distributed in this manner:
Now, I want to fit a smooth Gaussian over it. Can anyone tell me what would be the best way to fit a smooth Gaussian for these data points
| [
"There can't be. It is obviously not a gaussian at all.\nYou have to find another model. For example, a constant + a gaussian.\nIn that case, you could, for example, imitate Gaussian fit for Python . Except that in this example, the model is a Gaussian, when in your case it is not.\nSo what you want to fit with cur... | [
0
] | [] | [] | [
"curve_fitting",
"gaussian",
"python",
"sharp"
] | stackoverflow_0074146895_curve_fitting_gaussian_python_sharp.txt |
Q:
List that shows which element has the largest value
I am trying to make a function that will take elements and values input by the user, and list whichever element has the highest value. For example,
['H', 14.5, 'Be', 2.5, 'C', 50.5, 'O', 22.5 'Mg', 4.0, 'Si', 6.0]
the correct answer is 'C'. I can't seem to figur... | List that shows which element has the largest value | I am trying to make a function that will take elements and values input by the user, and list whichever element has the highest value. For example,
['H', 14.5, 'Be', 2.5, 'C', 50.5, 'O', 22.5 'Mg', 4.0, 'Si', 6.0]
the correct answer is 'C'. I can't seem to figure out how to get this to work. I don't have any code yet,... | [
"You can zip the list with itself to get alternating tuples. If you put the number first, you can just use max() to get the largest. This assumes there are not ties:\nl = ['H', 14.5, 'Be', 2.5, 'C', 50.5, 'O', 22.5, 'Mg', 4.0, 'Si', 6.0]\nnum, symbol = max(zip(l[1::2], l[::2]))\n# (50.5, 'C')\n\nThis works because ... | [
3,
2,
2,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074144594_list_python_python_3.x.txt |
Q:
Finding a float number in a range
I am checking conditions of time range from a csv file. There are around 20,000 rows of file and I would like to check if a given time is between start and end time. The csv contains columns such as time_check, time_window_start and time_window_end with time given as float values.... | Finding a float number in a range | I am checking conditions of time range from a csv file. There are around 20,000 rows of file and I would like to check if a given time is between start and end time. The csv contains columns such as time_check, time_window_start and time_window_end with time given as float values. It looks something like below:
tim... | [
"You should change your code to this\ndf1 = df1[((df1.time_check > df1.time_window_start) & (df1.time_check < df1.time_window_end))]\n\n"
] | [
1
] | [] | [] | [
"python",
"typeerror"
] | stackoverflow_0074147003_python_typeerror.txt |
Q:
Can a Python function have multiple return types?
Is it possible for a Python function to return different types depending on the if-else case?
def return_different() -> [String, List]:
a = random.randint(1, 10)
if a%2 == 0:
return []
else:
return "odd"
So in one case, it could r... | Can a Python function have multiple return types? | Is it possible for a Python function to return different types depending on the if-else case?
def return_different() -> [String, List]:
a = random.randint(1, 10)
if a%2 == 0:
return []
else:
return "odd"
So in one case, it could return a String, or in another, it could return a List.... | [
"Yes, you want a Union type:\ndef return_different() -> Union[str, List]:\n\n# Or in Python 3.10+\n\ndef return_different() -> str | list:\n\nI would reconsider this function though. Returning different types without proper thought makes your caller's life more difficult since strings and lists don't have a lot of ... | [
2
] | [
"Yes, you not must to declare on the return type and then you can return what you want.\n",
"In Python, there are no types, so you can return whatever you want. That means you can return more than one type of thing; e.g in your example above sometimes a list is returned, other times a string is returned. The func... | [
-2,
-2
] | [
"python",
"return_type",
"signature",
"types"
] | stackoverflow_0074147044_python_return_type_signature_types.txt |
Q:
OpenCV - Creating a video from a set of images in a directory
I am trying to create a video from a sequence of images. Below is my code.
import os
import cv2
mean_width = 6000
mean_height = 4000
def generate_video():
image_folder = 'C:/New folder/Images/q/'
video_name = 'myvideo.avi'
os.chdir("C:/New... | OpenCV - Creating a video from a set of images in a directory | I am trying to create a video from a sequence of images. Below is my code.
import os
import cv2
mean_width = 6000
mean_height = 4000
def generate_video():
image_folder = 'C:/New folder/Images/q/'
video_name = 'myvideo.avi'
os.chdir("C:/New folder/Images/q/")
images = [img for img in os.listdir(image_... | [
"To make a video you need your images to have the same resolution. If some images have different sizes cv2.VideoWriter quietly skips them without any errors.\nSo you may need to resize your images to fixed size:\nfor image in images:\n image = cv2.imread(os.path.join(image_folder, image))\n image = cv2.resize... | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074145827_opencv_python.txt |
Q:
How to replace a classic for loop with df.iterrows()?
I have a huge data frame.
I am using a for loop in the below sample code:
for i in range(1, len(df_A2C), 1):
A2C_TT= df_A2C.loc[(df_A2C['TO_ID'] == i)].sort_values('DURATION_H').head(1)
if A2C_TT.size > 0:
print (A2C_TT)
This is working fine bu... | How to replace a classic for loop with df.iterrows()? | I have a huge data frame.
I am using a for loop in the below sample code:
for i in range(1, len(df_A2C), 1):
A2C_TT= df_A2C.loc[(df_A2C['TO_ID'] == i)].sort_values('DURATION_H').head(1)
if A2C_TT.size > 0:
print (A2C_TT)
This is working fine but I want to use df.iterrows() since it will help me to auto... | [
"As far as I understand your question, you want to group your data by To_ID and select the row where Duration_H is the smallest? Is that right?\ndf.loc[df.groupby('TO_ID').DURATION_H.idxmin()]\n \n\n",
"here is one way about it\n# run the loop for as many unique TO_ID you have\n# instead of iterrows, which runs f... | [
3,
2
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074146842_dataframe_jupyter_notebook_pandas_python_python_3.x.txt |
Q:
Python Nested loops: printed seats
Given rows and cols, print a list of all seats in a theater. Rows are numbered, columns lettered, as in 1A or 3E. Print a space after each seat, including after the last.
Ex: num_rows = 2 and num_cols = 3 prints:
1A 1B 1C 2A 2B 2C
num_rows = 2
num_cols = 3
c1 = 1
while c1 <= num... | Python Nested loops: printed seats | Given rows and cols, print a list of all seats in a theater. Rows are numbered, columns lettered, as in 1A or 3E. Print a space after each seat, including after the last.
Ex: num_rows = 2 and num_cols = 3 prints:
1A 1B 1C 2A 2B 2C
num_rows = 2
num_cols = 3
c1 = 1
while c1 <= num_rows:
c2 = 'A'
while c2 <= 'C':... | [
"\"\"\" c2 = 'A'\nwhile c2 <= 'C':\"\"\"\n\nI think the problem is here. Counting the alphabet would need an assigned value like you have 'C' but if you wanted to iterate through the alphabet with more or less columns you would need to assign a number to the maximum instead of the character. (The uppercase alpha... | [
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"s1 = 1\nwhile s1 <= num_rows and num_cols != 0:\n s2 = 'A'\n while s2 <= 'C':\n print('%s%s' % (s1,s2), end = ' ')\n s2 = chr(ord(s2) + 1)\ns1 += 1\n\nprint()\n"
] | [
-3
] | [
"python"
] | stackoverflow_0052640648_python.txt |
Q:
python random choice against multiple lists
I'm having trouble explaining this so please bare with me.
I have several lists and I want to write a python script that picks an item at random from the first list, then checks that result against a "fail list," if the item isn't on the "fail list" I want to move to the... | python random choice against multiple lists | I'm having trouble explaining this so please bare with me.
I have several lists and I want to write a python script that picks an item at random from the first list, then checks that result against a "fail list," if the item isn't on the "fail list" I want to move to the next list and do the same thing until it fails.
... | [
"Put all your choices into a list, then loop through them testing if it's in the fail list.\nfor listname, choice in [('action_heros', rand_action_hero), ('friends', rand_friend), ('himym', rand_himym)]: \n if choice in simpsons:\n print(f'failed at {listname}')\n break\nelse:\n print('All tests... | [
1,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074146945_python.txt |
Q:
from file1.py import function, how to remove the code unexpected?
I have two files: file1.py and file2.py
file1.py
print("34343433")
def print_hello():
print("Hello")
file2.py
from file1 import print_hello
print_hello()
the output of file2 is:
34343433
Hello
I just want to have it print only the "Hello" p... | from file1.py import function, how to remove the code unexpected? | I have two files: file1.py and file2.py
file1.py
print("34343433")
def print_hello():
print("Hello")
file2.py
from file1 import print_hello
print_hello()
the output of file2 is:
34343433
Hello
I just want to have it print only the "Hello" portion.
| [
"When you import a file in Python, all code in the file is run (even in partial imports), including the print statement you had. To remove the extra numbers, you have two options:\n1: Remove the code\n#file1.py\ndef print_hello():\n print(\"Hello\")\n\n2: Put it into its own function\n#file1.py\ndef print_nums()... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074147112_python.txt |
Q:
Creating a network using classes for defining nodes
I am having some issues trying to use class objects as nodes in a graph.
I am creating two classes of agents that I would like to use as nodes in a random graph (e.g. Erdos Renyi).
class man(Agent):
def __init__(self):
self.m = np.ran... | Creating a network using classes for defining nodes | I am having some issues trying to use class objects as nodes in a graph.
I am creating two classes of agents that I would like to use as nodes in a random graph (e.g. Erdos Renyi).
class man(Agent):
def __init__(self):
self.m = np.random.normal(0.5, 0.1)
self.n= np.random.normal... | [
"Your class man doesn't take any arguments and you're passing self and i+1\n# Create nodes man\n for i, node in enumerate(self.G.nodes()):\n a1 = man()\n self.schedule.add(a1)\n self.grid.place_agent(a1, node)\n\n"
] | [
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0074147065_networkx_python.txt |
Q:
y should be a 1d array, got an array of shape (2603, 2) instead
import numpy as np
import pandas as pd
import matplotlib
import xgboost as xgb
from sklearn.metrics import roc_auc_score
from xgboost.sklearn import XGBClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFo... | y should be a 1d array, got an array of shape (2603, 2) instead | import numpy as np
import pandas as pd
import matplotlib
import xgboost as xgb
from sklearn.metrics import roc_auc_score
from xgboost.sklearn import XGBClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold
train = pd.read_csv("train_final.csv")
y = train['Y']
YValues = [... | [
"You have to convert it to an array. Pandas essentially creates a container around your data. Try:\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport xgboost as xgb\nfrom sklearn.metrics import roc_auc_score\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.model_selection import GridSearchC... | [
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0074140220_python_scikit_learn.txt |
Q:
failed pip install mysqlclient on ubuntu 20.04 with python 3.10
I am trying to install mysqlclient with pip but it keeps giving me error message,
I already have the development from sudo apt-get install python3-dev default-libmysqlclient-dev build-essential,
or use this step :
LDFLAGS=-L/usr/local/opt/openssl/lib ... | failed pip install mysqlclient on ubuntu 20.04 with python 3.10 | I am trying to install mysqlclient with pip but it keeps giving me error message,
I already have the development from sudo apt-get install python3-dev default-libmysqlclient-dev build-essential,
or use this step :
LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysqlclient, and this sudo apt-get install libmariadb-dev... | [
"I've just encountered the same problem, getting error messages when installing mysqlclient using pip. After some searches, I found this blog post. Following the blog post, we need to install several libraries:\nsudo apt-get install python3.10-dev\nsudo apt-get install mysql-client\nsudo apt-get install libmysqlcli... | [
3
] | [] | [] | [
"mysql",
"pip",
"python",
"python_wheel",
"ubuntu_20.04"
] | stackoverflow_0072209870_mysql_pip_python_python_wheel_ubuntu_20.04.txt |
Q:
How can I select a data in python DataFrame (table) that depends on three column(variable)?
At first from a table (Data frame) I find the ID, Frame Type and Frame material (Aluminum and wood). Then I want to come to this data frame and write a function to find the corresponding value.
For example, from the first d... | How can I select a data in python DataFrame (table) that depends on three column(variable)? | At first from a table (Data frame) I find the ID, Frame Type and Frame material (Aluminum and wood). Then I want to come to this data frame and write a function to find the corresponding value.
For example, from the first data frame I understand that: ID = 1c , Frame_type = fixed and Frame material = aluminum.
but I do... | [
"If you want to find rows by three values, you can use this construction\ndf = df[((df.ID == x1) & (df.Frame_type == x2) & (df.Aluminum == x3))]\n\nIf this isn't a solution, can you clarify the question?\n"
] | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074147113_dataframe_python.txt |
Q:
GridSearchCV best_score_ is nan when using StratifiedGroupKFold
ever since switching my kfold from StratifiedKFold to StratifiedGroupKFold I have the issue that grid.best_score returns nan, while it worked fine before. My code looks like this:
kfold = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=0)
... | GridSearchCV best_score_ is nan when using StratifiedGroupKFold | ever since switching my kfold from StratifiedKFold to StratifiedGroupKFold I have the issue that grid.best_score returns nan, while it worked fine before. My code looks like this:
kfold = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=0)
train_indx, test_indx = next(GroupShuffleSplit(random_state=i, test_... | [
"To have correct results StratifiedGroupKFold may expects groups to be specified. But you do not provide groups. You can pass the groups using two ways:\n\nWhen calling grid.fit:\n\ngrid.fit(X_train, Y_train, groups=groups)\n\n\nOr pass the iterable of (train, val) indices as a splitter:\n\nkfold = StratifiedGroupK... | [
1
] | [] | [] | [
"cross_validation",
"gridsearchcv",
"python",
"scikit_learn"
] | stackoverflow_0074147052_cross_validation_gridsearchcv_python_scikit_learn.txt |
Q:
Pandas Find Max High with variable length when condition met
I have a pandas dataframe of close to 1 million records with columns including the cond1, height, distance (which is the number of rows forward). What I would like to do is iterate over the dataframe and when the cond1 = True get the maximum height from... | Pandas Find Max High with variable length when condition met | I have a pandas dataframe of close to 1 million records with columns including the cond1, height, distance (which is the number of rows forward). What I would like to do is iterate over the dataframe and when the cond1 = True get the maximum height from the current index + 1 to the number of rows as per the distance c... | [
"You can try defining a custom window, where you will be able to set the step of the window each time:\nimport pandas as pd\nimport numpy as np\nfrom pandas.api.indexers import BaseIndexer\n\nclass CustomIndexer(BaseIndexer):\n\n def get_window_bounds(self, num_values, min_periods, center, closed):\n \n ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"vectorization"
] | stackoverflow_0074146902_dataframe_pandas_python_vectorization.txt |
Q:
finding href path value Python regex
Find all the url links in a html text using regex Arguments. below text assigned to html vaiable.
html = """
<a href="#fragment-only">anchor link</a>
<a id="some-id" href="/relative/path#fragment">relative link</a>
<a href="//other.host/same-protocol">same-protocol link</a>
<a ... | finding href path value Python regex | Find all the url links in a html text using regex Arguments. below text assigned to html vaiable.
html = """
<a href="#fragment-only">anchor link</a>
<a id="some-id" href="/relative/path#fragment">relative link</a>
<a href="//other.host/same-protocol">same-protocol link</a>
<a href="https://example.com">absolute URL</a... | [
"You could try using positive lookbehind to find the quoted strings in front of href= in html\npattern = re.compile(r'(?<=href=\\\")(?!#)(.+?)(?=#|\\\")')\nurls = re.findall(pattern, html)\n\nSee this answer for more on how matching only up to the '#' character works, and here if you want a breakdown of the RegEx o... | [
1,
1
] | [] | [] | [
"python",
"python_re",
"regex"
] | stackoverflow_0074144436_python_python_re_regex.txt |
Q:
How to return ordinary variables from scipy odeint?
I have an R code, solving an ordinary differential equation using ode function from DeSolve package.
f <- function(t, y, parms) {
with(as.list(c(y, parms)),{
rate <- M * A/(A + K) * A
dA <- -rate + D * (IN - A)
dB <- rate - D * B
Total... | How to return ordinary variables from scipy odeint? | I have an R code, solving an ordinary differential equation using ode function from DeSolve package.
f <- function(t, y, parms) {
with(as.list(c(y, parms)),{
rate <- M * A/(A + K) * A
dA <- -rate + D * (IN - A)
dB <- rate - D * B
Total <- A + B
Conserved<- dA + dB - D * (IN - A) + D... | [
"Python's odeint does not support the output of internal variables directly, but it is possible to emulate the behavior.\nPython\nFirst create a function f2 with all desired variables. For sake of simplicity, let's also output time t and both the derivatives dA, dB and the states A, B:\nimport numpy as np\nimport s... | [
1
] | [] | [] | [
"ode",
"python",
"r",
"scipy"
] | stackoverflow_0074143515_ode_python_r_scipy.txt |
Q:
How to pass data from a stream server in Python back into the main task?
I've adapted this TCP echo server with streams example to my needs so that I can have multiple clients send data to my device:
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode(... | How to pass data from a stream server in Python back into the main task? | I've adapted this TCP echo server with streams example to my needs so that I can have multiple clients send data to my device:
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!... | [
"First: the fact that no asyncio loop is running when module level code is executed does not block the creation of an asyncio.Queue instance - just do it, if you want to use asyncio.Queue s at all: but any data structure will work for you, and maybe using a collections.deque, which is synchronous, will require less... | [
1
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074142601_python_python_asyncio.txt |
Q:
Python Homework - Inventory program with nested dictionaries
Not sure if anyone can help. This is my first class so I'm very new to python and programming in general. I have a program for my Python class that I am stuck on. I have it doing the basics, but cannot figure out how to check the inventory quantity again... | Python Homework - Inventory program with nested dictionaries | Not sure if anyone can help. This is my first class so I'm very new to python and programming in general. I have a program for my Python class that I am stuck on. I have it doing the basics, but cannot figure out how to check the inventory quantity against the user inputted quantity. I know the nested if statement is i... | [
"The error I see is in the line\nif quantity_input >= new_data['sprocket']['quantity']:\n print(\"Error, only\" + new_data['sprocket']['quantity'] + part_input + \" \n are available!\")\n\n\nReplace the first key with part_input\nThis should be more like this\nif quantity_input >= new_... | [
2,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074146712_dictionary_python.txt |
Q:
I need help comparing data within a table in python
I have the following table
a1b1
a1Eb1
a1b2
a1Eb2
a2b1
a2Eb1
a2b2
a2Eb2
a3b1
a3Eb1
a3b2
a3Eb2
2
20
8
54
3
56
3
67
2
78
7
75
8
30
6
67
6
35
4
56
3
85
6
74
5
54
4
64
7
23
6
48
4
67
4
82
6
65
7
53
8
27
7
35
5
25
3
64
4
34
2
52
4
28
8
27
6
94
2
29
i want to com... | I need help comparing data within a table in python | I have the following table
a1b1
a1Eb1
a1b2
a1Eb2
a2b1
a2Eb1
a2b2
a2Eb2
a3b1
a3Eb1
a3b2
a3Eb2
2
20
8
54
3
56
3
67
2
78
7
75
8
30
6
67
6
35
4
56
3
85
6
74
5
54
4
64
7
23
6
48
4
67
4
82
6
65
7
53
8
27
7
35
5
25
3
64
4
34
2
52
4
28
8
27
6
94
2
29
i want to compare the following data:
a1b1 vs a1b2;
then ... | [
"If you want to display only specific columns of your dataframe you can use the following syntax with [[ and ]] after the name of the dataframe (df), and in between you just add the names of the columns you want to see. It can be 2,\n3 or even all of the columns of the dataframes, as long as you separate their name... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074147156_pandas_python.txt |
Q:
Python subarray from dataclass array
i Have th following dataclass
@dataclass
class Cell:
electric_field: np.double=0
boarder_left: np.double=0
boarder_right: np.double=0
i do an array of it like this. by the way is this the best way?
Cell_Array = []
for i in range(cnt):
cell=Cell()
Cell_Array.append... | Python subarray from dataclass array | i Have th following dataclass
@dataclass
class Cell:
electric_field: np.double=0
boarder_left: np.double=0
boarder_right: np.double=0
i do an array of it like this. by the way is this the best way?
Cell_Array = []
for i in range(cnt):
cell=Cell()
Cell_Array.append(cell)
now i would like to have an array ... | [
"If you want an array of electric_field attributes from all the instances you can do this:\nall_electric_fields = []\nfor cell in Cell_Array:\n all_electric_fields.append(cell.electric_fields)\n\n"
] | [
0
] | [] | [] | [
"arrays",
"python",
"python_dataclasses"
] | stackoverflow_0074108450_arrays_python_python_dataclasses.txt |
Q:
Adafruit-PlatformDetect unable to detect board
Im trying to import board on a feather m4 expressx and getting the following error. Ive run the command it promoted me to do below and nothing changed. All libraries and software is updated. Im still getting the following error
NotImplementedError: Adafruit-Platfo... | Adafruit-PlatformDetect unable to detect board | Im trying to import board on a feather m4 expressx and getting the following error. Ive run the command it promoted me to do below and nothing changed. All libraries and software is updated. Im still getting the following error
NotImplementedError: Adafruit-PlatformDetect version 3.26.0 was unable to identify the b... | [
"Please try this but be aware that I can't test any of it as I don't have the hardware available.\n\nexecute this command in your cli: cat /proc/cpuinfo\ntry to find this file (your path might be a bit different.):\n/usr/local/lib/python3.9/dist-packages/adafruit_platformdetect/constants/boards.py\n\nThe output of ... | [
0
] | [] | [] | [
"adafruit",
"platform_detection",
"python"
] | stackoverflow_0073102231_adafruit_platform_detection_python.txt |
Q:
How to insert list into nested list in python?
Right now I am practicing List
I am facing a problem of inserting nested list.
for instance; I have a nested list and i want to make another nested.
example
a = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]
output should be:
output = [['a'[1,2],[2,3]], ['b'[3]... | How to insert list into nested list in python? | Right now I am practicing List
I am facing a problem of inserting nested list.
for instance; I have a nested list and i want to make another nested.
example
a = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]
output should be:
output = [['a'[1,2],[2,3]], ['b'[3],[4]], ['c'[4],[5]]]
| [
"Use a dictionary to collect all the sublists with the same string.\nfrom collections import defaultdict\n\na = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]\noutput_dict = defaultdict(lambda: [[], []])\n\nfor num1, key, num2 in a:\n output_dict[key][0].append(num1)\n output_dict[key][1].append(num2)\n... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074147262_python.txt |
Q:
Pygame dice roller
I'd like to have the dice roll, and then player 1 move forward as many spaces as the dice rolls on. Currently, this is the starting code with the grid and the squares along with the numbers.
import pygame
import random
w_in_squares = 7
h_in_squares = 6
square_dim = 50
blue = (47,134,150)
w... | Pygame dice roller | I'd like to have the dice roll, and then player 1 move forward as many spaces as the dice rolls on. Currently, this is the starting code with the grid and the squares along with the numbers.
import pygame
import random
w_in_squares = 7
h_in_squares = 6
square_dim = 50
blue = (47,134,150)
white = (255, 255, 255)
b... | [
"It's not really clear what you need here, the code does not do what's described. So I've re-arranged it, moved some code into a function, and \"made it work\" somewhat.\nSo, to address the changes:\n\nAll constants to be named in capitals. This is a very common convention in programming.\n\nI pushed them all to ... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074132944_pygame_python.txt |
Q:
Geopandas geometry to lat/long
df = gpd.read_file('/content/buildings.geojson')
df has a 'geometry' column with values like POINT (-12635143.897 7083229.283)
Reference image:
I have to change all the rows containing Point values to Latitude and Longitude (WGS84 coordinate system (i.e. EPSG=4326))
What's the best... | Geopandas geometry to lat/long | df = gpd.read_file('/content/buildings.geojson')
df has a 'geometry' column with values like POINT (-12635143.897 7083229.283)
Reference image:
I have to change all the rows containing Point values to Latitude and Longitude (WGS84 coordinate system (i.e. EPSG=4326))
What's the best code for this?
| [
"I am not sure what CRS the data currently is, thus if you need to re-project the points. But to get latitude and longitude, try this:\ndf[\"lat\"]=df['geometry'].y\ndf[\"lon]=df['geometry'].x\n\n"
] | [
0
] | [] | [] | [
"geometry",
"geopandas",
"pandas",
"python"
] | stackoverflow_0074147335_geometry_geopandas_pandas_python.txt |
Q:
Convert a duplicated list into a combined one with same key
I have a list: and this list could be very long duplicated of the values can vary because of it.
l1 = [[{'node': 'node-3', 'value': 7.5456592756413645},{'node': 'node-5', 'value': 6.988051860579239},{'node': 'node-0', 'value': 11.394453190010722},{'node':... | Convert a duplicated list into a combined one with same key | I have a list: and this list could be very long duplicated of the values can vary because of it.
l1 = [[{'node': 'node-3', 'value': 7.5456592756413645},{'node': 'node-5', 'value': 6.988051860579239},{'node': 'node-0', 'value': 11.394453190010722},{'node': 'node-7', 'value': 7.905077155911794}, {'node': 'node-4', 'value... | [
"You may achieve this, with varying length N of values, with the following:\nl2 = [{'nodes': l1[0][i]['node'], 'value': [l1[n][i]['value'] for n in range(len(l1))]} for i in range(len(l1[0]))]\n\nSomething to note, the original post requested for 'value'. This was maintained to meet the original request, but I woul... | [
2,
1
] | [] | [] | [
"dictionary",
"list",
"python",
"python_3.x"
] | stackoverflow_0074147320_dictionary_list_python_python_3.x.txt |
Q:
How to count combinations contained in a Pandas dataframe column
I have a Pandas dataframe that looks like this:
data = {
'start' : ['ABC', 'DEF', 'MNO', 'PQR', 'MNO', 'MNO', 'STU'],
'end' : ['MNO', 'FGI', 'ABC', 'STU', 'DEF', 'ABC', 'PQR']
}
df = pd.DataFrame(data)
Then, I enrich it by ... | How to count combinations contained in a Pandas dataframe column | I have a Pandas dataframe that looks like this:
data = {
'start' : ['ABC', 'DEF', 'MNO', 'PQR', 'MNO', 'MNO', 'STU'],
'end' : ['MNO', 'FGI', 'ABC', 'STU', 'DEF', 'ABC', 'PQR']
}
df = pd.DataFrame(data)
Then, I enrich it by adding a routing column based on the two original columns:
df['routing... | [
"df['routing'].str.split('<>', expand=True).apply(lambda x: '<>'.join(sorted(x)), axis=1).value_counts()\n\n\nABC<>MNO 3\nPQR<>STU 2\nDEF<>FGI 1\nDEF<>MNO 1\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074147344_pandas_python.txt |
Q:
I want to extract article text and article title from list of URL's
I need help with the use of BeautifulSoup. How do I extract article text and article title from a list of URLs? Here is my current state of the code::
for i in range(0,len(df)):
j = df.iloc[i].values
headers = {'User-Agent':'Mozilla/5.0 (... | I want to extract article text and article title from list of URL's | I need help with the use of BeautifulSoup. How do I extract article text and article title from a list of URLs? Here is my current state of the code::
for i in range(0,len(df)):
j = df.iloc[i].values
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrom... | [
"You need to add some checks and error handling in your code.\nfor i in range(0,len(df)):\n j = df.iloc[i].values\n headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'}\n page = requests.get(j[0],headers = headers)#loadin... | [
0
] | [] | [] | [
"beautifulsoup",
"pandas",
"python"
] | stackoverflow_0074136255_beautifulsoup_pandas_python.txt |
Q:
How to modify every third element in matrix?
I had to make a matrix using numpy.array method. How can I now update every third element of my matrix? I have made a for loop for the problem but that is not the optimal solution. Is there a way to avoid loops? For example if I have this matrix:
matrix = np.array([[1,2... | How to modify every third element in matrix? | I had to make a matrix using numpy.array method. How can I now update every third element of my matrix? I have made a for loop for the problem but that is not the optimal solution. Is there a way to avoid loops? For example if I have this matrix:
matrix = np.array([[1,2,3,4],
[5,6,7,8],
... | [
"Solution:\nmatrix = np.ascontiguousarray(matrix)\nmatrix.ravel()[::3] += 1\n\nWhy does the ascontiguousarray is needed? Because matrix may not be c-contiguous (for example matrix may have fortran-order - column major). It that case ravel returns a copy instead of a view so a simple inplace operation matrix.ravel()... | [
1
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0074142995_matrix_numpy_python.txt |
Q:
Why is code printing "invalid literal for int() with base 10:" when running through mcdonalds and what does it mean?
When I run my code, it does not error out until it gets to the random.randint part of the code. I tried removing the mcdonalds part but the 2nd part does not work either. I have done this before wit... | Why is code printing "invalid literal for int() with base 10:" when running through mcdonalds and what does it mean? | When I run my code, it does not error out until it gets to the random.randint part of the code. I tried removing the mcdonalds part but the 2nd part does not work either. I have done this before with other programs but it errors out now, why?.
import time
one = "mcdonalds"
two = "burger_king"
three = "culvers"
four = "... | [
"You are trying to convert the string \"mcdonalds\" to a number. This can't be done. Instead use a list and random.choice. Here is your code with the applied changes:\nimport time\nimport random\nrestaurants = [\"McDonalds\",\"Burger King\",\"Culvers\",\"Little Ceasers\",\"Panda Express\",\"Taco Bell\"]#List of all... | [
1
] | [] | [] | [
"python",
"read_eval_print_loop"
] | stackoverflow_0074147490_python_read_eval_print_loop.txt |
Q:
Failing: Performing addition to a data frame and storing it in a data frame
I am trying to add some constant values to a data frame.
I have successfully done multiplication, but now addition does not work.
This works:
df_C2H_TT_y1['DURATION_H'] = df_C2H_TT_y1['DURATION_H'] * 0.95
This does not work:
TT_Base = pd.... | Failing: Performing addition to a data frame and storing it in a data frame | I am trying to add some constant values to a data frame.
I have successfully done multiplication, but now addition does not work.
This works:
df_C2H_TT_y1['DURATION_H'] = df_C2H_TT_y1['DURATION_H'] * 0.95
This does not work:
TT_Base = pd.DataFrame
TT_Base["TT"] = (0.05 + A2C_TT_x2['DURATION_H']) + 0.25 + df_C2H_TT_y1[... | [
"You need to create a dataframe by adding parenthesis:\nTT_Base = pd.DataFrame()\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074147516_dataframe_jupyter_notebook_pandas_python_python_3.x.txt |
Q:
checking for a name inside an object
Struggling to figure out how to check that a name, given as an argument, exists within a larger name. Have tried with .split() but only get assertionerror all the time.
def __init__(self, artist, title):
self._artist = artist
self._title = title
def check_artist(... | checking for a name inside an object | Struggling to figure out how to check that a name, given as an argument, exists within a larger name. Have tried with .split() but only get assertionerror all the time.
def __init__(self, artist, title):
self._artist = artist
self._title = title
def check_artist(self, name):
if name in self._art... | [
"From the documentation on assert, assert as you are using it is basically equivalent to:\nif not <expression>: raise AssertionError\n\nYour code is actually functioning as expected, as \"Lord Gaga\" is not in the artist name. A better use of assert here would be:\nassert not song1.check_artist(\"Lord Gaga\")\nasse... | [
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074142996_class_python.txt |
Q:
Attempting to use PyInstaller with Selenium and Pandas
I'm attempting to create an application that can search for items on a website the user provides. I want the application to be able to run by non-Python users. I attempted to use PyInstaller with the following code. It ran successfully but upon attempting t... | Attempting to use PyInstaller with Selenium and Pandas | I'm attempting to create an application that can search for items on a website the user provides. I want the application to be able to run by non-Python users. I attempted to use PyInstaller with the following code. It ran successfully but upon attempting to get the application to run, the error on the bottom return... | [
"try this:\n!pyinstaller ./test.py --onefile --collect-data selenium --add-binary \"./driver/chromedriver.exe;./driver\"\nfound here: Error while executing my .exe made with pyinstaller\n"
] | [
0
] | [] | [] | [
"pandas",
"pyinstaller",
"python",
"selenium",
"webdriver"
] | stackoverflow_0073873472_pandas_pyinstaller_python_selenium_webdriver.txt |
Q:
How to check if a certain char is in a list/tuple in Python?
Beginner here. I am making a simple hangman game that can take up to 6 wrong guesses from the player. As long as they guess right, they can continue playing as many turns as necessary. There is no end behavior, I am just working on getting the input and ... | How to check if a certain char is in a list/tuple in Python? | Beginner here. I am making a simple hangman game that can take up to 6 wrong guesses from the player. As long as they guess right, they can continue playing as many turns as necessary. There is no end behavior, I am just working on getting the input and having the program respond to it properly. My code below:
word_lis... | [
"in is the correct solution, you were just never giving it valid data to check for. You didn't return from get_guess, so it always returns None (thus, guess was always None and None was never in the list). Similarly, you didn't assign to guess on subsequent calls, so even if you had returned a value, guess wouldn't... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0074147558_python.txt |
Q:
scipy.stats.multivariable_norm.pdf: "The input matrix must be symmetric positive semidefinite."
So I have the following code below.
L = np.array([1,2,3])
M = np.array([1,2,3])
Q = np.random.uniform(0,10,size=(3,3))
S = Q.T*Q
print(sp.stats.multivariate_normal.pdf(L,M,S))
Clearly S is a symmetric positive semidefi... | scipy.stats.multivariable_norm.pdf: "The input matrix must be symmetric positive semidefinite." | So I have the following code below.
L = np.array([1,2,3])
M = np.array([1,2,3])
Q = np.random.uniform(0,10,size=(3,3))
S = Q.T*Q
print(sp.stats.multivariate_normal.pdf(L,M,S))
Clearly S is a symmetric positive semidefinite matrix. I can prove it using linear algebra theory. However, scipy complains that it isn't when ... | [
"Like the comment by Mechanic Pig says, replace * (element-wise multiplication on Numpy arrays) with @.\nimport scipy as sp\nimport numpy as np\n\nL = np.array([1, 2, 3])\nM = np.array([1, 2, 3])\nQ = np.random.uniform(0, 10, size=(3, 3))\nS = Q.T @ Q\nprint(sp.stats.multivariate_normal.pdf(L, M, S))\n\nprints, in ... | [
0
] | [] | [] | [
"linear_algebra",
"numpy",
"python",
"scipy",
"scipy.stats"
] | stackoverflow_0073983044_linear_algebra_numpy_python_scipy_scipy.stats.txt |
Q:
How can I fix my function on finding the determinant of an N by N matrix?
Here is my code:
def det(mat):
if len(mat) < 2 or len(mat[0]) < 2:
return None
else:
if len(mat) == 2 and len(mat[0]) == 2:
return ((mat[0][0] * mat[1][1])-(mat[0][1] * mat[1][0]))
elif len(mat) > ... | How can I fix my function on finding the determinant of an N by N matrix? | Here is my code:
def det(mat):
if len(mat) < 2 or len(mat[0]) < 2:
return None
else:
if len(mat) == 2 and len(mat[0]) == 2:
return ((mat[0][0] * mat[1][1])-(mat[0][1] * mat[1][0]))
elif len(mat) > 2 and len(mat[0]) > 2:
tot = 0
n = len(mat)
... | [
"The first iteration of the function recursively calls itself. Then the second iteration calls itself again. When it does so, it passes a value of [[1], [1]], and so it gets back None (because a 1x2 matrix has no determinant). It then tries to multiply that returned value by num, which leads to the error you are... | [
0
] | [] | [] | [
"matrix",
"python",
"recursion"
] | stackoverflow_0074147537_matrix_python_recursion.txt |
Q:
How to Write a Nested For Loop in One Line Python with File Url and File Name
data = json.dumps({'conf':{a:b for a in table_name for b in file_url}})
print(data)
I have 2 files in file_url.
sales_dy_20221022.csv
sales_wk_20221022
I have 2 table names in table_name
sales_dy
sales_wk
If I write the code like th... | How to Write a Nested For Loop in One Line Python with File Url and File Name | data = json.dumps({'conf':{a:b for a in table_name for b in file_url}})
print(data)
I have 2 files in file_url.
sales_dy_20221022.csv
sales_wk_20221022
I have 2 table names in table_name
sales_dy
sales_wk
If I write the code like the above I get the result below.
"conf": {
"sales_dy": "sales_dy_20221022.csv",
"sal... | [
"You are in the right path, use zip.\nex. data = json.dumps({'conf':{a:b for a,b in zip(table_name,file_url)}})\n"
] | [
1
] | [] | [] | [
"for_loop",
"if_statement",
"nested",
"python"
] | stackoverflow_0074147574_for_loop_if_statement_nested_python.txt |
Q:
Python/Pandas: Convert ByteStream into Pandas Dataframe with rows and columns
I have a bytestream that would like to read into the Python. I would like to use Pandas to hold the data. For example:
bytestream = '000102030404'
First I need to split the bytestream into different rows, with fixed size (2 bytes in thi... | Python/Pandas: Convert ByteStream into Pandas Dataframe with rows and columns | I have a bytestream that would like to read into the Python. I would like to use Pandas to hold the data. For example:
bytestream = '000102030404'
First I need to split the bytestream into different rows, with fixed size (2 bytes in this example).
bytestreamArray = ['0001', '0203', '0404']
Then I would like to split ... | [
"You could use regex to find the pattern:\nr'(\\d\\d)(\\d\\d)'\n\nThe (\\d\\d) looks for two digits, and assigns them to a group. I included the search for two groups to make it easier for what you were trying to do.\nI then use the output from the findall() function to generate a dataframe.\nHere is the code:\nimp... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074147597_pandas_python.txt |
Q:
Why is my data from my input field inputting all previous data input into my spreadsheet?
i am trying to get data from a text box to an excel document, i have this working but the only problem is that it adds the previous data submitted along with the data in the text box
Here is the get data code and the delete c... | Why is my data from my input field inputting all previous data input into my spreadsheet? | i am trying to get data from a text box to an excel document, i have this working but the only problem is that it adds the previous data submitted along with the data in the text box
Here is the get data code and the delete code I'm using.
def clear():
# clear the content of text entry box
name_field.delet... | [
"Put the value inside a variable 1st then from variable to cell. This way you can clear the variable for each prompt and not just clearing the text box\nname_field.delete(0, END)\nnameValue = None\nnameValue = name_field.get()\nsheet.cell(row=current_row + 1, column=3).value = nameValue\n\n"
] | [
0
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0074147371_excel_python.txt |
Q:
distinguish decimal and string columns in a pandas dataframe
I need to identify which columns in a dataframe are decimals and which are strings.
Using df.dtypes gives 'object' for both column types:
import pandas as pd
import decimal
data = {'dec1': [1.1, 1.2],'str1': ["a","b"]}
df = pd.DataFrame(data)
df.dec1 ... | distinguish decimal and string columns in a pandas dataframe | I need to identify which columns in a dataframe are decimals and which are strings.
Using df.dtypes gives 'object' for both column types:
import pandas as pd
import decimal
data = {'dec1': [1.1, 1.2],'str1': ["a","b"]}
df = pd.DataFrame(data)
df.dec1 = df.dec1.apply(lambda x: decimal.Decimal(x))
df.dtypes
I am us... | [
"Use isinstance, what should be more preferable like type, link:\nmask = df.iloc[0].map(lambda x: isinstance(x, decimal.Decimal))\ndf_decimals = df.loc[:,mask]\nprint (df_decimals)\n dec1\n0 1.10000000000000008881784197001252323389053344...\n1 1.199999999999999955591... | [
3,
1
] | [] | [] | [
"decimal",
"dtype",
"pandas",
"python",
"types"
] | stackoverflow_0061118320_decimal_dtype_pandas_python_types.txt |
Q:
querying class attributes when given the "name" of a class
I have a case where the "names" of classes of interest are available.
Is it possible, without creating an instance of the class, to check for the existing and value of Class attributes ?
E.g., I know that one can do this
class Universal:
answer = 42
a... | querying class attributes when given the "name" of a class | I have a case where the "names" of classes of interest are available.
Is it possible, without creating an instance of the class, to check for the existing and value of Class attributes ?
E.g., I know that one can do this
class Universal:
answer = 42
all_knowing_one_class = Universal
solution = 'answer'
unknown = '... | [
"You don't need to create a local mapping between name and class, because such a mapping already exists - locals(). The dynamic namespace lookup can be done with either getitem or getattr style access: it's getattr if you have the module instance itself, and getitem if you have the namespace (i.e. the module's __di... | [
0
] | [] | [] | [
"attributes",
"class",
"python"
] | stackoverflow_0074147648_attributes_class_python.txt |
Q:
python runtime warning debugging
I am trying to learn Python, and I am still a novice so please bear with me. I am using the Komodo IDE environment. I currently wish to debug a a runtime warning that says:
RuntimeWarning: invalid value encountered in greater & (matrixCsvOutput[:,8] > 30))[0] ,:]
Now, I wish to set... | python runtime warning debugging | I am trying to learn Python, and I am still a novice so please bear with me. I am using the Komodo IDE environment. I currently wish to debug a a runtime warning that says:
RuntimeWarning: invalid value encountered in greater & (matrixCsvOutput[:,8] > 30))[0] ,:]
Now, I wish to set a breakpoint that would allow me to e... | [
"before the line number mentioned in RuntimeWarning, add this:\nimport pdb ; pdb.set_trace()\n\n",
"You can run your script through pdb from the command line too:\npython -m pdb myscript.py\n\n(command taken from the pdb docs)\n",
"To anyone (but probably not novice) who concerns only debugging the runtime warn... | [
1,
1,
0
] | [] | [] | [
"debugging",
"komodo",
"python",
"runtime_error"
] | stackoverflow_0024468197_debugging_komodo_python_runtime_error.txt |
Q:
How to Filter CSV File using Pandas by Multiple Values
I am currently trying to filter one column in a CSV file by multiple values. For instance, I would like all of the data in the CSV file that is related to departments 104, 105, 106, etc. I have the code below, so far which works for each department individuall... | How to Filter CSV File using Pandas by Multiple Values | I am currently trying to filter one column in a CSV file by multiple values. For instance, I would like all of the data in the CSV file that is related to departments 104, 105, 106, etc. I have the code below, so far which works for each department individually. However, is there something more dynamic that can utilize... | [
"you can use loc in combination with the isin to filter on all the departments\n\ndf=df.loc[df['Department'].isin(departments)]\ndf.to_csv('file_filtered.csv')\n\n\n",
"Alternatively you can combine in with query.\nCheck out this example:\nimport pandas as pd\nimport numpy as np\ndf = pd.DataFrame({\n 'departm... | [
1,
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074147563_csv_pandas_python.txt |
Q:
Creating a 2x2 grid of images in a single array based on 4 images in python
I've been stuck on this question and I have figured it out in the image below. The second image is the first task that task 2 is based on. I have been told that the solution needs to be in a single new array. The following starter script w... | Creating a 2x2 grid of images in a single array based on 4 images in python | I've been stuck on this question and I have figured it out in the image below. The second image is the first task that task 2 is based on. I have been told that the solution needs to be in a single new array. The following starter script was given: grid_image = and plt.imshow(grid_image).
Task 1 code:
images = np.lo... | [
"Here is an example using de CIFAR10 dataset from TensorFlow. For this task, you can use NumPy Indexing on 'ndarrays'.\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nimport numpy as np\n(images, _), (_, _) = tf.keras.datasets.cifar10.load_data()\n\ngrid_image = images\nfig, axis = plt.subplots(2,2)... | [
1
] | [] | [] | [
"image",
"matplotlib",
"python",
"subplot"
] | stackoverflow_0074147365_image_matplotlib_python_subplot.txt |
Q:
Variables in callback function wont update even when the loop reiterates
The task I am currently working on is:
A robot that is installed with a LIDAR sensor and placed in an enclosed warehouse. The robot initially is placed at any random position in the environment. My task is to guide the robot around the wareho... | Variables in callback function wont update even when the loop reiterates | The task I am currently working on is:
A robot that is installed with a LIDAR sensor and placed in an enclosed warehouse. The robot initially is placed at any random position in the environment. My task is to guide the robot around the warehouse using the values from the sensor, such as wall following etc.
The problem ... | [
"msg won't change as you're still inside callback(msg). In your code, callback(msg) will be called everytime sub will receive a LiDAR scan message.\nI suggest that you separate the code that receives the message from the code that waits and publishes, as you will lose laser scan messages if your node is still proce... | [
1
] | [] | [] | [
"python",
"ros"
] | stackoverflow_0074147582_python_ros.txt |
Q:
Python pip still not recognized
I've been trying to get pip to work with python. I've followed a lot of the guides out there and I still can't seem to get this working.
I've downloaded the file from https://bootstrap.pypa.io/get-pip.py.
I used the terminal to navigate to it and install.
When I go to settings in my... | Python pip still not recognized | I've been trying to get pip to work with python. I've followed a lot of the guides out there and I still can't seem to get this working.
I've downloaded the file from https://bootstrap.pypa.io/get-pip.py.
I used the terminal to navigate to it and install.
When I go to settings in my project and look under 'interpreter'... | [
"try python -m pip install package-name\n"
] | [
0
] | [] | [] | [
"pip",
"pycharm",
"python"
] | stackoverflow_0074147700_pip_pycharm_python.txt |
Q:
loosing dict content as soon as am out of loop in python
Team: need some assistance..
sub: loosing dict content as soon as am out of loop. dict is populated with loop vars that are added to dict using subscript approach.
below foo() is always getting executed because the team_oncall_dict is empty outside. any hin... | loosing dict content as soon as am out of loop in python | Team: need some assistance..
sub: loosing dict content as soon as am out of loop. dict is populated with loop vars that are added to dict using subscript approach.
below foo() is always getting executed because the team_oncall_dict is empty outside. any hint how can I retain it as it was inside loop?
def askduty_onca... | [
"t was local vs global. fixed it by declaring the team_oncall_dict globally outside the function.\nintead of\ndef func1()\nteam_oncall_dict = {}\n\nteam_oncall_dict = {}\ndef func1()\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"loops",
"python"
] | stackoverflow_0074147351_dictionary_loops_python.txt |
Q:
Using openpyxl to append URL links to Excel, but they aren't hyperlinked in Excel
I've been using openpyxl's append() function to add url links to an Excel document. When I open Excel, none of the links have hyperlinks until I go into each individual cell and press enter. How do I format as hyperlink via Python du... | Using openpyxl to append URL links to Excel, but they aren't hyperlinked in Excel | I've been using openpyxl's append() function to add url links to an Excel document. When I open Excel, none of the links have hyperlinks until I go into each individual cell and press enter. How do I format as hyperlink via Python during my append? Thanks!
url = 'www.google.com'
ws.append([url])
| [
"You need to set the cell hyperlink attribute and the style. Then Excel doesn't need to work it out, which is what happens when you select the cell and press Enter.\nHere's a minimal example:\nfrom openpyxl import Workbook\n\nwb = Workbook() # create a new workbook\nws = wb.active # get the active sheet\n\nws.tit... | [
1
] | [] | [] | [
"append",
"excel",
"openpyxl",
"python"
] | stackoverflow_0074146896_append_excel_openpyxl_python.txt |
Q:
Need help creating a GCP Machine Image using GCP Python Libraries
I'm trying to create a new machine image from a .tar.gz file in one of my storage buckets. Doing this through the console is easy enough, but I need to do this programmatically with Python for a project I'm working on.
I've found what I think is the... | Need help creating a GCP Machine Image using GCP Python Libraries | I'm trying to create a new machine image from a .tar.gz file in one of my storage buckets. Doing this through the console is easy enough, but I need to do this programmatically with Python for a project I'm working on.
I've found what I think is the correct sections on how to create the machine image, but without examp... | [
"Hurray! I was able to successfully create my image from the tar.gz file within my storage bucket. Thanks for the help everyone.\nfrom pprint import pprint\nimport os\nfrom googleapiclient import discovery\nfrom oauth2client.client import GoogleCredentials\n\n#Path to service account credentials JSON file for authe... | [
1,
0
] | [] | [] | [
"google_cloud_platform",
"python"
] | stackoverflow_0074133955_google_cloud_platform_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.