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:
How do I group into different dates based on change in another column values in Pandas
I have data that looks like this
df = pd.DataFrame({'ID': [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
'DATE': ['1/1/2015','1/2/2015', '1/3/2015','1/4/2015','1/5/2015','1/6/2015','1/7/2015','1/8/2015',
'1/9/2016','1/2/2015'... | How do I group into different dates based on change in another column values in Pandas | I have data that looks like this
df = pd.DataFrame({'ID': [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
'DATE': ['1/1/2015','1/2/2015', '1/3/2015','1/4/2015','1/5/2015','1/6/2015','1/7/2015','1/8/2015',
'1/9/2016','1/2/2015','1/3/2015','1/4/2015','1/5/2015','1/6/2015','1/7/2015'],
'CD': ['A','A','A','A','B','B','A... | [
"make grouper for grouping\ngrouper = df['CD'].ne(df['CD'].shift(1)).cumsum()\n\ngrouper:\n0 1\n1 1\n2 1\n3 1\n4 2\n5 2\n6 3\n7 3\n8 4\n9 5\n10 5\n11 5\n12 5\n13 5\n14 5\nName: CD, dtype: int32\n\nthen use groupby with grouper\ndf.groupby(['ID', grouper, 'CD'])... | [
1
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074643312_pandas_python_python_3.x.txt |
Q:
How do I Scrape and Iterate Through a Table from Website in Python
I am trying to scrape and iterate through a table in Python and then input it into a pandas DataFrame, but I am having trouble even finding the table using BeautifulSoup. This is what I normally do, but there does not seem to be a table within the ... | How do I Scrape and Iterate Through a Table from Website in Python | I am trying to scrape and iterate through a table in Python and then input it into a pandas DataFrame, but I am having trouble even finding the table using BeautifulSoup. This is what I normally do, but there does not seem to be a table within the source code. How would I pull the main table on this page?
from bs4 impo... | [
"That is because there is no table tag on the URL you are loading. Go to the URL and view the source then search on \"<table\" you will find that there are no results\n",
"when you get the table, define the HTML tag of the table as a dictionary dict or a list list such as \"tablex\"\nafter that you may do the fol... | [
0,
0,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0064729163_beautifulsoup_python.txt |
Q:
Imported a file but it says module not found
So i have the issue that i imported a file "DB.py", but if i try to run my program it says that the module wasnt found.
See this error
This is how in imported the file
I already tried to change the file name n stuff but nothing rly works.
A:
You need a blank python fi... | Imported a file but it says module not found | So i have the issue that i imported a file "DB.py", but if i try to run my program it says that the module wasnt found.
See this error
This is how in imported the file
I already tried to change the file name n stuff but nothing rly works.
| [
"You need a blank python file named __init__.py in the directory that has DB.py. It tells python that there is a python module in that directory.\n"
] | [
0
] | [] | [] | [
"python",
"python_import"
] | stackoverflow_0074643602_python_python_import.txt |
Q:
Get the first item from an iterable that matches a condition
I would like to get the first item from a list matching a condition. It's important that the resulting method not process the entire list, which could be quite large. For example, the following function is adequate:
def first(the_iterable, condition = la... | Get the first item from an iterable that matches a condition | I would like to get the first item from a list matching a condition. It's important that the resulting method not process the entire list, which could be quite large. For example, the following function is adequate:
def first(the_iterable, condition = lambda x: True):
for i in the_iterable:
if condition(i):... | [
"Python 2.6+ and Python 3:\nIf you want StopIteration to be raised if no matching element is found:\nnext(x for x in the_iterable if x > 3)\n\nIf you want default_value (e.g. None) to be returned instead:\nnext((x for x in the_iterable if x > 3), default_value)\n\nNote that you need an extra pair of parentheses aro... | [
767,
52,
43,
26,
13,
12,
12,
8,
7,
5,
4,
1,
1,
1,
0,
0,
0
] | [
"Oneliner:\nthefirst = [i for i in range(10) if i > 3][0]\n\nIf youre not sure that any element will be valid according to the criteria, you should enclose this with try/except since that [0] can raise an IndexError.\n"
] | [
-3
] | [
"iterator",
"python"
] | stackoverflow_0002361426_iterator_python.txt |
Q:
Compare the values of one list with the values of another list
I have the list a:
a = ['wood', 'stone', 'bricks', 'diamond']
And the list b:
b = ['iron', 'gold', 'stone', 'diamond', 'wood']
I need to compare lists and if value of list a equals with value from list b, it will be added to a list c:
c = ['wood', 'sto... | Compare the values of one list with the values of another list | I have the list a:
a = ['wood', 'stone', 'bricks', 'diamond']
And the list b:
b = ['iron', 'gold', 'stone', 'diamond', 'wood']
I need to compare lists and if value of list a equals with value from list b, it will be added to a list c:
c = ['wood', 'stone', 'diamond']
How can I compare these lists?
| [
"You could convert them to sets and get the intersection.\nlist(set(a) & set(b))\n\n",
"When comparing values of one list to another you can use one of two options:\nFirst you could use a for loop like so:\nc = []\n\nfor element in a:\n if element in b:\n c.append(element)\nprint(c)\n\nThis is a rather ... | [
1,
0
] | [] | [] | [
"compare",
"list",
"python"
] | stackoverflow_0074643499_compare_list_python.txt |
Q:
request.headers.get('Authorization') is empty in Flask production
I have the following flask method that simple returns back the value of the Authorization header:
@app.route('/test', methods=['POST'])
def test():
return jsonify({"data" : request.headers.get('Authorization') })
When I submit the following curl... | request.headers.get('Authorization') is empty in Flask production | I have the following flask method that simple returns back the value of the Authorization header:
@app.route('/test', methods=['POST'])
def test():
return jsonify({"data" : request.headers.get('Authorization') })
When I submit the following curl request to my API which has been deployed to a DO instance, the header... | [
"Have you tried using a proper Authorization header? Possibly the header is being filtered out by a web application firewall or proxy because it doesn't specify a scheme. For example:\n\ncurl --data '' -H \"Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=\" api.mysite.com/test\n\nThis sends a basic authorization heade... | [
2,
0
] | [] | [] | [
"authorization",
"flask",
"http",
"python"
] | stackoverflow_0038927945_authorization_flask_http_python.txt |
Q:
install Chrome driver, AttributeError: 'Service' object has no attribute 'process'
#This is the code that i tried to use chrome driver
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
driver=webdriver.Chrome(r"/usr/local/bin/chromedriver")
#But the error is coming..
<ipy... | install Chrome driver, AttributeError: 'Service' object has no attribute 'process' | #This is the code that i tried to use chrome driver
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
driver=webdriver.Chrome(r"/usr/local/bin/chromedriver")
#But the error is coming..
<ipython-input-118-b695456c07d9>:6: DeprecationWarning: executable_path has been deprecated... | [
"In the latest Selenium version, executable_path has been deprecated, so you have to use Service:\nfrom selenium.webdriver.chrome.service import Service\n\ndriver = webdriver.Chrome(service=Service(<chromedriver.exe path>))\ndriver.get(<URL>)\n\n"
] | [
0
] | [] | [] | [
"attributeerror",
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0074643146_attributeerror_python_selenium_selenium_chromedriver.txt |
Q:
Flask-Sqlite: not visualizing username list from database in the dropdown menu
I am new to web dev with Python Flask and SQlalchemy and I am trying to populate a a dropdown menu with usernames from the table "user" for a Kanban board. I was able to fetch the datas from the database but for some reason they are not... | Flask-Sqlite: not visualizing username list from database in the dropdown menu | I am new to web dev with Python Flask and SQlalchemy and I am trying to populate a a dropdown menu with usernames from the table "user" for a Kanban board. I was able to fetch the datas from the database but for some reason they are not displayed in the dropdown menu in my dashboard template. Actually the dropdown menu... | [
"The usernames you're getting in a console is a list of tuples. Each tuple has only one item which you're accessing in dashboard.html like this:\n<OPTION value={{t[0]}}>{{t[1]}}</OPTION>\nThe second item {{t[1}} is None therefore you are getting no visible text in a select field. Try to go like this:\n<OPTION value... | [
1
] | [] | [] | [
"flask",
"python",
"sqlite"
] | stackoverflow_0074643082_flask_python_sqlite.txt |
Q:
Create a column of differences in 'col2' for each item in 'col1'
I have the following dataframe:
df=pd.DataFrame({
'col1' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D'],
'col2' : [9.6,10.4, 11.2, 3.3, 6, 4, 1.94, 15.44, 6.17, 8.16]
})
It has the display :
col1 col2
0 A 9.60
1 A 10.40
2 ... | Create a column of differences in 'col2' for each item in 'col1' | I have the following dataframe:
df=pd.DataFrame({
'col1' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D'],
'col2' : [9.6,10.4, 11.2, 3.3, 6, 4, 1.94, 15.44, 6.17, 8.16]
})
It has the display :
col1 col2
0 A 9.60
1 A 10.40
2 A 11.20
3 B 3.30
4 B 6.00
5 B 4.00
6 C 1.94
7 C ... | [
"You need a groupby, this works i think :\ndf.insert(2, 'Diff', (df.groupby('col1')['col2'].diff()))\n\n\nresult :\n col1 col2 Diff\n0 A 9.60 NaN\n1 A 10.40 0.80\n2 A 11.20 0.80\n3 B 3.30 NaN\n4 B 6.00 2.70\n5 B 4.00 -2.00\n6 C 1.94 NaN\n7 C 15.44 13.50\... | [
2,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074643572_dataframe_pandas_python.txt |
Q:
Dynamically change scale of widgets in Canvas - Python
I am trying to create a canvas with one useful function for me. I need to make my program understand when object on canvas is too big so this object will collide with borders of canvas and automatically will decrise size of object. I know that canvas can't cha... | Dynamically change scale of widgets in Canvas - Python | I am trying to create a canvas with one useful function for me. I need to make my program understand when object on canvas is too big so this object will collide with borders of canvas and automatically will decrise size of object. I know that canvas can't change size of objects, canvas just change coordinates of objec... | [
"Okay now, you should change this part\ndata = c.bbox(rect)\n\nif float(data[0]) <= 0 or float(data[1]) <= 0:\n print(data)\n c.scale(\"all\", ((x1+x2) / 2), ((y1+y2) / 2), 0.5, 0.5)\n\ninto this one:\ndata = c.bbox(rect)\nwhile float(data[0]) <= 0 or float(data[1]) <= 0:\n c.scale(\"all\", ((x1+x2) / 2), ... | [
0
] | [] | [] | [
"canvas",
"python",
"scale",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074627144_canvas_python_scale_tkinter_tkinter_canvas.txt |
Q:
Write array with opcua
everyone!
I need to write a variable as an array (list) to the OPC server. I am using Python and Python OPC-UA.
In the picture you can see the name and structure of the variable where I am trying to write the data.
opc-image
I try to use this code and get an error
q = [0]*50
data = c... | Write array with opcua | everyone!
I need to write a variable as an array (list) to the OPC server. I am using Python and Python OPC-UA.
In the picture you can see the name and structure of the variable where I am trying to write the data.
opc-image
I try to use this code and get an error
q = [0]*50
data = client.get_node(f'ns=3;s="OSC... | [
"Ok you have a custom datatype so you have to create the corresponding class:\nq = [ua.OSC(...), ua.OSC(...), ...]\ndata.set_value(ua.Variant(q, ua.VariantType.ExtensionObject)) \n\n"
] | [
1
] | [] | [] | [
"opc",
"opc_ua",
"python"
] | stackoverflow_0074640874_opc_opc_ua_python.txt |
Q:
Iam getting this error how to solve AttributeError: 'tuple' object has no attribute 'setInput'?
I have imported a picture and everything is fine but I am getting an AttributeError when running net.setInput(blob).
import numpy as np
import cv2
#load the image
img=cv2.imread(r"E:\Face recognition\3_FaceDetection_Fe... | Iam getting this error how to solve AttributeError: 'tuple' object has no attribute 'setInput'? | I have imported a picture and everything is fine but I am getting an AttributeError when running net.setInput(blob).
import numpy as np
import cv2
#load the image
img=cv2.imread(r"E:\Face recognition\3_FaceDetection_FeatureExtraction\images\faces.jpg")
cv2.imshow('faces',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
pr... | [
"As @Dan Mašek mentioned in his comment, the critical line is\nnet = cv2.dnn.readNetFromCaffe(\"E:/Face recognition/Models/deploy.prototxt.txt\"),(\"E:/Face recognition/Models/res10_300x300_ssd_iter_140000_fp16.caffemodel\")\n\nThe comma makes net a tuple containing the return value of the function calll cv2.dnn.re... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074628839_python.txt |
Q:
Convert dataframe column names from camel case to snake case
I want to change the column labels of a Pandas DataFrame from
['evaluationId,createdAt,scheduleEndDate,sharedTo, ...]
to
['EVALUATION_ID,CREATED_AT,SCHEDULE_END_DATE,SHARED_TO,...]
I have a lot of columns with this pattern "aaaBb" and I want to create ... | Convert dataframe column names from camel case to snake case | I want to change the column labels of a Pandas DataFrame from
['evaluationId,createdAt,scheduleEndDate,sharedTo, ...]
to
['EVALUATION_ID,CREATED_AT,SCHEDULE_END_DATE,SHARED_TO,...]
I have a lot of columns with this pattern "aaaBb" and I want to create this pattern "AAA_BB" of renamed columns
Can anyone help me?
Cheer... | [
"You can use a regex with str.replace to detect the lowercase-UPPERCASE shifts and insert a _, then str.upper:\ndf.columns = (df.columns\n .str.replace('(?<=[a-z])(?=[A-Z])', '_', regex=True)\n .str.upper()\n )\n\nBefore:\n evaluationId createdAt scheduleEndDate sharedTo\n... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074643621_dataframe_pandas_python.txt |
Q:
How to give Tkinter file dialog focus
I'm using OS X. I'm double clicking my script to run it from Finder. This script imports and runs the function below.
I'd like the script to present a Tkinter open file dialog and return a list of files selected.
Here's what I have so far:
def open_files(starting_dir):
"... | How to give Tkinter file dialog focus | I'm using OS X. I'm double clicking my script to run it from Finder. This script imports and runs the function below.
I'd like the script to present a Tkinter open file dialog and return a list of files selected.
Here's what I have so far:
def open_files(starting_dir):
"""Returns list of filenames+paths given sta... | [
"For anybody that ends up here via Google (like I did), here is a hack I've devised that works in both Windows and Ubuntu. In my case, I actually still need the terminal, but just want the dialog to be on top when displayed.\n# Make a top-level instance and hide since it is ugly and big.\nroot = Tkinter.Tk()\nroot.... | [
15,
6,
4,
1,
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003375227_python_tkinter.txt |
Q:
ParserError: unable to convert txt file to df due to json format and delimiter being the same
Im fairly new dealing with .txt files that has a dictionary within it. Im trying to pd.read_csv and create a dataframe in pandas.I get thrown an error of Error tokenizing data. C error: Expected 4 fields in line 2, saw 11... | ParserError: unable to convert txt file to df due to json format and delimiter being the same | Im fairly new dealing with .txt files that has a dictionary within it. Im trying to pd.read_csv and create a dataframe in pandas.I get thrown an error of Error tokenizing data. C error: Expected 4 fields in line 2, saw 11. I belive I found the root problem which is the file is difficult to read because each row contain... | [
"I think adding quotes around the dictionaries is the right approach. You can use regex to do so and use a different quote character than \" (I used § in my example):\nfrom io import StringIO\nimport re\nimport json\n\nwith open(\"store.txt\", \"r\") as f:\n csv_content = re.sub(r\"(\\{.*})\", r\"§\\1§\", f.read... | [
0
] | [] | [] | [
"pandas",
"python",
"text_files"
] | stackoverflow_0074641167_pandas_python_text_files.txt |
Q:
How do I add this code (txt file) into my class __init__ section?
Using Python. I have a class with 4 functions (addStudent, showStudent, deleteStudent, searchStudent), and am pulling from a database from a .txt file.
I have this code at the beginning of every function:
data = "studentMockData_AS2.txt"
stu... | How do I add this code (txt file) into my class __init__ section? | Using Python. I have a class with 4 functions (addStudent, showStudent, deleteStudent, searchStudent), and am pulling from a database from a .txt file.
I have this code at the beginning of every function:
data = "studentMockData_AS2.txt"
students = []
with open(data, "r") as datafile:
f... | [
"There is something going wrong with your function SearchStudent. You may want to pass an extra parameter OR to use a class member variable to compare to the string 'byId'.\nIn the case the if condition passes (i.e.: self == 'byId' is true), then your class reference self is a string. So it is normal it does not ha... | [
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074643650_class_python.txt |
Q:
Python in-memory cache with time to live
I have multiple threads running the same process that need to be able to to notify each other that something should not be worked on for the next n seconds its not the end of the world if they do however.
My aim is to be able to pass a string and a TTL to the cache and be a... | Python in-memory cache with time to live | I have multiple threads running the same process that need to be able to to notify each other that something should not be worked on for the next n seconds its not the end of the world if they do however.
My aim is to be able to pass a string and a TTL to the cache and be able to fetch all the strings that are in the c... | [
"In case you don't want to use any 3rd libraries, you can add one more parameter to your expensive function: ttl_hash=None. This new parameter is so-called \"time sensitive hash\", its the only purpose is to affect lru_cache.\nFor example:\nfrom functools import lru_cache\nimport time\n\n\n@lru_cache()\ndef my_expe... | [
163,
130,
44,
32,
19,
19,
8,
7,
5,
2
] | [
"You can also go for dictttl, which has MutableMapping, OrderedDict and defaultDict(list)\nInitialize an ordinary dict with each key having a ttl of 30 seconds\ndata = {'a': 1, 'b': 2}\ndict_ttl = DictTTL(30, data)\n\nOrderedDict\ndata = {'a': 1, 'b': 2}\ndict_ttl = OrderedDictTTL(30, data)\n\ndefaultDict(list)\ndi... | [
-1,
-1
] | [
"caching",
"python"
] | stackoverflow_0031771286_caching_python.txt |
Q:
How to suppress OpenAI API warnings in Python
When can I suppress warnings such as:
message='Request to OpenAI API' method=post path=https://api.openai.com/v1/engines/davinci/completions
when I am running OpenAI in python?
A:
Add this to your Jupyter Notebook or Python script file
import logging
logging.getLogge... | How to suppress OpenAI API warnings in Python | When can I suppress warnings such as:
message='Request to OpenAI API' method=post path=https://api.openai.com/v1/engines/davinci/completions
when I am running OpenAI in python?
| [
"Add this to your Jupyter Notebook or Python script file\nimport logging\nlogging.getLogger().setLevel(logging.CRITICAL)\n\n",
"When you are using the OpenAI python package and do requests to GPT-3 for example you will get messages like OP shows (showing the duration of the request for example).\nIn theory you ne... | [
0,
0
] | [] | [] | [
"openai",
"python"
] | stackoverflow_0071893613_openai_python.txt |
Q:
How to configure Atom to run Python3 scripts?
In my terminal, I type $ which python3, outputting
/opt/local/bin/python3
I would like to configure Atom to run Python3 scripts. In my Atom Config, I have
runner:
python: "/opt/local/bin/python3"
However, if I run the following script in some script named filename.... | How to configure Atom to run Python3 scripts? | In my terminal, I type $ which python3, outputting
/opt/local/bin/python3
I would like to configure Atom to run Python3 scripts. In my Atom Config, I have
runner:
python: "/opt/local/bin/python3"
However, if I run the following script in some script named filename.py,
import sys
print(sys.version)
I get the follow... | [
"Go to the Atom's menu bar -> Packages -> Script -> Configure Script\n(Or, you can use the shortcut Shift+Ctrl+Alt+O)\nThen type python3 to the Command space.\nHopefully, it will work.\n",
"i am using \"script\" package (3.18.1 by rgbkrk) to run code inside atom and this is how i fixed it\n\nopen package settings... | [
33,
12,
6,
4,
3,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"atom_editor",
"path",
"python",
"python_3.x"
] | stackoverflow_0035546627_atom_editor_path_python_python_3.x.txt |
Q:
Hexadecimal to decimal array each element 1 byte long
I have the following hexadecimal string:
7609a2fed47be9131ea1b803afc517b8
I want to convert it to hexadecimal array each element 1 byte long
[76 09 a2 fe d4 7b e9 13 1e a1 b8 03 af c5 17 b8]
then i need to convert it to decimal array.
i tried converting it to b... | Hexadecimal to decimal array each element 1 byte long | I have the following hexadecimal string:
7609a2fed47be9131ea1b803afc517b8
I want to convert it to hexadecimal array each element 1 byte long
[76 09 a2 fe d4 7b e9 13 1e a1 b8 03 af c5 17 b8]
then i need to convert it to decimal array.
i tried converting it to binary then to hexadecimal again, it did not work
| [
"To convert a hexadecimal string to a list of hexadecimal values, each one byte long, you can use the binascii.unhexlify() method from the binascii module. This method takes a hexadecimal string as its input, and returns a bytes object containing the corresponding binary data.\nYou can then use the bytearray() cons... | [
0,
0
] | [] | [] | [
"arrays",
"hex",
"python"
] | stackoverflow_0074643739_arrays_hex_python.txt |
Q:
How Can I call a function with values that will be executed only once when I have several parameters in pytest
I run pytest with several params:
@pytest.mark.parametrize('signature_algorithm, cipher, name', [
pytest.param(rsa_pss_rsae_sha256, AES128-GCM-SHA256, "KEY1"),
pytest.param(rsa_pss_rsae_sha384, AE... | How Can I call a function with values that will be executed only once when I have several parameters in pytest | I run pytest with several params:
@pytest.mark.parametrize('signature_algorithm, cipher, name', [
pytest.param(rsa_pss_rsae_sha256, AES128-GCM-SHA256, "KEY1"),
pytest.param(rsa_pss_rsae_sha384, AES128-GCM-SHA256, "KEY2"),
....
def test(signature_algorithm, cipher, cert_name, functaion1("data")):
...... | [
"First of all, I recommend you to read the documentation\nhttps://docs.pytest.org/en/6.2.x/parametrize.html\nMy spider sense says \"KEY1K\" is a project requirement. Therefore, you can either keep or remove it from parametrization and setup on test function begin\n@pytest.mark.parametrize(\"test_input,expected\", [... | [
0,
0
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074642527_pytest_python.txt |
Q:
How to get the difference between two dictionaries in Python?
I have two dictionaries, and I need to find the difference between the two, which should give me both a key and a value.
I have searched and found some addons/packages like datadiff and dictdiff-master, but when I try to import them in Python 2.7, it sa... | How to get the difference between two dictionaries in Python? | I have two dictionaries, and I need to find the difference between the two, which should give me both a key and a value.
I have searched and found some addons/packages like datadiff and dictdiff-master, but when I try to import them in Python 2.7, it says that no such modules are defined.
I used a set here:
first_dict ... | [
"I think it's better to use the symmetric difference operation of sets to do that Here is the link to the doc.\n>>> dict1 = {1:'donkey', 2:'chicken', 3:'dog'}\n>>> dict2 = {1:'donkey', 2:'chimpansee', 4:'chicken'}\n>>> set1 = set(dict1.items())\n>>> set2 = set(dict2.items())\n>>> set1 ^ set2\n{(2, 'chimpansee'), (4... | [
184,
108,
67,
12,
12,
10,
8,
8,
7,
6,
6,
5,
5,
3,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0032815640_dictionary_python.txt |
Q:
Python linking to wrong library folder - sndfile library not found
I get the following error when trying to import the librosa library into my python project and running it in the global python environment:
Traceback (most recent call last): File
"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/... | Python linking to wrong library folder - sndfile library not found | I get the following error when trying to import the librosa library into my python project and running it in the global python environment:
Traceback (most recent call last): File
"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/soundfile.py",
line 142, in
raise OSError('sndfile librar... | [
"As far as I know it only works with python 3.6 and 3.7 (lucidsonicdreams), although I didn't have success on 3.6. I had to create a virtual environment through conda and run code through Jupyter notebook. conda install tensorflow==1.15 (will not work with higher versions), python==3.7, pip install lucidsonicdreams... | [
0
] | [] | [] | [
"anaconda",
"librosa",
"libsndfile",
"python",
"pythonpath"
] | stackoverflow_0072623930_anaconda_librosa_libsndfile_python_pythonpath.txt |
Q:
Python. Attach data to asyncio.Task
Is there proper way to attach additional data to asyncio.create_task()? The example is
import asyncio
from dataclasses import dataclass
@dataclass
class Foo:
name: str
url_to_download: str
size: int
...
async def download_file(url: str):
return await download_i... | Python. Attach data to asyncio.Task | Is there proper way to attach additional data to asyncio.create_task()? The example is
import asyncio
from dataclasses import dataclass
@dataclass
class Foo:
name: str
url_to_download: str
size: int
...
async def download_file(url: str):
return await download_impl()
objs: list[Foo] = [obj1, obj2, ..... | [
"If I understood correctly, you just want a way to match the returned values from all your tasks to the instances of Foo whose url_to_download attributes you passed as arguments to said tasks.\nSince all you are doing in that last loop is blocking until all tasks are completed, you may as well simply run the corout... | [
0
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074635301_python_python_asyncio.txt |
Q:
Locating all numbers not present in multiple columns
I am having difficulties trying to locate multiple values from columns in a csv file.
So far i have tried defining the columns from which i want to extract the values as,
Assignments = (data.loc[:, ~data.columns.isin(['A', 'B','C'])])
This should take each colu... | Locating all numbers not present in multiple columns | I am having difficulties trying to locate multiple values from columns in a csv file.
So far i have tried defining the columns from which i want to extract the values as,
Assignments = (data.loc[:, ~data.columns.isin(['A', 'B','C'])])
This should take each column not named 'A', 'B' of 'C' from the csv file.
I tried ru... | [
"For a single value, you can do: df[(df[:] != 20).all(axis = 1)]\nFor multiple values you can use numpy arrays to do elementwise boolean logic:\nar1 = np.array((df[:] != 20).all(axis = 1))\nar2 = np.array((df[:] != 30).all(axis = 1))\ndf[ar1 & ar2]\n\n",
"To select rows in a Pandas DataFrame that do not contain a... | [
1,
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074642981_csv_pandas_python.txt |
Q:
How to strip a 2d array in python Numpy Array?
Suppose i have an np array like this-
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
I want a function fun_strip(x) . After applying this function i want the returned array to look like this:
[[ 6 7 8]
[11 12 13]]
A:
Do you want to remo... | How to strip a 2d array in python Numpy Array? | Suppose i have an np array like this-
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
I want a function fun_strip(x) . After applying this function i want the returned array to look like this:
[[ 6 7 8]
[11 12 13]]
| [
"Do you want to remove 1 value on each border?\na = np.array([[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]])\n\nout = a[1:a.shape[0]-1, 1:a.shape[1]-1]\n\nGeneralization for N:\nN = 1\na[N:a.shape[0]-N, N:a.shape[1]-N]\n\nOutput:... | [
1,
0,
0
] | [] | [] | [
"numpy",
"python",
"strip"
] | stackoverflow_0074643721_numpy_python_strip.txt |
Q:
Calculate by how much a row has shifted horizontally in pandas dataframe
I have a dataframe where the rows have been shifted horizontally by an unknown amount. Each and every row has shifted by a different amount as shown below:
Heading 1
Heading 2
Unnamed: 1
Unnamed: 2
NaN
34
24
NaN
5
NaN
NaN
NaN
NaN
NaN
13
7... | Calculate by how much a row has shifted horizontally in pandas dataframe | I have a dataframe where the rows have been shifted horizontally by an unknown amount. Each and every row has shifted by a different amount as shown below:
Heading 1
Heading 2
Unnamed: 1
Unnamed: 2
NaN
34
24
NaN
5
NaN
NaN
NaN
NaN
NaN
13
77
NaN
NaN
NaN
18
In the above dataframe, there are only 2 origin... | [
"Updated Answer\nThe logic that @mozway gave was an elegant one liner which i liked a lot but for some reason does not work always. Also it does not give the non nan values in the extra columns.\nI managed to get it working in a slightly long but relatively simple to understand logic. Here goes:\n#read the excel fi... | [
1,
0
] | [] | [] | [
"data_cleaning",
"data_preprocessing",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074641344_data_cleaning_data_preprocessing_dataframe_pandas_python.txt |
Q:
Check if string is in a pandas dataframe
I would like to see if a particular string exists in a particular column within my dataframe.
I'm getting the error
ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().
import pandas as pd
BabyDataSet = [('Bob', 968),... | Check if string is in a pandas dataframe | I would like to see if a particular string exists in a particular column within my dataframe.
I'm getting the error
ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().
import pandas as pd
BabyDataSet = [('Bob', 968), ('Jessica', 155), ('Mary', 77), ('John', 578)... | [
"a['Names'].str.contains('Mel') will return an indicator vector of boolean values of size len(BabyDataSet)\nTherefore, you can use\nmel_count=a['Names'].str.contains('Mel').sum()\nif mel_count>0:\n print (\"There are {m} Mels\".format(m=mel_count))\n\nOr any(), if you don't care how many records match your query... | [
165,
36,
20,
8,
3,
3,
2,
2,
1,
0,
0
] | [
"You should check the value of your line of code like adding checking length of it.\nif(len(a['Names'].str.contains('Mel'))>0):\n print(\"Name Present\")\n\n"
] | [
-1
] | [
"pandas",
"python"
] | stackoverflow_0030944577_pandas_python.txt |
Q:
Given a list of 2-columns pandas dataframes, how can I take the median of the second columns?
I have a list of pandas dataframes, each with 2-columns. The first column represents an ID, and the second represents the values. How would I combine these dataframes to where values with common IDs are replaced with its ... | Given a list of 2-columns pandas dataframes, how can I take the median of the second columns? | I have a list of pandas dataframes, each with 2-columns. The first column represents an ID, and the second represents the values. How would I combine these dataframes to where values with common IDs are replaced with its median?
E.g
df_1 = pd.DataFrame({'#id': [1,2,3,4], 'values_1': [1,3,4,3]})
df_2 = pd.DataFrame({'#i... | [
"Merge all df's into one df. Then group by id and calculate the median of each group.\ndf = pd.concat([df_1,df_2,df_3])\ndf = df.groupby('#id').agg({'values':'median'})\n'''\n#id values\n1 2.0\n2 5.0\n3 5.5\n4 5.0\n5 7.0\n\n'''\n\nWrite to excel:\ndf.reset_index().to_excel('give_an_excel_name.xlsx',index=... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074643951_numpy_pandas_python.txt |
Q:
How do I run Pygame on Pycharm
I am trying to run pygame on the PyCharm IDE, I have installed the latest version of pygame for python 3.5 and have added it to the project interpreter. I installed pygame from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame and copied it too python35-32/Scripts/. The test program ... | How do I run Pygame on Pycharm | I am trying to run pygame on the PyCharm IDE, I have installed the latest version of pygame for python 3.5 and have added it to the project interpreter. I installed pygame from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame and copied it too python35-32/Scripts/. The test program below runs fine in the python shell ... | [
"Follow the instructions provided here. I think its related to the problem you are having on pygame and PyCharm on windows. \nHow do I download Pygame for Python 3.5.1?\n",
"its bcus pycharme has not recognised you're env or working on wrong env\n\nhttps://www.jetbrains.com/help/pycharm/creating-virtual-environm... | [
0,
0
] | [] | [] | [
"failed_installation",
"pycharm",
"pygame",
"python",
"python_3.x"
] | stackoverflow_0039339709_failed_installation_pycharm_pygame_python_python_3.x.txt |
Q:
Enforce `Unresolved attribute reference` when referencing non-existing Python enums.Enum
I am just disappointed with the behavior of Enum vs standard object-based class, that I don't get in my IDE warning about Unresolved attribute reference, maybe I am not aware of some OO nuance which will allow making this happ... | Enforce `Unresolved attribute reference` when referencing non-existing Python enums.Enum | I am just disappointed with the behavior of Enum vs standard object-based class, that I don't get in my IDE warning about Unresolved attribute reference, maybe I am not aware of some OO nuance which will allow making this happen?
class Animal(Enum):
ant = 1
bee = 2
cat = 3
dog = 4
writing Animal.tiger ... | [
"This bug has been fixed in PyCharm 2022.1, the Unresolved attribute reference warning is now correctly shown by the IDE's linter.\n\n"
] | [
1
] | [] | [] | [
"enums",
"pycharm",
"python"
] | stackoverflow_0059462483_enums_pycharm_python.txt |
Q:
Pandas: enter missing rows in a dataframe
I'm collecting time series data, but sometimes for some time points there is no data to be collected. Just say for example I am collecting data across four time points, I might get a dataframe like this:
df_ = pd.DataFrame({'group': ['A']*3+['B']*3,
'ti... | Pandas: enter missing rows in a dataframe | I'm collecting time series data, but sometimes for some time points there is no data to be collected. Just say for example I am collecting data across four time points, I might get a dataframe like this:
df_ = pd.DataFrame({'group': ['A']*3+['B']*3,
'time': [1,2,4,1,3,4],
'value'... | [
"I would use:\n(df_.pivot(index='time', columns='group', values='value')\n # reindex only of you want to add missing times for all groups\n .reindex(range(df_['time'].min(), df_['time'].max()+1))\n .ffill().unstack().reset_index(name='value')\n)\n\nOutput:\n group time value\n0 A 1 100.0\n1 ... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074643048_pandas_python.txt |
Q:
Pycharm Multiprocessing Error, What Can I Do?
I'm facing a error with Pycharm when tried to use multiprocessing.
import multiprocessing
import time
inicio = time.perf_counter()
def calcula_soma():
print('Iniciando a Funcao...')
soma = 0
for i in range(50_000_000):
soma = soma + 1
print('C... | Pycharm Multiprocessing Error, What Can I Do? | I'm facing a error with Pycharm when tried to use multiprocessing.
import multiprocessing
import time
inicio = time.perf_counter()
def calcula_soma():
print('Iniciando a Funcao...')
soma = 0
for i in range(50_000_000):
soma = soma + 1
print('Calculo Finalizado!')
if __name__ == '__main__':
... | [
"After a long time looking for a anwser, I didn't find quickly. So to help someone else this is what helps me.\nThe link about this issues is: https://youtrack.jetbrains.com/issue/PY-50116\nSolution:\n\nIn menus bar go to Run/Debug Configurations\n\n\n\nAdd a New Configuration\n\n\n\nClick on Python\n\n\n\nRename t... | [
1
] | [] | [] | [
"multiprocessing",
"pycharm",
"python",
"python_3.x"
] | stackoverflow_0074644040_multiprocessing_pycharm_python_python_3.x.txt |
Q:
Airflow: How to set a dynamic timeout to python sensor
I have four tasks t1,t2,t3,t4. I want to push a value into xcom in t1 and pull that value from Xcom and use that as timeout in pythonsensor which is t4
Currently the value is hardcoded
PythonSensor(
task_id="poll_status",
poke_interval=POKE_INTERVAL,
... | Airflow: How to set a dynamic timeout to python sensor | I have four tasks t1,t2,t3,t4. I want to push a value into xcom in t1 and pull that value from Xcom and use that as timeout in pythonsensor which is t4
Currently the value is hardcoded
PythonSensor(
task_id="poll_status",
poke_interval=POKE_INTERVAL,
timeout=180,
mode=MODE,
soft_fail=True,
pytho... | [
"According to airflow XCOM documentation(https://airflow.apache.org/docs/apache-airflow/stable/concepts/xcoms.html), you might wish to use templated result:\nPythonSensor(\n task_id=\"poll_job_status\",\n poke_interval=POKE_INTERVAL,\n timeout={{ task_instance.xcom_pull(task_ids='t1', key='timeout') }}, # ... | [
0
] | [] | [] | [
"airflow",
"python"
] | stackoverflow_0074641709_airflow_python.txt |
Q:
Speed up importing huge json files
I am trying to open up some huge json files
papers0 = []
papers1 = []
papers2 = []
papers3 = []
papers4 = []
papers5 = []
papers6 = []
papers7 = []
for x in range(8):
for line in open(f'part_00{x}.json', 'r'):
globals()['papers%s' % x].append(json.loads(line))
Howev... | Speed up importing huge json files | I am trying to open up some huge json files
papers0 = []
papers1 = []
papers2 = []
papers3 = []
papers4 = []
papers5 = []
papers6 = []
papers7 = []
for x in range(8):
for line in open(f'part_00{x}.json', 'r'):
globals()['papers%s' % x].append(json.loads(line))
However the process above is slow. I wonder i... | [
"If the JSON files are very large then loading them (as Python dictionaries) will be I/O bound. Therefore, multithreading would be appropriate for parallelisation.\nRather than having discrete variables for each dictionary, why not have a single dictionary keyed on the significant numeric part of the filename(s).\n... | [
1
] | [] | [] | [
"for_loop",
"json",
"list",
"python"
] | stackoverflow_0074643262_for_loop_json_list_python.txt |
Q:
Python C++ API make member private
I'm making a python extension module using my C++ code and I've made a struct that I use to pass my C++ variables. I want some of those variables to be inaccessible from the python level. How can I do that?
typedef struct {
PyObject_HEAD
std::string region;
... | Python C++ API make member private | I'm making a python extension module using my C++ code and I've made a struct that I use to pass my C++ variables. I want some of those variables to be inaccessible from the python level. How can I do that?
typedef struct {
PyObject_HEAD
std::string region;
std::string stream;
bool ... | [
"You should do nothing. Unless you create an accessor property these attributes are already inaccessible from Python. Python cannot automatically see C/C++ struct members.\n"
] | [
1
] | [] | [] | [
"c++",
"python",
"python_c_api"
] | stackoverflow_0074642027_c++_python_python_c_api.txt |
Q:
How do I remove unwanted parts from strings in a Python DataFrame column
Based on the script originally suggested by u/commandlineluser at reddit, I (as a Python novice) attempted to revise the original code to remove unwanted parts that vary across column values. The Python script involves creating a dictionary w... | How do I remove unwanted parts from strings in a Python DataFrame column | Based on the script originally suggested by u/commandlineluser at reddit, I (as a Python novice) attempted to revise the original code to remove unwanted parts that vary across column values. The Python script involves creating a dictionary with keys and values and using a list comprehension with str.replace.
(part of ... | [
"You have two issues here, and they are all in this line:\nextensions = [\"dat\", \"ssp\", \"dta\", \"20dta\", \"u20dta\", \"f1dta\", \"f2dta\", \"v9\", \"xlsx\"]\n\nFirst issue\nThe first issue is in the order of the elements of this list. \"dat\" and \"dta\" are substrings of other elements in this string and the... | [
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074634406_python_regex.txt |
Q:
Matching a string if it contains all words of a list in python
I have a number of long strings and I want to match those that contain all words of a given list.
keywords=['special','dreams']
search_string1="This is something that manifests especially in dreams"
search_string2="This is something that manifests in s... | Matching a string if it contains all words of a list in python | I have a number of long strings and I want to match those that contain all words of a given list.
keywords=['special','dreams']
search_string1="This is something that manifests especially in dreams"
search_string2="This is something that manifests in special cases in dreams"
I want only search_string2 matched. So far ... | [
"you can use regex to do the same but I prefer to just use python.\nstring classes in python can be split to list of words. (join can join a list to string). while using word in list_of_words will help you understand if word is in the list.\nkeywords=['special','dreams']\nfound = True\nfor word in keywords:\n if... | [
1,
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074634142_python_string.txt |
Q:
Python3 - Tkinter - Widget creation with a dict
Im trying to create widgets dynamically onto the root window of tkinter with a json file as a widget config. I simplified the code so you can also test things out. (Im using grid() in my main code but its not necessary here)
The json file contains an items list with ... | Python3 - Tkinter - Widget creation with a dict | Im trying to create widgets dynamically onto the root window of tkinter with a json file as a widget config. I simplified the code so you can also test things out. (Im using grid() in my main code but its not necessary here)
The json file contains an items list with each widget in a seperate dict, it can look for examp... | [
"As what the name locals means, it stores only local variables. So locals() inside the function just contains local variables defined inside the function.\nIt is not recommended to use locals() like this. Just use a normal dictionary instead:\n...\n# Example: Change Frame Color to Blue\ndef change_background(frame_... | [
1
] | [] | [] | [
"dictionary",
"python",
"tkinter",
"variables"
] | stackoverflow_0074629883_dictionary_python_tkinter_variables.txt |
Q:
Join on different named columns in Pandas
I have two dataframes in Pandas
left = pd.DataFrame(
{"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]}
)
right = pd.DataFrame(
{"C": ["A0", "A1", "A2"], "D": ["D0", "D2", "D3"]}
)
How would I left join on the column A in left dataframe and column C in right data... | Join on different named columns in Pandas | I have two dataframes in Pandas
left = pd.DataFrame(
{"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]}
)
right = pd.DataFrame(
{"C": ["A0", "A1", "A2"], "D": ["D0", "D2", "D3"]}
)
How would I left join on the column A in left dataframe and column C in right dataframe?
Output
B D A
B0 D0 A0
B1 D2 A1
B... | [
"You can use merge with kwargs left_on and right_on:\npd.merge(left, right, how=\"left\", left_on=\"A\", right_on=\"C\")\n\nOutput:\n A B C D\n0 A0 B0 A0 D0\n1 A1 B1 A1 D2\n2 A2 B2 A2 D3\n\nEdit: you can drop the C column with .drop(\"C\", axis=1)\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074644002_pandas_python.txt |
Q:
Time complexity in case of multiple "in" operator usage in a condition in python
Suppose I have 3 elements that I want to check if they are in an iterable say (str or list).
I'm going to use an str as an example now but it should be the same in the case of a list:
Assuming values to check for are 'a','b','c' and s... | Time complexity in case of multiple "in" operator usage in a condition in python | Suppose I have 3 elements that I want to check if they are in an iterable say (str or list).
I'm going to use an str as an example now but it should be the same in the case of a list:
Assuming values to check for are 'a','b','c' and string to search in is 'abcd' saved in variable line.
There are "two" general ways of d... | [
"Hard to say about time complexity, but the first is actually faster at runtime, presumably because it doesn't involve\n\na name lookup (all)\na function call (all)\na generator expression\na list construction (['a','b','c']) (though this may be negligible for an imported module)\nSee comments.\n\nSee for yourself:... | [
6,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074643486_python.txt |
Q:
converting pandas column data from list of tuples to dict of dicts
I am trying to convert the pandas dataframe column values from -
{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}
this is what i have tried till now, but not working
import pandas as pd
df = pd.DataFram... | converting pandas column data from list of tuples to dict of dicts | I am trying to convert the pandas dataframe column values from -
{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}
this is what i have tried till now, but not working
import pandas as pd
df = pd.DataFrame.from_records([{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY':... | [
"We can use df.applymap(), with dict comprehension to convert each list to a dict, like this:\ndf[col_list] = df[col_list].applymap(lambda lst: {k: v for k, v in lst})\n\n",
"import pandas as pd\n\ndf = pd.DataFrame.from_records([{'01AB': [(\"ABC\", 5),(\"XYZ\", 4),(\"LMN\", 1)], '02AB_QTY': [(\"Other\", 20),(\"n... | [
1,
1,
1,
0
] | [] | [] | [
"amazon_dynamodb",
"lambda",
"pandas",
"python"
] | stackoverflow_0074643412_amazon_dynamodb_lambda_pandas_python.txt |
Q:
Does package management of a WinPython installation depend on the machine?
I have a WinPython installation on a network server that I can access from two different machines. As the installation is portable, I would expect the packages versions to be the same whether I use one or the other machine.
However, I recen... | Does package management of a WinPython installation depend on the machine? | I have a WinPython installation on a network server that I can access from two different machines. As the installation is portable, I would expect the packages versions to be the same whether I use one or the other machine.
However, I recently downgraded tensorflow from 2.9 to 2.6 using machine A, and when I check the ... | [
"Actually I found the issue. When downgrading tensorflow I used the --user option, so 2.6 version was installed in a user-specific location of machine A, not accessible from machine B.\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"python_install"
] | stackoverflow_0074643168_pip_python_python_install.txt |
Q:
Random Number Script Is not looping
for y in (random.randint(0,9)) in (x):
TypeError: argument of type 'int' is not iterable
import random
x = (random.randint(0,9))
print (x)
y = (random.randint(0,9))
print (y)
for y in (random.randint(0,9)) in (x):
if (y)==(x):
break
A:
what does (random.randint(0,... | Random Number Script Is not looping |
for y in (random.randint(0,9)) in (x):
TypeError: argument of type 'int' is not iterable
import random
x = (random.randint(0,9))
print (x)
y = (random.randint(0,9))
print (y)
for y in (random.randint(0,9)) in (x):
if (y)==(x):
break
| [
"what does (random.randint(0,9)) in (x) means?\nYou try iterate over int/number. You need to create an iterable object to loop over it like list, tuple, range etc.\n",
"If you want to iterate until x==y you should use a while loop. for loops iterate over a sequence.\nYou could do something like\nimport random\nx ... | [
0,
0
] | [] | [] | [
"loops",
"numbers",
"python",
"random",
"typeerror"
] | stackoverflow_0074644103_loops_numbers_python_random_typeerror.txt |
Q:
Pytest/Locust: ModuleNotFoundError No module named
Ive tried to find anwsers on similar topics, but... nothing helped.
When I run my regular tests with pytest -m blablabla - there are no problems, but
when I run locust by command:
locust -f my_locustfiles/instr_performance.py
than got this:
(venv) evgen@TLL amap... | Pytest/Locust: ModuleNotFoundError No module named | Ive tried to find anwsers on similar topics, but... nothing helped.
When I run my regular tests with pytest -m blablabla - there are no problems, but
when I run locust by command:
locust -f my_locustfiles/instr_performance.py
than got this:
(venv) evgen@TLL amapitest % locust -f my_locustfiles/instr_performance.py
Tr... | [
"Your current directory is automatically added to sys.path by locust, according to the documentation https://docs.locust.io/en/stable/writing-a-locustfile.html#how-to-structure-your-test-code\nTry going to the parent directory and run\nlocust -f amapitest/my_locustfiles/instr_performance.py\n",
"Ive solved my pro... | [
0,
0,
0
] | [] | [] | [
"locust",
"performance_testing",
"pytest",
"python",
"web_api_testing"
] | stackoverflow_0073375591_locust_performance_testing_pytest_python_web_api_testing.txt |
Q:
Tracking progress of joblib.Parallel execution
Is there a simple way to track the overall progress of a joblib.Parallel execution?
I have a long-running execution composed of thousands of jobs, which I want to track and record in a database. However, to do that, whenever Parallel finishes a task, I need it to exec... | Tracking progress of joblib.Parallel execution | Is there a simple way to track the overall progress of a joblib.Parallel execution?
I have a long-running execution composed of thousands of jobs, which I want to track and record in a database. However, to do that, whenever Parallel finishes a task, I need it to execute a callback, reporting how many remaining jobs ar... | [
"Yet another step ahead from dano's and Connor's answers is to wrap the whole thing as a context manager:\nimport contextlib\nimport joblib\nfrom tqdm import tqdm\n\n@contextlib.contextmanager\ndef tqdm_joblib(tqdm_object):\n \"\"\"Context manager to patch joblib to report into tqdm progress bar given as argumen... | [
77,
25,
22,
11,
7,
4,
1,
0,
0
] | [] | [] | [
"joblib",
"multiprocessing",
"multithreading",
"parallel_processing",
"python"
] | stackoverflow_0024983493_joblib_multiprocessing_multithreading_parallel_processing_python.txt |
Q:
Individually specify nested dict fields in pydantic model
Is it possible to specify the individual fields in a dict contained inside a pydantic model? I was not able to find anything but maybe I'm using the wrong keywords. I'm thinking of something like this:
from pydantic import BaseModel
class User(BaseModel):
... | Individually specify nested dict fields in pydantic model | Is it possible to specify the individual fields in a dict contained inside a pydantic model? I was not able to find anything but maybe I'm using the wrong keywords. I'm thinking of something like this:
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str = 'Jane Doe'
stats = {
ag... | [
"You can do something similar using nested classes:\nfrom pydantic import BaseModel\n\nclass UserStats(BaseModel):\n age: int\n height: float\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: UserStats\n\nThen when you construct any User instance you can pass the stats field as a dicti... | [
3,
2
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0074643755_pydantic_python.txt |
Q:
pandas dataframe - searching for numbers
On the column named "criacao" I have some data stored as object, and they are, for example, "2022-01-03 10:20:40" as df.head(1) and "2022-12-01 10:33:25" as df.tail(1).
I want to extract the data for every 3 months and store in a variable.
I am doing the following and it wo... | pandas dataframe - searching for numbers | On the column named "criacao" I have some data stored as object, and they are, for example, "2022-01-03 10:20:40" as df.head(1) and "2022-12-01 10:33:25" as df.tail(1).
I want to extract the data for every 3 months and store in a variable.
I am doing the following and it works for the first month:
fd_pri_tri = (df_fres... | [
"An option is to convert the criacao date string value to a python datetime data type, review the month for this date, and then assign that month to a specific quarter.\n\nMonth 1-3, assigned to Quarter 1\nMonth 4-6, assigned to Quarter 2\nMonth 7-9, assigned to Quarter 3\nMonth 10-12, assigned to Quarter 4\n\nPand... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074643963_pandas_python.txt |
Q:
more efficient way to select image pixel that satisfy multiple color conditions
i want to select fire pixels in each video frame using Lab, RGB, and YCbCr color rule.
i've tried with the code below, but the video output turns out really laggy. i believe this caused by iterating through pixel frame with loop. i won... | more efficient way to select image pixel that satisfy multiple color conditions | i want to select fire pixels in each video frame using Lab, RGB, and YCbCr color rule.
i've tried with the code below, but the video output turns out really laggy. i believe this caused by iterating through pixel frame with loop. i wonder if there is more efficient way to do this (e.g. with numpy).
here is my code:
# C... | [
"Solved!\nshoutout to @dan-mašek for helping me to solve this problem. here is the code: https://pastebin.com/DXrxmf17\n# COLOR SEGMENTATION\nlab_convert = convert_lab(frame)\nL, a, b = cv2.split(lab_convert)\nL_mean, a_mean, b_mean = cv2.mean(lab_convert)[:-1]\n\nrgb_convert = convert_rgb(frame)\nR, G, B = cv2.spl... | [
1
] | [] | [] | [
"image_processing",
"image_segmentation",
"numpy",
"opencv",
"python"
] | stackoverflow_0074641817_image_processing_image_segmentation_numpy_opencv_python.txt |
Q:
How do I use OpenCV to detect exclusively almost straight edges?
I'm trying to detect straight edges in a basketball card and what I have so far does a good job of detecting all edges. I would like for this piece of code however, to detect exclusively straight edges (the outline of the card).
import cv2
import num... | How do I use OpenCV to detect exclusively almost straight edges? | I'm trying to detect straight edges in a basketball card and what I have so far does a good job of detecting all edges. I would like for this piece of code however, to detect exclusively straight edges (the outline of the card).
import cv2
import numpy as np
import imutils
img = cv2.imread('edgedetection/cardgiannis.j... | [
"Here is what I think.\nIf you can somehow get the highest & lowest valued coordinates in the pixels that are forming the lines, you can use those pixels to form a rectangle that consist of the straight edges.\n\nUsing the pixels to (roughly) form a rectangle can be the solution!\n\nTo find the pixels in a line, yo... | [
0,
0
] | [] | [] | [
"computer_vision",
"edge_detection",
"image_processing",
"opencv",
"python"
] | stackoverflow_0073213310_computer_vision_edge_detection_image_processing_opencv_python.txt |
Q:
Apply lambda function to two columns in two Pandas dataframes
I have two data frames that I'm trying to merge, based on a primary & foreign key of company name. One data set has ~50,000 unique company names, the other one has about 5,000. Duplicate company names are possible within each list. I'm trying to produce... | Apply lambda function to two columns in two Pandas dataframes | I have two data frames that I'm trying to merge, based on a primary & foreign key of company name. One data set has ~50,000 unique company names, the other one has about 5,000. Duplicate company names are possible within each list. I'm trying to produce some string-edit distance metrics comparing two columns between tw... | [
"You can add a common column for both datasets and then we can use pandas merge on that common column\nHere is the sample code\nmwe1['common']=mwe2['common']=1\ndf = pd.merge(mwe1,mwe2,on='common').drop('common',1)\ndf.sort_values(by='salesforce_name',inplace=True)\n\nOutput:\n company_name reve... | [
0
] | [] | [] | [
"fuzzy_comparison",
"pandas",
"python",
"string"
] | stackoverflow_0074635404_fuzzy_comparison_pandas_python_string.txt |
Q:
displaying a table without invalid values python
How do I get rid of invalid values in a ragged list to display in a table?
A:
I'm not sure I fully understand what format you're trying to do, but hope ths helps point you in the right direction.
If you want to print only the values where val > 0.05:
Make your jo... | displaying a table without invalid values python | How do I get rid of invalid values in a ragged list to display in a table?
| [
"I'm not sure I fully understand what format you're trying to do, but hope ths helps point you in the right direction.\nIf you want to print only the values where val > 0.05:\n\nMake your joint_pmf_ID a numpy array.\nIndex by boolean condition and set the desired values to 0.\nIn your looping function, don't print ... | [
1
] | [] | [] | [
"numpy",
"python",
"statistics"
] | stackoverflow_0074644169_numpy_python_statistics.txt |
Q:
Python - Timeit within a class
I'm having some real trouble with timing a function from within an instance of a class. I'm not sure I'm going about it the right way (never used timeIt before) and I tried a few variations of the second argument importing things, but no luck. Here's a silly example of what I'm doing... | Python - Timeit within a class | I'm having some real trouble with timing a function from within an instance of a class. I'm not sure I'm going about it the right way (never used timeIt before) and I tried a few variations of the second argument importing things, but no luck. Here's a silly example of what I'm doing:
import timeit
class TimedClass():... | [
"if you're willing to consider alternatives to timeit, i recently found the stopwatch timer utility which might be useful in your case. it's really simple and intuitive, too:\nimport stopwatch\n\nclass TimedClass():\n\n def __init__(self):\n t = stopwatch.Timer()\n # do stuff here\n t.stop()... | [
10,
9,
7,
0,
0
] | [] | [] | [
"python",
"self",
"timeit"
] | stackoverflow_0003609148_python_self_timeit.txt |
Q:
how to compare dictionaries and color the different key, value
I have a django application. And I have two texboxes where data is displayed coming from two different functions.
So the data is displayed in the texboxes. But the key,value has to be marked red when there is a difference in the two dictionaries. So in... | how to compare dictionaries and color the different key, value | I have a django application. And I have two texboxes where data is displayed coming from two different functions.
So the data is displayed in the texboxes. But the key,value has to be marked red when there is a difference in the two dictionaries. So in this example it is ananas that has the difference.
So I have the Te... | [
"There are two misconcepts. First is how you are building you 'diff_set' variable to check in the template, it should be a list with the name of the fruit (Otherwise you need to do logic at template level, which is one thing you should always avoid.):\n['ananas',...]\n\nSecond is trying to color lines inside a text... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074641427_django_python.txt |
Q:
Way to recreate all python class instances each time program loops
For a python RPG, I have player_module.py, which contains all classes, methods and functions.
class RingOfRegeneration(Regeneration):
def __init__(self):
super().__init__()
self.name = "Ring of Regeneration"
self.item_ty... | Way to recreate all python class instances each time program loops | For a python RPG, I have player_module.py, which contains all classes, methods and functions.
class RingOfRegeneration(Regeneration):
def __init__(self):
super().__init__()
self.name = "Ring of Regeneration"
self.item_type = "Rings of Regeneration"
self.regenerate = 1
self.se... | [
"Your loot dict has in real reference to objects and if you assign to player character any object from loot_dict you assign reference to the same object what is in your loot_dict. (Just like a pointer in cpp).\nYou need to create new instance of object every time the player gets new item.\nTo achive it You can do s... | [
1
] | [] | [] | [
"class",
"python",
"reset"
] | stackoverflow_0074644091_class_python_reset.txt |
Q:
Tkinter menu background is not changing
I am trying to create a menu for a tkinter project
but I am facing some problems
the menu background is not changing
import tkinter as tk
root = tk.Tk()
Menu1= tk.Menu(root, background="red")
filemenu = tk.Menu(Menu1, tearoff=0)
filemenu.add_command(label="New")
filemenu.a... | Tkinter menu background is not changing | I am trying to create a menu for a tkinter project
but I am facing some problems
the menu background is not changing
import tkinter as tk
root = tk.Tk()
Menu1= tk.Menu(root, background="red")
filemenu = tk.Menu(Menu1, tearoff=0)
filemenu.add_command(label="New")
filemenu.add_command(label="Open")
filemenu.add_command... | [
"If you want to change the background of the items in your File menu, you have to config that Menu instead of the root Menu1\nfilemenu.config(background='red')\n\nIf you want to color each menu item individually, you can set background for each add_command\nfilemenu.add_command(label=\"New\", background='red')\nfil... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074644255_python_tkinter.txt |
Q:
Fill up DataFrame counting to full cartesian product
Look at this code:
result=pd.DataFrame(df.groupby(['col1','col2'])['col3'].count())
It basically does what I want to with one minor issue: I want the result to have the full cartesian product of all occurring values of col1 and col2 as index. Of course, my comm... | Fill up DataFrame counting to full cartesian product | Look at this code:
result=pd.DataFrame(df.groupby(['col1','col2'])['col3'].count())
It basically does what I want to with one minor issue: I want the result to have the full cartesian product of all occurring values of col1 and col2 as index. Of course, my command takes only those combinations of col1 and col2 into ac... | [
"is this what you're looking for?\nresult = df.groupby([\"col1\", \"col2\"])[\"col3\"].count().unstack(fill_value=0).stack()\n\n\nresult :\ncol1 col2\nA 1 2\n 2 1\n 3 0\nB 1 0\n 2 0\n 3 1\nC 1 2\n 2 0\n 3 0\n\n\n"
] | [
2
] | [] | [] | [
"cartesian_product",
"count",
"pandas",
"python"
] | stackoverflow_0074643411_cartesian_product_count_pandas_python.txt |
Q:
Add value to OAuth2PasswordRequestForm in FastAPI
i want the client to pass aditional information while loggin in to FastApi. I think for that i have to change the scheme for OAuth2PasswordRequestForm. Can anyone explain how to do that?
Im using the code from the FastApi tutorial right now:
https://fastapi.tiangol... | Add value to OAuth2PasswordRequestForm in FastAPI | i want the client to pass aditional information while loggin in to FastApi. I think for that i have to change the scheme for OAuth2PasswordRequestForm. Can anyone explain how to do that?
Im using the code from the FastApi tutorial right now:
https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/
| [
"If I understand your question correctly, you would like to have the user pass the info required by OAuth2PasswordRequestForm and also include some extra required information.\nThe easiest way to do this would probably be to create your own scheme that is a subclass of OAuth2PasswordRequestForm.\n\n import fasta... | [
0,
0
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0068973789_fastapi_python.txt |
Q:
Iterate and compare nth element with the rest of elements in list
I have a list of integers and have to check if all of the integers to the right (so, from each int to the end of the list) are strictly smaller than the one I'm iterating over.
E.g. for [42, 7, 12, 9, 2, 5] I have to compare if 42 is bigger than [7,... | Iterate and compare nth element with the rest of elements in list | I have a list of integers and have to check if all of the integers to the right (so, from each int to the end of the list) are strictly smaller than the one I'm iterating over.
E.g. for [42, 7, 12, 9, 2, 5] I have to compare if 42 is bigger than [7, 12, 9, 2, 5], if 7 is bigger than [12, 9, 2, 5] and so on to the end o... | [
"I'd suggest using enumerate to iterate over the items with their indices (as you're already doing), and then using all to iterate over all the items after a given item, and sum to sum all of the all results:\n>>> def count_dominators(items):\n... return sum(all(n > m for m in items[i+1:]) for i, n in enumerate... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074644376_python.txt |
Q:
Getting invalid signature for HMAC authentication of python pickle file
I am trying to use HMAC authentication for reading and write pickle files.
Sample Data :
import base64
import hashlib
import hmac
from datetime import datetime
import six
import pandas as pd
import pickle
df1 = pd.DataFrame({'id' : [1,2,3,4,5... | Getting invalid signature for HMAC authentication of python pickle file | I am trying to use HMAC authentication for reading and write pickle files.
Sample Data :
import base64
import hashlib
import hmac
from datetime import datetime
import six
import pandas as pd
import pickle
df1 = pd.DataFrame({'id' : [1,2,3,4,5],
'score' : [720, 700, 710, 690, 670]})
df2 = pd.DataFra... | [
"Here is some code illustrating what I think is a cleaner way to solve the problem.\nimport hashlib\nimport hmac\nimport io\nimport os\nimport pickle\n\nsample_obj = {'hello': [os.urandom(50)]}\n\ndata = pickle.dumps(sample_obj)\n\n# write it out\n\nmy_hmac = hmac.new(b'my_hmac_key', digestmod=hashlib.blake2b)\nmy_... | [
1
] | [] | [] | [
"hmac",
"pickle",
"python"
] | stackoverflow_0074638045_hmac_pickle_python.txt |
Q:
Python Clean Specific Elements in List of Lists
I have a noisy list with 3 different rows that looks like this:
array = ['Apple Mug Seaweed Wallet Toilet Bear Toy Key Alcohol Paper',
'cup, egg, pillow, leash, banana, raindrop, phone, animal, shirt, basket',
'1. Dog 2. America 3. Notebook 4. Mois... | Python Clean Specific Elements in List of Lists | I have a noisy list with 3 different rows that looks like this:
array = ['Apple Mug Seaweed Wallet Toilet Bear Toy Key Alcohol Paper',
'cup, egg, pillow, leash, banana, raindrop, phone, animal, shirt, basket',
'1. Dog 2. America 3. Notebook 4. Moisturizer 5. ADHD 6. Balloon 7. Contacts 8. Blanket 9... | [
"One approach is to use list comprehension (optional) and regular expressions, where a pattern can be set to keep only alphabetical characters. (e.g.: [a-zA-Z]+ meaning one or more alpha characters.)\nThe str.join() function is used to combine the regex search output into a single string, which is added as an eleme... | [
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074633667_list_python.txt |
Q:
Service geckodriver unexpectedly exited. Status code was: -6
I am using Ubuntu 22.04, and I got this error when I tried to run Selenium tutorial:
selenium.common.exceptions.WebDriverException: Message: Service geckodriver unexpectedly exited. Status code was: -6
And this is the code:
from selenium import webdrive... | Service geckodriver unexpectedly exited. Status code was: -6 | I am using Ubuntu 22.04, and I got this error when I tried to run Selenium tutorial:
selenium.common.exceptions.WebDriverException: Message: Service geckodriver unexpectedly exited. Status code was: -6
And this is the code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.we... | [
"Just to be sure, do you have Firefox installed? Does this thread help for you?\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074644408_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
Python Code Coverage and Multiprocessing
I use coveralls in combination with coverage.py to track python code coverage of my testing scripts. I use the following commands:
coverage run --parallel-mode --source=mysource --omit=*/stuff/idont/need.py ./mysource/tests/run_all_tests.py
coverage combine
coveralls --verb... | Python Code Coverage and Multiprocessing | I use coveralls in combination with coverage.py to track python code coverage of my testing scripts. I use the following commands:
coverage run --parallel-mode --source=mysource --omit=*/stuff/idont/need.py ./mysource/tests/run_all_tests.py
coverage combine
coveralls --verbose
This works quite nicely with the exceptio... | [
"Coverage 4.0 includes a command-line option --concurrency=multiprocessing to deal with this. You must use coverage combine afterward. For instance, if your tests are in regression_tests.py, then you would simply do this at the command line:\ncoverage run --concurrency=multiprocessing regression_tests.py\ncoverag... | [
28,
1,
0
] | [] | [] | [
"code_coverage",
"coverage.py",
"coveralls",
"multiprocessing",
"python"
] | stackoverflow_0028297497_code_coverage_coverage.py_coveralls_multiprocessing_python.txt |
Q:
No module named kubernetes.dynamic.resource
I try to deploy some .yaml file with code of Kubernetes, but get error
TASK [/cur/develop/inno/777/name.k8s/roles/deploy_k8s_dashboard : Apply the Kubernetes dashboard] ******************************************************************************************************... | No module named kubernetes.dynamic.resource | I try to deploy some .yaml file with code of Kubernetes, but get error
TASK [/cur/develop/inno/777/name.k8s/roles/deploy_k8s_dashboard : Apply the Kubernetes dashboard] *******************************************************************************************************************************************************... | [
"I've had a similar problem. locally I had to execute the following\nansible-galaxy collection install kubernetes.core\n\nOn the target server make sure that you have python3 installed as python2 won't be enough. Once that is installed, I also had to define the below in my vars:\nansible_python_interpreter: /bin/py... | [
0
] | [] | [] | [
"ansible",
"kubernetes",
"python"
] | stackoverflow_0074096933_ansible_kubernetes_python.txt |
Q:
GitPython Submodule Tree Display
I'm working with a git repo that has multiple sub-modules beneath. I'm able to walk through the blobs and trees in that folder with no problem, but when I encounter a submodule, I receive the following error: AttributeError: Cannot retrieve the name of a submodule if it was not set... | GitPython Submodule Tree Display | I'm working with a git repo that has multiple sub-modules beneath. I'm able to walk through the blobs and trees in that folder with no problem, but when I encounter a submodule, I receive the following error: AttributeError: Cannot retrieve the name of a submodule if it was not set initially.
The code I'm using looks ... | [
"For a full description on why Submodule objects retrieved from Trees are not fully functional, see https://github.com/gitpython-developers/GitPython/issues/1092\nSo the short answer: It is a bug/missing feature in GitPython that is still unsolved.\n"
] | [
0
] | [] | [] | [
"git",
"gitpython",
"python"
] | stackoverflow_0034360710_git_gitpython_python.txt |
Q:
Repeat a function 3 times
I'm programming the "Rock, paper, scissors". I want now to run the function I added below 3 times. I tried using a for _ in range(s) but printed the same result 3 times.
import random
OPTIONS = ["Rock", "Paper", "Scissors"]
def get_user_input():
user_choice = input("Select your play... | Repeat a function 3 times | I'm programming the "Rock, paper, scissors". I want now to run the function I added below 3 times. I tried using a for _ in range(s) but printed the same result 3 times.
import random
OPTIONS = ["Rock", "Paper", "Scissors"]
def get_user_input():
user_choice = input("Select your play (Rock, Paper or Scissors): ")
... | [
"I think you have to rework your code in main()\ndef main():\n\n for _ in range(3):\n user_choice = get_user_input()\n computer_choice = random_choice()\n game(user_choice, computer_choice)\n\n print(\"Game has ended!\")\n\nTry something like this\n",
"Your program works great! just one... | [
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074644420_python_python_3.x.txt |
Q:
Normalizing Nested JSON in python
I'm really new to API'S and python so,
I'm trying to convert a API request JSON that contains nested data into a pandas DataFrame to input it in power BI as a external python file, but I can't figure out what's hapennig with my JSON normalizing. It is a paginate API, so i had to i... | Normalizing Nested JSON in python | I'm really new to API'S and python so,
I'm trying to convert a API request JSON that contains nested data into a pandas DataFrame to input it in power BI as a external python file, but I can't figure out what's hapennig with my JSON normalizing. It is a paginate API, so i had to implement a loop to get all data from it... | [
"if produtos = list_products('all') is the output df in the question.\nprodutos = list_products('all')\ndf = pd.json_normalize(produtos.explode('retorno.produtos')['retorno.produtos'])\n\n'''\n| | produto.id | produto.codigo | produto.descricao | produto.tipo | produto.situacao | produt... | [
0
] | [] | [] | [
"api",
"json",
"pandas",
"powerbi",
"python"
] | stackoverflow_0074633613_api_json_pandas_powerbi_python.txt |
Q:
PySnmp query not working for reachable target but command line 'snmpget' succeeds
I need an SNMP server that can monitor an SNMP agent. For this purpose, I wrote a basic Python application, and I run an SNMP agent (polinux/snmpd image based), on the same network, the agent has a fixed IP address. When I run the SN... | PySnmp query not working for reachable target but command line 'snmpget' succeeds | I need an SNMP server that can monitor an SNMP agent. For this purpose, I wrote a basic Python application, and I run an SNMP agent (polinux/snmpd image based), on the same network, the agent has a fixed IP address. When I run the SNMP get query from the server container, I get the desired OIB, but when I want to do th... | [
"The issue was with Pipfile, the logs indicated some dependency issues and conflicts. I do not remember why but at some point the allow_prereleases flag was set to true in the file. When I set it to false and recreated the Pipfile.lock, the error gone away.\n"
] | [
0
] | [] | [] | [
"docker_compose",
"mib",
"pysnmp",
"python",
"snmp"
] | stackoverflow_0074430619_docker_compose_mib_pysnmp_python_snmp.txt |
Q:
Delta Lake Table Storage Sorting
I have a delta lake table and inserting the data into that table. Business asked to sort the data while storing it in the table.
I sorted my dataframe before creating the delta table as below
df.sort()
and then created the delta table as below
df.write.format('delta').Option('merg... | Delta Lake Table Storage Sorting | I have a delta lake table and inserting the data into that table. Business asked to sort the data while storing it in the table.
I sorted my dataframe before creating the delta table as below
df.sort()
and then created the delta table as below
df.write.format('delta').Option('mergeSchema, true).save('deltalocation')
... | [
"Delta Lake itself does not itself enable sorting because this would require any engine writing to sort the data. To balance simplicity, speed of ingestion, and speed of query, this is why Delta Lake itself does not require or enable sorting per se. i.e., your statement is correct.\n\nMy understanding is that it pa... | [
0
] | [] | [] | [
"azure_data_lake",
"azure_databricks",
"delta_lake",
"pyspark",
"python"
] | stackoverflow_0074638658_azure_data_lake_azure_databricks_delta_lake_pyspark_python.txt |
Q:
Is there an Alternative to textvariable on ttk.Entry widget, for tk.Text widget on TK inter?
so according to Tkinter documentation, the purpose of an Entry widget is to allow the user to enter or edit a single line of text. I want to get enter and Edit multiple lines of text but there is a problem. The alternative... | Is there an Alternative to textvariable on ttk.Entry widget, for tk.Text widget on TK inter? | so according to Tkinter documentation, the purpose of an Entry widget is to allow the user to enter or edit a single line of text. I want to get enter and Edit multiple lines of text but there is a problem. The alternative suggested by tkinter, Text, doesn't do the job at all!
here is my code using ttk.Entry:
def _s... | [
"The Text widget doesn't support textvariable because a Text widget can contain more than just text. To get the content out of the Text widget you need to call the get method on the widget.\nTo get all of the contents of the widget you first need to keep a reference to the widget. Then it's just a matter of calling... | [
1
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074643264_python_tkinter_user_interface.txt |
Q:
How can I sort a column in python3?
I am creating a tool to automate some tasks. These tasks generate two DataFrames, but when concatenating them the columns are messed up as follows:
col2 col4 col3 col1
0 A 2 0 a
1 A 1 1 B
2 B 9 9 c
3 NaN 8 4 D
4 D ... | How can I sort a column in python3? | I am creating a tool to automate some tasks. These tasks generate two DataFrames, but when concatenating them the columns are messed up as follows:
col2 col4 col3 col1
0 A 2 0 a
1 A 1 1 B
2 B 9 9 c
3 NaN 8 4 D
4 D 7 2 e
5 C 4 3 F
Bu... | [
"use following code:\ndf.sort_index(axis=1)\n\n",
"You can do:\ndf = df[sorted(df.columns.tolist())].copy()\n\n",
"df = df[['col1', 'col2', 'col3', 'col4']]\n\n"
] | [
1,
0,
0
] | [] | [] | [
"data_science",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074644592_data_science_pandas_python_python_3.x.txt |
Q:
Why is a simple in-place addition much faster with numba than numpy?
According to the snippet below, performing an in-place addition with a numba jit-compiled function is ~10 times faster than with numpy's ufunc.
This would be understandable with a function performing multiple numpy operations as explained in this... | Why is a simple in-place addition much faster with numba than numpy? | According to the snippet below, performing an in-place addition with a numba jit-compiled function is ~10 times faster than with numpy's ufunc.
This would be understandable with a function performing multiple numpy operations as explained in this question.
But here the improvement concern 1 simple numpy ufunc...
So why... | [
"The ufunc.add.at() is much more generic then your addat(). It iterates over the array elements and calls some unit operation function for each element. Let the unit operation function be add_vectors(). It adds two input vectors, where a vector means array elements in C-contiguous order and aligned. It utilizes SIM... | [
1
] | [] | [] | [
"numba",
"numpy",
"python"
] | stackoverflow_0074640730_numba_numpy_python.txt |
Q:
Get specific data from dictionary generated from yaml
I have a yaml that I need to process with a python script, the yaml is something like this:
user: john
description: Blablabla
version: 1
data:
data1: {type : bool, default: 0, flag: True}
data2: {type : bool, default: 0, flag: True}
data3: {type : float, de... | Get specific data from dictionary generated from yaml | I have a yaml that I need to process with a python script, the yaml is something like this:
user: john
description: Blablabla
version: 1
data:
data1: {type : bool, default: 0, flag: True}
data2: {type : bool, default: 0, flag: True}
data3: {type : float, default: 0, flag: false}
I need a list the the names of all ... | [
"You can use the type() function to check the type of an object in Python. In this case, x['data'] returns a dictionary, so you can use the items() method to get the items in the dictionary and then iterate over them to check their values. Here's an example of how you can do this:\n# Get the items in the 'data' dic... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"yaml"
] | stackoverflow_0074644248_python_python_3.x_yaml.txt |
Q:
How to display all returned photos on a kivy app using python
I am making a project involving looking up images. I decided to use kivy, creating a system where you can input a name of a folder (located in a specific directory) into a search bar, and it will return all images inside said folder tagged '.jpg'. I am ... | How to display all returned photos on a kivy app using python | I am making a project involving looking up images. I decided to use kivy, creating a system where you can input a name of a folder (located in a specific directory) into a search bar, and it will return all images inside said folder tagged '.jpg'. I am stuck with updating the window to display these images, and I can't... | [
"Your submit() method is creating Image widgets and adding them to a newly created layout2, You are returning that new layout2 from that method, but that does not add it to your GUI. Try replacing:\nlayout2.add_widget(self.img)\n\nwith:\nself.root.add_widget(self.img)\n\n"
] | [
0
] | [] | [] | [
"image",
"kivy",
"kivymd",
"python"
] | stackoverflow_0074644180_image_kivy_kivymd_python.txt |
Q:
changing an iterative function into a recursive one
def itr(n):
s = 0
for i in range(0, n+1):
s = s + i * i
return s
This is a simple iterative function that i would like to change into a recursive function.
def rec(n):
import math
if n!=0:
s=n-(2*math.sqrt(n))
if s!... | changing an iterative function into a recursive one | def itr(n):
s = 0
for i in range(0, n+1):
s = s + i * i
return s
This is a simple iterative function that i would like to change into a recursive function.
def rec(n):
import math
if n!=0:
s=n-(2*math.sqrt(n))
if s!=0:
return(s+rec(n))
else:
... | [
"def recursive(total, n):\n if n == 0:\n return total\n else:\n return recursive(total + n * n, n - 1)\n\nA couple of thought\n\nThis can be refactored to using only a single argument, but by supplying both the total and the current iteration count, it is easier to see how to transform the itera... | [
0
] | [] | [] | [
"loops",
"python",
"recursion"
] | stackoverflow_0074644545_loops_python_recursion.txt |
Q:
If I'm printing (0,n) in a for loop, how do i make the program print the last number?
I'm coding a simple for loop to print out all the numbers of a user inputted n using this code:
if __name__ == '__main__':
n = int(input())
for i in range (1,n):
print(i, end=" ")
I expected a result like:
Input... | If I'm printing (0,n) in a for loop, how do i make the program print the last number? | I'm coding a simple for loop to print out all the numbers of a user inputted n using this code:
if __name__ == '__main__':
n = int(input())
for i in range (1,n):
print(i, end=" ")
I expected a result like:
Input:
5
Output:
1 2 3 4 5
but instead, I am getting this output:
1 2 3 4
| [
"Just add 1. The range function, when used as range(start, stop), does not include stop, and it stops when the next number is greater than or equal to stop.\nif __name__ == '__main__':\n n = int(input())\n for i in range(1,n + 1):\n print(i, end=\" \")\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074644680_python.txt |
Q:
How to summarise multiple arrays from one df row into one array?
How do I "extract" a row from a dataframe containing multiple arrays and transfer it into a single array?
data = numpy.array([([6,5,6], [2,6,3], [3,4,5]), ([0,9,4], [7,6,5], [8,2,4]), (1,3,5)])
df = pd.DataFrame(data)
print(df)
target1 = [6,5,6,2,6,... | How to summarise multiple arrays from one df row into one array? | How do I "extract" a row from a dataframe containing multiple arrays and transfer it into a single array?
data = numpy.array([([6,5,6], [2,6,3], [3,4,5]), ([0,9,4], [7,6,5], [8,2,4]), (1,3,5)])
df = pd.DataFrame(data)
print(df)
target1 = [6,5,6,2,6,3,3,4,5]
target2 = [0,9,4,7,6,5,8,2,4]
print(target, target2)
| [
"\nExtract the row using whichever method you prefer and save it as a list\nUse any of these methods to flatten your list\n\nrow = list(df.loc[0])\ntarget = [val for val in sublist for sublist in row]\n\n"
] | [
1
] | [] | [] | [
"arrays",
"pandas",
"python"
] | stackoverflow_0074644621_arrays_pandas_python.txt |
Q:
Get a Spark dataframe field into a String value
I am currently trying to filter my dataframe into an if and get the field returned into variable.
Here is my code:
if df_table.filter(col(field).contains("val")):
id_2 = df_table.select(another_field)
print(id_2)
# Recursive call with new variable
The probl... | Get a Spark dataframe field into a String value | I am currently trying to filter my dataframe into an if and get the field returned into variable.
Here is my code:
if df_table.filter(col(field).contains("val")):
id_2 = df_table.select(another_field)
print(id_2)
# Recursive call with new variable
The problem is : it looks like the if filtering works, but id_... | [
"In fact, dataFrame.select(colName) is supposed to return a column(a dataframe of with only one column) but not the column value of the line. I see in your comment you want to do recursive lookup in a spark dataframe. The thing is, firstly, spark AFAIK, doesn't support recursive operation. If you have a deep recurs... | [
0
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"pyspark",
"python"
] | stackoverflow_0074630297_apache_spark_apache_spark_sql_pyspark_python.txt |
Q:
numpy-equivalent of list.pop?
Is there a numpy method which is equivalent to the builtin pop for python lists?
Popping obviously doesn't work on numpy arrays, and I want to avoid a list conversion.
A:
There is no pop method for NumPy arrays, but you could just use basic slicing (which would be efficient since i... | numpy-equivalent of list.pop? | Is there a numpy method which is equivalent to the builtin pop for python lists?
Popping obviously doesn't work on numpy arrays, and I want to avoid a list conversion.
| [
"There is no pop method for NumPy arrays, but you could just use basic slicing (which would be efficient since it returns a view, not a copy):\nIn [104]: y = np.arange(5); y\nOut[105]: array([0, 1, 2, 3, 4])\n\nIn [106]: last, y = y[-1], y[:-1]\n\nIn [107]: last, y\nOut[107]: (4, array([0, 1, 2, 3]))\n\nIf there we... | [
30,
20,
6,
6,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"arrays",
"list",
"numpy",
"python",
"stack"
] | stackoverflow_0039945410_arrays_list_numpy_python_stack.txt |
Q:
group rows based on column and sum their values
df = pd.DataFrame({'c1':['Ax','Bx','Ay','By'], 'c2':[1,2,3,4]})
c1 c2
0 Ax 1
1 Bx 2
2 Ay 3
3 By 4
I'd like to group xs and ys in c1 and sum their respective c2 values.
Desired output:
c1 c2
0 Cx 3
1 Cy 7
A:
example
df.groupby(df['c1'].str[-1])... | group rows based on column and sum their values | df = pd.DataFrame({'c1':['Ax','Bx','Ay','By'], 'c2':[1,2,3,4]})
c1 c2
0 Ax 1
1 Bx 2
2 Ay 3
3 By 4
I'd like to group xs and ys in c1 and sum their respective c2 values.
Desired output:
c1 c2
0 Cx 3
1 Cy 7
| [
"example\ndf.groupby(df['c1'].str[-1]).sum()\n\noutput:\n c2\nc1 \nx 3\ny 7\n\nuse following code:\ndf.groupby('C' + df['c1'].str[-1]).sum().reset_index()\n\nresult:\n c1 c2\n0 Cx 3\n1 Cy 7\n\n",
"You may do:\nout = df.groupby(df.c1.str[-1]).sum().reset_index()\nout['c1'] = 'C' + out['c1']\n\npr... | [
2,
1,
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074644651_pandas_python.txt |
Q:
Failed to create virtual environment in PyCharm
I have problem with create virtual environment in PyCharm.
Exactly, Python in version 3.10 was add to Path during installation and I use latest version PyCharm community.
Did anyone have a similar problem?
Adding Informations
How I create environment :
file -> New ... | Failed to create virtual environment in PyCharm | I have problem with create virtual environment in PyCharm.
Exactly, Python in version 3.10 was add to Path during installation and I use latest version PyCharm community.
Did anyone have a similar problem?
Adding Informations
How I create environment :
file -> New project
Location : D:\mm\projekty\pythonProject2
m... | [
"I had the same problem. I needed to install package python3-venv.\n",
"In order to fix this, I had to run from my terminal:\npip install virtualenv\n\nAfter installing the virtualenv package everything works as expected.\n",
"If you have python3-env already installed, the commands provided in most of the answe... | [
22,
19,
10,
7,
6,
4,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"pycharm",
"python",
"virtualenv"
] | stackoverflow_0069709251_pycharm_python_virtualenv.txt |
Q:
Extract mail from Each value in a Column in a Dataframe
Create a function that evaluates the data within a cell and extracts only the email, place the value found in a new column called "Email Found".
This is the Code I'm using, it work if I use it with a single str, but it doesn't work for my DataFrame
import re
... | Extract mail from Each value in a Column in a Dataframe | Create a function that evaluates the data within a cell and extracts only the email, place the value found in a new column called "Email Found".
This is the Code I'm using, it work if I use it with a single str, but it doesn't work for my DataFrame
import re
def extract_mail(text):
match = re.search(r'[\w.+-]+@[\w... | [
"IIUC, try this using the str accessor with extract method and your regex:\ndf['email'] = df['info'].str.extract('([\\w.+-]+@[\\w-]+\\.[\\w.-]+)')\ndf['Email Found'] = df['email'].notna()\n\noutput:\n info \\\n0 Maxwell <maxwell_hamilton557388853@nimogy.biz>... \n1... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"text_extraction"
] | stackoverflow_0074644673_dataframe_pandas_python_text_extraction.txt |
Q:
What is wrong with the convert function?
def main():
askForTime = input("What time is it? ").strip().split()
time = convert(askForTime)
if 7 <= time <= 8:
print("breacfast time")
elif 12 <= time <= 13:
print("lunch time")
elif 18 <= time <= 19:
print("dinner time")
def ... | What is wrong with the convert function? | def main():
askForTime = input("What time is it? ").strip().split()
time = convert(askForTime)
if 7 <= time <= 8:
print("breacfast time")
elif 12 <= time <= 13:
print("lunch time")
elif 18 <= time <= 19:
print("dinner time")
def convert(clock):
if "p.m" in clock or "pm... | [
"Inspect the askForTime value you get from this line:\ndef main():\n askForTime = input(\"What time is it? \").strip().split()\n\nWhen you do, you will discover that it is returning the input as a list. (That's because you used .split() - the return is a list.) Your convert() function \"works\" because it expec... | [
0
] | [] | [] | [
"cs50",
"decimal",
"python",
"type_conversion"
] | stackoverflow_0074635140_cs50_decimal_python_type_conversion.txt |
Q:
f-string like behaviour with explicit format method
With f-string I can do like this:
a = 10
f'a equals {a}' # 'a equals 10'
f'b equals {a - 1}' # 'b equals 9'
but when using .format I cannot do any operation on the variable:
'b equals {a - 1}'.format(dict(a=10)) # KeyError: 'a - 1'
The error message is cle... | f-string like behaviour with explicit format method | With f-string I can do like this:
a = 10
f'a equals {a}' # 'a equals 10'
f'b equals {a - 1}' # 'b equals 9'
but when using .format I cannot do any operation on the variable:
'b equals {a - 1}'.format(dict(a=10)) # KeyError: 'a - 1'
The error message is clear - the format function treats everything in the {} as a... | [
"When using format, the {} are a place holder for an expression. Do the arithmetic in the format argument, not in the place holder.\nstr = \"a = {}\"\na = 10\nstra = str.format(a-1)\nprint(stra)\n>> a = 9\n\n"
] | [
1
] | [] | [] | [
"f_string",
"python"
] | stackoverflow_0074644395_f_string_python.txt |
Q:
regular expression in Python to update string in a file
Anything that starts with <a class=“rms-req-link” href=“https://rms. AND ends with </a> should be replaced by TBD.
Example:
<a class=“req-link” href=“https://doc.test.com/req_view/ABC-3456">ABC-3456</a>
or:
<a class=“req-link” href=“https://doc.test.com/req... | regular expression in Python to update string in a file | Anything that starts with <a class=“rms-req-link” href=“https://rms. AND ends with </a> should be replaced by TBD.
Example:
<a class=“req-link” href=“https://doc.test.com/req_view/ABC-3456">ABC-3456</a>
or:
<a class=“req-link” href=“https://doc.test.com/req_view/ABC-1234">ABC-1234</a>
Such strings should be replaced... | [
"As mentioned in the comments, the pattern you mention does not match the one you use in your code, nor does it correspond to the example strings you want replaced. So you may or may not want to adjust the following pattern depending on what you actually need.\nimport re\nfrom pathlib import Path\n\n\nPATTERN = re.... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074644465_python_regex.txt |
Q:
Hi, sorry, I ran into this problem while coding, please help me
sen=(input('lotfan sen khod ra vared konid :'))
if sen > 40:
print('pirshodiiiiii')
elif sen >=30 and sen <=40:
print('mian sal hasti')
elif sen >=20 and sen<=30:
print('hanoz javani')
elif sen >=15 and sen <=20:
print('nojavan hasti')... | Hi, sorry, I ran into this problem while coding, please help me | sen=(input('lotfan sen khod ra vared konid :'))
if sen > 40:
print('pirshodiiiiii')
elif sen >=30 and sen <=40:
print('mian sal hasti')
elif sen >=20 and sen<=30:
print('hanoz javani')
elif sen >=15 and sen <=20:
print('nojavan hasti')
elif sen >=10 and sen <=15:
print('kodak hasti')
else:
print... | [
"input returns a str\nsen = input('lotfan sen khod ra vared konid :')\n\nYou can convert it to an int for your comparisons\nsen = int(input('lotfan sen khod ra vared konid :'))\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074644909_python.txt |
Q:
Python sys package not available in conda?
I am trying to install the python sys package in my conda 4.13.0 environment on MX-Linux:
conda install sys
The answer is:
PackagesNotFoundError: The following packages are not available from current channels:
- sys
Current channels:
- https://repo.anaconda.com/pk... | Python sys package not available in conda? | I am trying to install the python sys package in my conda 4.13.0 environment on MX-Linux:
conda install sys
The answer is:
PackagesNotFoundError: The following packages are not available from current channels:
- sys
Current channels:
- https://repo.anaconda.com/pkgs/main/linux-64
- https://repo.anaconda.com/p... | [
"The sys package is part of python's standard library, which means it comes with python and does not need installed separately.\n"
] | [
0
] | [] | [] | [
"conda",
"python",
"sys"
] | stackoverflow_0074643892_conda_python_sys.txt |
Q:
apply_along_axis with various variables
I have a cooccurrence matrix, a symmetric matrix (Numpy Array) in which each cell indicates the frequency of two co-occurring words.
In this matrix, I want to calculate the association strength. Which is defined as the number of times word i and j co-occur, divided by the pr... | apply_along_axis with various variables | I have a cooccurrence matrix, a symmetric matrix (Numpy Array) in which each cell indicates the frequency of two co-occurring words.
In this matrix, I want to calculate the association strength. Which is defined as the number of times word i and j co-occur, divided by the product of i- and j's total frequency:
def calc... | [
"IIUC you want to row- and columnwise divide each element of coor by word_occurrences. This can be done by simple elementwise division and broadcasting:\nimport numpy as np\n\ncooc = np.array([[0, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1], [0, 1, 1, 0]])\nword_occurrences = [1, 2, 3, 4]\n\ncooc / word_occurrences / np.a... | [
0
] | [] | [] | [
"apply",
"numpy",
"python"
] | stackoverflow_0074643395_apply_numpy_python.txt |
Q:
Detect whether to fetch from psycopg2 cursor or not?
Let's say if I execute the following command.
insert into hello (username) values ('me')
and I ran like
cursor.fetchall()
I get the following error
psycopg2.ProgrammingError: no results to fetch
How can I detect whether to call fetchall() or not without check... | Detect whether to fetch from psycopg2 cursor or not? | Let's say if I execute the following command.
insert into hello (username) values ('me')
and I ran like
cursor.fetchall()
I get the following error
psycopg2.ProgrammingError: no results to fetch
How can I detect whether to call fetchall() or not without checking the query is "insert" or "select"?
Thanks.
| [
"Look at this attribute:\ncur.description\n\nAfter you have executed your query, it will be set to None if no rows were returned, or will contain data otherwise - for example:\n(Column(name='id', type_code=20, display_size=None, internal_size=8, precision=None, scale=None, null_ok=None),)\n\nCatching exceptions is ... | [
31,
4,
2,
0,
0
] | [] | [] | [
"psycopg2",
"python"
] | stackoverflow_0038657566_psycopg2_python.txt |
Q:
How to get name of function that executed code?
Let's say for example I have this fuction:
def example(foo:str="bar"):
# code
How do I get the name of the function (for this, "example") that executed the code, something like this:
def example(foor:str="bar"):
print(functions.get()["name"]) # prints "example"
... | How to get name of function that executed code? | Let's say for example I have this fuction:
def example(foo:str="bar"):
# code
How do I get the name of the function (for this, "example") that executed the code, something like this:
def example(foor:str="bar"):
print(functions.get()["name"]) # prints "example"
I looked at the inspect modules and the examples but... | [
"Did you mean something like this:\ndef example():\n pass\n\na = []\na.append(example)\n\n# What is a[0]'s name?\nprint(a[0].__name__)\n\nAs en element of the list a, we don't know the function's name. But by calling the __name__ attribute, I get the associated string.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074644299_python_python_3.x.txt |
Q:
Optimize applying a conditional filter to pandas dataframe for large input list
I have a large (>3 million rows) pandas dataframe that I'd like to apply a single condition (a simple greater than less than) to a large number of inputs. I'd skip the "new_df" step below, but putting it here for clarity.
For example:
... | Optimize applying a conditional filter to pandas dataframe for large input list | I have a large (>3 million rows) pandas dataframe that I'd like to apply a single condition (a simple greater than less than) to a large number of inputs. I'd skip the "new_df" step below, but putting it here for clarity.
For example:
df = pd.DataFrame({"X":[0,2,3,6,13],
"Y":[10,12,16,8,22]})
input ... | [
"Of course, you can parallelize all available cores of your CPU. I use the convenient and simple parallelbar library. The idea is simple. Create a function that returns a list of indexes. Run this function on a thread pool and pass a list of inputs to the pool.\nimport pandas as pd\nimport numpy as np\nfrom paralle... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074644336_dataframe_pandas_python.txt |
Q:
Python-setattr pass function with args
I'm trying to set methods of a class programmatically by calling setattr in a loop, but the reference I pass to the function that is called by this method defaults back to its last value, instead of what was passed at the time of the setattrcall. Curiously, I'm also setting t... | Python-setattr pass function with args | I'm trying to set methods of a class programmatically by calling setattr in a loop, but the reference I pass to the function that is called by this method defaults back to its last value, instead of what was passed at the time of the setattrcall. Curiously, I'm also setting the __doc__ attribute and this assignment act... | [
"Methods are class attributes, so some_func needs to be attached to type(self), not self itself.\nclass Foo:\n\n def __init__(self):\n self.reference = \"ti-hihi\"\n self.foo2 = Foo2()\n for (method_name, pass_this) in [(\"bar\", \"passed-for-bar\"), (\"bar2\", \"passed-for-bar2\")]:\n ... | [
0,
0
] | [] | [] | [
"class",
"lambda",
"python",
"setattr"
] | stackoverflow_0074644762_class_lambda_python_setattr.txt |
Q:
python module dlls
Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by ov... | python module dlls | Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules ... | [
"If you're talking about Python module DLLs, then simply modifying sys.path should be fine. However, if you're talking about DLLs linked against those DLLs; i.e. a libfoo.dll which a foo.pyd depends on, then you need to modify your PATH environment variable. I wrote about doing this for PyGTK a while ago, but in ... | [
32,
15,
7,
0,
0,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0000214852_module_python.txt |
Q:
Multiple choice in model
ANIMALS = (('dog','dog'), ('cat','cat'))
class Owner(models.Model):
animal = models.Charfield(choices=ANIMALS, max_length=10)
My problem is how I can do if I have both ?
A:
your need to have model like this:
class Choices(models.Model):
animal = models.CharField(max_length=20)
c... | Multiple choice in model | ANIMALS = (('dog','dog'), ('cat','cat'))
class Owner(models.Model):
animal = models.Charfield(choices=ANIMALS, max_length=10)
My problem is how I can do if I have both ?
| [
"your need to have model like this:\nclass Choices(models.Model):\n animal = models.CharField(max_length=20)\n\nclass Owner(models.Model):\n animal = models.ManyToManyField(Choices)\n\n",
"Presumably your best solution is to think about how you are going to store the data at a database level. This will dictat... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074644492_django_python.txt |
Q:
Renaming Anytree Parent and Child Name
I have a dataset as follows
Unique Name
Parent
Child
US_SQ
A
A1
UC_LC
A
A2
UK_SJ
A2
A21
UI_QQ
B
B1
Now I want to set the output as follows:
US_SQ
├── A1
└── UC_LC
└── UK_SJ
UI_QQ
└── B1
In other words, I want to use the Unique name column value in the tree.
This i... | Renaming Anytree Parent and Child Name | I have a dataset as follows
Unique Name
Parent
Child
US_SQ
A
A1
UC_LC
A
A2
UK_SJ
A2
A21
UI_QQ
B
B1
Now I want to set the output as follows:
US_SQ
├── A1
└── UC_LC
└── UK_SJ
UI_QQ
└── B1
In other words, I want to use the Unique name column value in the tree.
This is the code that I am using:
def ... | [
"There are two parts to your question.\n1. Renaming the Node\nRegarding renaming the node by using Unique Name as the alias for Parent name, the above answer on aliasDict is good but we can modify the DataFrame directly instead, leaving your code unchanged.\nI have modified your DataFrame because it does not seem t... | [
2
] | [] | [] | [
"anytree",
"python",
"tree",
"treeview"
] | stackoverflow_0074622229_anytree_python_tree_treeview.txt |
Q:
Why the packages object-hash and crypto / hashlib return different values for sha1?
I have a javascript frontend which compares two object-hash sha1 hashes in order to determine if an input has changed (in which case a processing pipeline needs to be reran).
I started building a python interface to interact with t... | Why the packages object-hash and crypto / hashlib return different values for sha1? | I have a javascript frontend which compares two object-hash sha1 hashes in order to determine if an input has changed (in which case a processing pipeline needs to be reran).
I started building a python interface to interact with the same backend which uses hashlib for the sha1 generation, but unfortunately the two fun... | [
"It turns out that object-hash prefixes the variable for hashing with its type. In the case of strings I needed to add string:{string_length}: to the hash stream.\nhash = hashlib.sha1()\n\nhash.update(f'string:{len(json_data)}:'.encode('utf-8')) # The line in question\n\nhash.update(json_data)\nres = hash.hexdigest... | [
0
] | [] | [] | [
"hashlib",
"javascript",
"node.js",
"object_hash",
"python"
] | stackoverflow_0074633334_hashlib_javascript_node.js_object_hash_python.txt |
Q:
Found array with 0 feature(s) (shape=(10792, 0)) while a minimum of 1 is required
Hey I am using Jupitor Notebook and doing machine learning.
I wrote this code but getting this error and I dont know what is the error.
This is my code for reference:
f`rom sklearn.experimental import enable_iterative_imputer
from sk... | Found array with 0 feature(s) (shape=(10792, 0)) while a minimum of 1 is required | Hey I am using Jupitor Notebook and doing machine learning.
I wrote this code but getting this error and I dont know what is the error.
This is my code for reference:
f`rom sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
imp = IterativeImputer(random_state=42)
date = p... | [
"This is not how for loops work in Python.\nfor col in combi:\n if combi[col].dtype==\"object\":\n # ...\n\ncol isn't an index into the collection you're iterating over (combi), it is the dereferenced element itself. Change all instances of combi[col] inside your for loop to col to correct. Example:\nfor ... | [
0
] | [] | [] | [
"jupyter_notebook",
"kaggle",
"python",
"scikit_learn",
"seaborn"
] | stackoverflow_0074644908_jupyter_notebook_kaggle_python_scikit_learn_seaborn.txt |
Q:
Random Numbers in Excel into percentage
Hi my code works fine but is there any way to print how many times numbers 1-6 were said into a percentage
I haven't tried anything yet.
import pandas as pd
import random
data = [random.randint(0,6) for _ in range(10)]
df = pd.DataFrame(data)
print(df)
df.to_excel(r'H:\G... | Random Numbers in Excel into percentage | Hi my code works fine but is there any way to print how many times numbers 1-6 were said into a percentage
I haven't tried anything yet.
import pandas as pd
import random
data = [random.randint(0,6) for _ in range(10)]
df = pd.DataFrame(data)
print(df)
df.to_excel(r'H:\Grade10\Cs\Mir Hussain 12.00.00 3.xlsx', index... | [
"So from your data you could do:\nimport random\nfrom collections import Counter\n\n\ndata = [random.randint(0,6) for _ in range(10)]\ntotal_data = [data]\n\nfrequency = Counter(data)\nnumber_elements = len(data)\n\ntotal_data.append(list((frequency[item] / number_elements)*100 if item != 0 else '' for item in tota... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074644798_python.txt |
Q:
Adding floats precision
First time encountering floating point arithmetic.
How can I add:
0.4047617913405519 + 250459325658972.0
and choose my presicion?
I get
250459325658972.4
But I want at least
250459325658972.405
Why is python doing that. Any further resources?
A:
I think what you are looking for is the ... | Adding floats precision | First time encountering floating point arithmetic.
How can I add:
0.4047617913405519 + 250459325658972.0
and choose my presicion?
I get
250459325658972.4
But I want at least
250459325658972.405
Why is python doing that. Any further resources?
| [
"I think what you are looking for is the Decimal module:\n>>> from decimal import *\n>>> getcontext().prec = 6\n>>> Decimal(1) / Decimal(7)\nDecimal('0.142857')\n>>> getcontext().prec = 28\n>>> Decimal(1) / Decimal(7)\nDecimal('0.1428571428571428571428571429')\n\nIt gives complete control on the precision of your o... | [
1
] | [
"Use this\nprint(\"{0:.4f}\".format(250459325658972.0 +0.4047617913405519))\n\n"
] | [
-2
] | [
"floating_point",
"python"
] | stackoverflow_0074644755_floating_point_python.txt |
Q:
ANACONDA navigator cannot launch-from win32com.shell import shellcon, shell
I have downloaded the ANACONDA(Anaconda3-2020.02-Windows-x86) and installed. However, i found that i cannot lauch the ANACONDA navigator so i tried using the command line and got its feedback.
from win32com.shell import shellcon,shell
Im... | ANACONDA navigator cannot launch-from win32com.shell import shellcon, shell | I have downloaded the ANACONDA(Anaconda3-2020.02-Windows-x86) and installed. However, i found that i cannot lauch the ANACONDA navigator so i tried using the command line and got its feedback.
from win32com.shell import shellcon,shell
Import Error:DLL load failed: The specified moduld could not found.
***(base) C:\W... | [
"Had exactly the same issue and solved it by installing the latest of win32com.\npip install pywin32==301\n\n",
"I had the same issue:\nfrom win32com.shell import shellcon, shell\n ImportError: DLL load failed: The specified module could not be found.***\n\nI fixed mine by clearing my environment variable call... | [
5,
4,
1,
0
] | [] | [] | [
"anaconda",
"python"
] | stackoverflow_0061382692_anaconda_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.