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:
Average of an uarray in python uncertainties
My problem:
I have an array of ufloats (e.g. an unarray) in pythons uncertainties package.
All values of the array got their own errors, and I need a funktion, that gives me the average of the array in respect to both, the error
I get when calculating the mean of the no... | Average of an uarray in python uncertainties | My problem:
I have an array of ufloats (e.g. an unarray) in pythons uncertainties package.
All values of the array got their own errors, and I need a funktion, that gives me the average of the array in respect to both, the error
I get when calculating the mean of the nominal values and the influence the values errors ... | [
"Assuming Gaussian statistics, the uncertainties stem from Gaussian parent distributions. In such a case, it is standard to weight the measurements (nominal values) by the inverse variance. This application to the general weighted average gives,\n$$ \\frac{\\sum_i w_i x_i}{\\sum_i w_i} = \\frac{\\sum_i x_i/\\sigma_... | [
3,
1,
0,
0
] | [] | [] | [
"arrays",
"python",
"uncertainty"
] | stackoverflow_0043637370_arrays_python_uncertainty.txt |
Q:
Regex match 3 digits followed by 8 digits or just 8 digits, but do not match 3 digits if it is after decimal
I have a string like this:
'''82290574 BB BBBBB 3.0 195.00 3.75 0.00 0.00 0.00 85.00 113.75 21.61 135.36 220811 11.08.2022 00.000
82290600 BB ... | Regex match 3 digits followed by 8 digits or just 8 digits, but do not match 3 digits if it is after decimal | I have a string like this:
'''82290574 BB BBBBB 3.0 195.00 3.75 0.00 0.00 0.00 85.00 113.75 21.61 135.36 220811 11.08.2022 00.000
82290600 BB BBBBB 2.5 375.00 3.13 0.00 0.00 0.00 225.00 153.13 29.09 18... | [
"With your one example, this works:\ns = '''82290574 BB BBBBB 3.0 195.00 3.75 0.00 0.00 0.00 85.00 113.75 21.61 135.36 220811 11.08.2022 00.000\n82290600 BB BBBBB 2.5 375.00 3.13 0.00 0.00 0.00 225.00 153.13 ... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074607791_python_regex.txt |
Q:
SQLAlchemy: How to change a MySQL server system variable using SQLAlchemy?
I want to set the general_log and general_log_file variables using SQLAlchemy, is there a way to do this? I've been Googling around and can't find anything on the topic.
A:
You can execute any raw SQL query which you need (of course you h... | SQLAlchemy: How to change a MySQL server system variable using SQLAlchemy? | I want to set the general_log and general_log_file variables using SQLAlchemy, is there a way to do this? I've been Googling around and can't find anything on the topic.
| [
"You can execute any raw SQL query which you need (of course you have to get appropriate rights in the session). To change a variable run something like this:\n# change variable name and values to what you need\nconnection.execute(\"SET SESSION query_cache_type = OFF\")\n\n",
"As mentioned previously, you could u... | [
5,
0
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0030926998_mysql_python_sqlalchemy.txt |
Q:
Python 3.11 worse optimized than 3.10?
I run this simple loop with Python 3.10.7 and 3.11.0 on Windows 10.
import time
a = 'a'
start = time.time()
for _ in range(1000000):
a += 'a'
end = time.time()
print(a[:5], (end-start) * 1000)
The older version executes in 187ms, Python 3.11 needs about 17000ms. Does 3... | Python 3.11 worse optimized than 3.10? | I run this simple loop with Python 3.10.7 and 3.11.0 on Windows 10.
import time
a = 'a'
start = time.time()
for _ in range(1000000):
a += 'a'
end = time.time()
print(a[:5], (end-start) * 1000)
The older version executes in 187ms, Python 3.11 needs about 17000ms. Does 3.10 realize that only the first 5 chars of a... | [
"TL;DR: you should not use such a loop in any performance critical code but ''.join instead. The inefficient execution appears to be related to a regression during the bytecode generation in CPython 3.11 (and missing optimizations during the evaluation of binary add operation on Unicode strings).\n\nGeneral guideli... | [
16
] | [] | [] | [
"optimization",
"performance",
"python",
"python_3.10",
"python_3.11"
] | stackoverflow_0074605279_optimization_performance_python_python_3.10_python_3.11.txt |
Q:
Operation returned an invalid status 'unauthorized' when deploying Python app
I am following this guide to deploy python app on Azure. https://learn.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python-webapp?view=azure-devops
I was successfully able to clone the repo and authenticated through Github in Az... | Operation returned an invalid status 'unauthorized' when deploying Python app | I am following this guide to deploy python app on Azure. https://learn.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python-webapp?view=azure-devops
I was successfully able to clone the repo and authenticated through Github in Azure Portal Shell.
But I got above error when I tried to deploy the app using the fo... | [
"We need to make sure that all the configurations has been done which building python webapp.\nbelow are few key points where we need to look into:\n\nFor FlaskApp App service looks for App.py which has below content:\n\n\n If application.py\ngunicorn --bind=0.0.0.0 --timeout 600 application:app\n If app.py\ngunico... | [
1,
0,
0
] | [] | [] | [
"azure",
"azure_web_app_service",
"python"
] | stackoverflow_0070015081_azure_azure_web_app_service_python.txt |
Q:
Turtle is moving slow
I created this program but I don't understand why it takes so long to draw the 2 hills of the heart.
I could reduce the numbers at my_turtle_cursor.speed(5) in line 117 and in line 128 as I wanted but there was no change.
When I changed the numbers in my turtle cursor.speed(1) on line 142, th... | Turtle is moving slow | I created this program but I don't understand why it takes so long to draw the 2 hills of the heart.
I could reduce the numbers at my_turtle_cursor.speed(5) in line 117 and in line 128 as I wanted but there was no change.
When I changed the numbers in my turtle cursor.speed(1) on line 142, the speed changed as well.
im... | [
"We can get the performance up, without tracer(), by removing the intentional slowdowns (speed(5)) and drawing less precisely:\nfrom turtle import Screen, Turtle\n\nMESSAGE_FONT = ('Helvetica', 28, 'bold')\n\ndef write_inside_heart():\n turtle.penup()\n turtle.goto(0, 15)\n turtle.pencolor('white')\n tu... | [
0
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074606163_python_python_turtle_turtle_graphics.txt |
Q:
How to make Popen() understand UTF-8 properly?
This is my code in Python:
[...]
proc = Popen(path, stdin=stdin, stdout=PIPE, stderr=PIPE)
result = [x for x in proc.stdout.readlines()]
result = ''.join(result);
Everything works fine, when it's ASCII. When I'm receiving UTF-8 text in stdout the result is unpredicta... | How to make Popen() understand UTF-8 properly? | This is my code in Python:
[...]
proc = Popen(path, stdin=stdin, stdout=PIPE, stderr=PIPE)
result = [x for x in proc.stdout.readlines()]
result = ''.join(result);
Everything works fine, when it's ASCII. When I'm receiving UTF-8 text in stdout the result is unpredictable. In most cases the output is damaged. What is wr... | [
"Have you tried decoding your string, and then combining your UTF-8 strings together? In Python 2.4+ (at least), this can be achieved with\nresult = [x.decode('utf8') for x in proc.stdout.readlines()]\n\nThe important point is that your lines x are sequences of bytes that must be interpreted as representing charac... | [
6,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003927151_python.txt |
Q:
tight_layout cannot make axes height small enough to accommodate all axes decorations
Is not the first time I encounter this problem and my usual workaround is to explicitly define the figure size and avoid using tight_layout all along (see second code example).
However, I find this solution not practical and I wo... | tight_layout cannot make axes height small enough to accommodate all axes decorations | Is not the first time I encounter this problem and my usual workaround is to explicitly define the figure size and avoid using tight_layout all along (see second code example).
However, I find this solution not practical and I would simply like to have the figure getting automatically resized according to its content, ... | [
"Why don't you just auto-scale the figsize argument?\nfrom math import ceil\n\nN=100\n\nfig, axs = plt.subplots( ncols=4, nrows=ceil(N/4), layout='constrained',\n figsize=(3.5 * 4, 3.5 * ceil(N/4)) )\n\nfor (i, var), ax in zip(enumerate(df.iloc[:,:N]), axs.flat):\n ax.set_title(var)\n ... | [
1
] | [] | [] | [
"autoresize",
"matplotlib",
"python"
] | stackoverflow_0055475035_autoresize_matplotlib_python.txt |
Q:
Program returning dictionary with coins for change not recognizing 0.01//0.01 as being 1.0
This code outputs a dictionary containing the number of coins of each type necessary to reach a certain change, while using the least coins possible.
def change(money):
res = {}
coin = 2.0
while coin>=0.01:
... | Program returning dictionary with coins for change not recognizing 0.01//0.01 as being 1.0 | This code outputs a dictionary containing the number of coins of each type necessary to reach a certain change, while using the least coins possible.
def change(money):
res = {}
coin = 2.0
while coin>=0.01:
parcel = money // coin
res[coin] = int(parcel)
money -= parcel * coin
... | [
"As others have stated, it's because of floating-point rounding errors.\nA standard workaround is to represent monetary amounts as integer numbers of the smallest unit (usually the cent) instead of as a float number of dollars/euros/pounds/whatever.\nHere's an alternative implementation of your function that uses i... | [
3,
0
] | [] | [] | [
"dictionary",
"floating_point",
"function",
"math",
"python"
] | stackoverflow_0074604355_dictionary_floating_point_function_math_python.txt |
Q:
Why do I get "ModuleNotFoundError: No module named 'pyperclip'" despite installing it with pip?
I get a "module not found" error when using idle while trying to import pyperclip.
In command terminal as administrator tried to install pyperclip using:
pip install pyperclip
Output was:
Requirement already satisfied... | Why do I get "ModuleNotFoundError: No module named 'pyperclip'" despite installing it with pip? | I get a "module not found" error when using idle while trying to import pyperclip.
In command terminal as administrator tried to install pyperclip using:
pip install pyperclip
Output was:
Requirement already satisfied: pyperclip in c:\users\ john smith\appdata\local\packages\pythonsoftwarefoundation.python.3.9_qbz5n2... | [
"It's possible that you're running two version of Python on your machine. Ex. a 2.7 and a 3.10. If you're on Windows, you can run the command py -0p to list all your python versions and their paths.\nIf you're looking to install pyperclip for a 3+ version of Python, you might want to use pip3 to install it.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074607321_python_python_3.x.txt |
Q:
How to position suptitle
I'm trying to adjust a suptitle above a multi-panel figure and am having trouble figuring out how to adjust the figsize and subsequently position the suptitle.
The problem is that calling plt.suptitle("my title", y=...) to adjust the position of the suptitle also adjusts the figure dimensi... | How to position suptitle | I'm trying to adjust a suptitle above a multi-panel figure and am having trouble figuring out how to adjust the figsize and subsequently position the suptitle.
The problem is that calling plt.suptitle("my title", y=...) to adjust the position of the suptitle also adjusts the figure dimensions. A few questions:
where d... | [
"1. What do figure coordinates mean?\nFigure coordinates go 0 to 1, where (0,0) is the lower left corner and (1,1) is the upper right corner. A coordinate of y=1.05 is hence slightly outside the figure.\n\n2. what is the effect on figure size when specifying y to suptitle?\nSpecifying y to suptitle has no effect wh... | [
93,
53,
12,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0055767312_matplotlib_python.txt |
Q:
Modified assignment problem (more tasks than agents)
Assume that N is the number of agents and M is the number of tasks. The number of tasks is greater than number of agents, i.e. M > N. Each agent must have at least one task. Given rectangular matrix of costs, find the optimal solution (i.e. assign each task to e... | Modified assignment problem (more tasks than agents) | Assume that N is the number of agents and M is the number of tasks. The number of tasks is greater than number of agents, i.e. M > N. Each agent must have at least one task. Given rectangular matrix of costs, find the optimal solution (i.e. assign each task to exactly one agent so each agent has at least one task and t... | [
"This can be formulated as a Minimum Cost Maximum Flow Problem.\nStart with a sink. It connects to the tasks along channels of cost 0 and flow 1. Each task connects to the agents along channels of costs from your matrix and flow 1. Each agent connects to the sink with a channel of flow 1 and cost 0. Agents are ... | [
3,
2
] | [] | [] | [
"algorithm",
"computer_science",
"optimization",
"python"
] | stackoverflow_0074606127_algorithm_computer_science_optimization_python.txt |
Q:
Kivy: How To Limit Simultaneous Touches to One?
I am using Kivy 1.9.1 and Python 3.5.2. My application breaks when more than one touch event is fired before the first has finished processing. I'm looking for some way to either restrict the number of touch events at a given time to one (something like the max_point... | Kivy: How To Limit Simultaneous Touches to One? | I am using Kivy 1.9.1 and Python 3.5.2. My application breaks when more than one touch event is fired before the first has finished processing. I'm looking for some way to either restrict the number of touch events at a given time to one (something like the max_pointers attribute in the HTML5 engine Phaser) or to filte... | [
"I was able to implement this by creating a TouchHandler widget:\nclass TouchHandler(Widget):\n \"\"\" Non-display widget to handle touch order \"\"\"\n instance = None\n\n def __init__(self):\n super().__init__()\n TouchHandler.instance = self\n self.active = None\n\nThen overriding W... | [
0,
0
] | [] | [] | [
"kivy",
"python",
"python_3.x"
] | stackoverflow_0042234075_kivy_python_python_3.x.txt |
Q:
how to change a date format 01oct2012 to 01-10-2012
I have a weird date format in my data. I currently have 01oct2012 and I would like 01-10-2012. Can someone help me change it! Thank you!
I tried using the pd.to_datetime, but I dont think I have the right code.
A:
As mentioned above this question has many answ... | how to change a date format 01oct2012 to 01-10-2012 | I have a weird date format in my data. I currently have 01oct2012 and I would like 01-10-2012. Can someone help me change it! Thank you!
I tried using the pd.to_datetime, but I dont think I have the right code.
| [
"As mentioned above this question has many answers. Taking just 1 date as an example:\nts = pd.to_datetime('01oct2012') produces the timestamp:\nTimestamp('2012-10-01 00:00:00')\nTo convert to the desired format:\nts.strftime('%d-%m-%Y') \n\nyields:\n'01-10-2012'\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074606928_pandas_python.txt |
Q:
how to create score.py file for azure ml
I am new to Azure ML and trying to deploy my model into Azure. My trained model is of classification in which text data is being first processed, then encoded using BERT model and then trained using catBoost. I have already registered my model; however, I am bit confused wi... | how to create score.py file for azure ml | I am new to Azure ML and trying to deploy my model into Azure. My trained model is of classification in which text data is being first processed, then encoded using BERT model and then trained using catBoost. I have already registered my model; however, I am bit confused with the scoring.py script. This is what I using... | [
"You can start debugging from the visual studio code as shown here and deployment sample with score.py.\n%%writefile source_directory/x/y/score.py\nimport joblib\nimport json\nimport numpy as np\nimport os\n\nfrom inference_schema.schema_decorators import input_schema, output_schema\nfrom inference_schema.parameter... | [
0
] | [] | [] | [
"azure_machine_learning_service",
"azure_machine_learning_studio",
"azure_machine_learning_workbench",
"python",
"scoring"
] | stackoverflow_0074576907_azure_machine_learning_service_azure_machine_learning_studio_azure_machine_learning_workbench_python_scoring.txt |
Q:
Python popen() - communicate( str.encode(encoding="utf-8", errors="ignore") ) crashes
Using Python 3.4.3 on Windows.
My script runs a little java program in console, and should get the ouput:
import subprocess
p1 = subprocess.Popen([ ... ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
o... | Python popen() - communicate( str.encode(encoding="utf-8", errors="ignore") ) crashes | Using Python 3.4.3 on Windows.
My script runs a little java program in console, and should get the ouput:
import subprocess
p1 = subprocess.Popen([ ... ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
out, err = p1.communicate(str.encode("utf-8"))
This leads to a normal
'UnicodeDecodeError... | [
"universal_newlines=True enables text mode. Combined with stdout=PIPE, it forces decoding of the child process' output using locale.getpreferredencoding(False) that is not utf-8 on Windows. That is why you see UnicodeDecodeError.\nTo read the subprocess' output using utf-8 encoding, drop universal_newlines=True:\n#... | [
22,
2,
0
] | [] | [] | [
"encoding",
"popen",
"python",
"python_3.x",
"subprocess"
] | stackoverflow_0033283603_encoding_popen_python_python_3.x_subprocess.txt |
Q:
Trouble Using Feature Columns in TensorFlow
I am using the HR Analytics: Employee Promotion Dataset from the following link: https://www.kaggle.com/datasets/arashnic/hr-ana
My goal is to train a tensor flow neural network using this dataset in order to classify whether an employee will be promoted or not. Many of ... | Trouble Using Feature Columns in TensorFlow | I am using the HR Analytics: Employee Promotion Dataset from the following link: https://www.kaggle.com/datasets/arashnic/hr-ana
My goal is to train a tensor flow neural network using this dataset in order to classify whether an employee will be promoted or not. Many of the columns in the dataset are...
numerical value... | [
"Solution: the first dimension of each tensorflow dataset element is supposed to be the batch_size. To do this all you have to do is slightly modify the df_to_dataset method:\n# A utility method to create a tf.data dataset from a Pandas Dataframe\ndef df_to_dataset(df, batch_size=32):\n y = df.pop('is_promoted')... | [
0
] | [] | [] | [
"pandas",
"python",
"scikit_learn",
"tensorflow"
] | stackoverflow_0074607599_pandas_python_scikit_learn_tensorflow.txt |
Q:
Diagonalizing an unitary matrix with numpy doesn't yield orthonormal eigenvectors
I'm trying to diagonalize an unitary matrix using numpy, in particular the numpy.linalg.eig function. Since the matrix is unitary, its eigenvectors are supposed to form an orthonormal basis. However, it seems that this is not the cas... | Diagonalizing an unitary matrix with numpy doesn't yield orthonormal eigenvectors | I'm trying to diagonalize an unitary matrix using numpy, in particular the numpy.linalg.eig function. Since the matrix is unitary, its eigenvectors are supposed to form an orthonormal basis. However, it seems that this is not the case:
import numpy as np
from qiskit.circuit.library import QFT
from qiskit.quantum_info i... | [
"The error in the reasoning comes from this part:\n\nAs a sanity check, I've ensured that v_i and v_j are indeed eigenvectors of op, which means they are correct, and which means they should be orthogonal.\n\nIf v_i and v_j are associated to the same eigenvalue lambda, then (v_i+v_j)/sqrt(2) is an eigenvector assoc... | [
2
] | [] | [] | [
"linear_algebra",
"numpy",
"python"
] | stackoverflow_0074607636_linear_algebra_numpy_python.txt |
Q:
How to correctly use typing for a sort key function
For this sort key method:
def srt(self,r:Optional[Colour])->Optional[int]:
if not isinstance(r,Colour):
return None
return r.index
used in a later method in the same class (NOT Colour):
items=sorted(self.__dict__.values(),key=self.srt)
results in this e... | How to correctly use typing for a sort key function | For this sort key method:
def srt(self,r:Optional[Colour])->Optional[int]:
if not isinstance(r,Colour):
return None
return r.index
used in a later method in the same class (NOT Colour):
items=sorted(self.__dict__.values(),key=self.srt)
results in this error from mypy:
error: Argument "key" to "sorted" has inc... | [
"You are passing a function that returns Optional[int] but a function is required that returns SupportsLessThan. Optional[int] does not support \"less than\", because None cannot be compared to any int.\nWhat does support \"less than\" is just int. So you could change the return type of your function to int and mak... | [
2
] | [] | [] | [
"python",
"python_3.x",
"sorting",
"typing"
] | stackoverflow_0074608046_python_python_3.x_sorting_typing.txt |
Q:
How would I visually graph 2 string type data using python?
I am rather new to coding, and tutorial hell has started to show it's toll. I need help to graph data that are both strings. I have attempted transforming the data using matplotlib, and pandas. However, I seem to not be able to graph them as the ones I ha... | How would I visually graph 2 string type data using python? | I am rather new to coding, and tutorial hell has started to show it's toll. I need help to graph data that are both strings. I have attempted transforming the data using matplotlib, and pandas. However, I seem to not be able to graph them as the ones I have used require int type data.
I have managed to group the data u... | [
"from collections import Counter\nCounter(df['Wafer'])\n\nTo plot the dict result, the follwing link is helpful https://stackoverflow.com/a/52572237/16353662.\n"
] | [
0
] | [] | [] | [
"dataframe",
"google_colaboratory",
"python"
] | stackoverflow_0074607897_dataframe_google_colaboratory_python.txt |
Q:
How to create an array of NA or Null values in Python?
This is easy to do in R and I am wondering if it is straight forward in Python and I am just missing something, but how do you create a vector of NaN values and Null values in Python? I am trying to do this using the np.full function.
R Code:
vec <- vector("c... | How to create an array of NA or Null values in Python? | This is easy to do in R and I am wondering if it is straight forward in Python and I am just missing something, but how do you create a vector of NaN values and Null values in Python? I am trying to do this using the np.full function.
R Code:
vec <- vector("character", 15)
vec[1:15] <- NA
vec
Python Code
unknowns = n... | [
"you could use either None or np.nan to create an array of just missing values in Python like so:\nnp.full(shape=5, fill_value=None)\nnp.full(shape=5, fill_value=np.nan)\n\nback to your example, this works just fine:\nimport numpy as np\nimport pandas as pd\n\nunknowns = np.full(shape=5, fill_value=None)\ncategorie... | [
2,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074607741_numpy_python.txt |
Q:
Infinite looping Issue Python. Can't quit game
I made a code for Blackjack in Python and whenever I run blackjack_game(deck) saying no to the 'Play Again' input should quit the game but it doesn't. Funds going zero and below should also trigger the game to quit but it doesn't.
This is what it looks like:
import ra... | Infinite looping Issue Python. Can't quit game | I made a code for Blackjack in Python and whenever I run blackjack_game(deck) saying no to the 'Play Again' input should quit the game but it doesn't. Funds going zero and below should also trigger the game to quit but it doesn't.
This is what it looks like:
import random
import os
# The Card class definition
class... | [
"Can you please try by replacing from this:\n # Bets\n while play_again == 'Y':\n while end_game == False:\n while funds > 0:\n while bet == 0:\n bet = int(input('Enter bet amount: '))\n\n if bet > funds:\n print('In... | [
0,
0
] | [] | [] | [
"blackjack",
"oop",
"python"
] | stackoverflow_0074574860_blackjack_oop_python.txt |
Q:
How do I push to a nested array in a PyMongo database?
I have a MongoDB database with the following structure (simplified for the question's sake):
User:
"id": int
"aquarium": Aquarium[]
Aquarium:
"name": str
"fish": Fish[]
I have access to:
The database, which contains a list of objects of type User, which in ... | How do I push to a nested array in a PyMongo database? | I have a MongoDB database with the following structure (simplified for the question's sake):
User:
"id": int
"aquarium": Aquarium[]
Aquarium:
"name": str
"fish": Fish[]
I have access to:
The database, which contains a list of objects of type User, which in turn have their own Aquarium objects (users_db)
The unique I... | [
"You get the mentioned problem as you are trying to add an object into the fish array which is a nested array (aquarium is also an array).\nYou need $ operator after aquarium. Aims to update the first matched aquarium array.\n\nMongoDB query\n\ndb.collection.update({\n \"_id\": ObjectId(\"5a934e000102030405000000... | [
1
] | [] | [] | [
"mongodb",
"pymongo",
"python",
"rest"
] | stackoverflow_0074607734_mongodb_pymongo_python_rest.txt |
Q:
module 'pandas._typing' has no attribute 'FilePathOrBuffer'
When trying to import a darts atribute using the line
from darts import TimeSeries, concatenate
i get the error message
AttributeError: module 'pandas._typing' has no attribute 'FilePathOrBuffer'
Is there a fix for this?
Versions of what I'm using:
pan... | module 'pandas._typing' has no attribute 'FilePathOrBuffer' | When trying to import a darts atribute using the line
from darts import TimeSeries, concatenate
i get the error message
AttributeError: module 'pandas._typing' has no attribute 'FilePathOrBuffer'
Is there a fix for this?
Versions of what I'm using:
pandas 1.5.2
Windows 10 64-bit, ver 21H2
Python 3.9.13
darts ver 0.1... | [
"Like yourself, running Windows 10 64-bit, using a sufficiently up to date copy of Python 3.9 (I'm using 3.9.13), if I do the following:\nvirtualenv test_env\ntestenv\\Scripts\\activate\npip install pandas\npip install darts\n\nThis installs a large number of dependencies for darts and takes several minutes to comp... | [
0
] | [] | [] | [
"libraries",
"python"
] | stackoverflow_0074607309_libraries_python.txt |
Q:
How to match one to one data-point based on some conditions
Let's say I have a dataframe that looks like this
df = pd.DataFrame(columns=['ID', 'job', 'eligible', "date"])
df['ID'] = ['1', '2', '3', '4', '5', '6', '7', '8']
df['job'] = ['waitress', 'doctor', 'benevolent', 'nurse', 'hairstylist', 'banker', 'waitress... | How to match one to one data-point based on some conditions | Let's say I have a dataframe that looks like this
df = pd.DataFrame(columns=['ID', 'job', 'eligible', "date"])
df['ID'] = ['1', '2', '3', '4', '5', '6', '7', '8']
df['job'] = ['waitress', 'doctor', 'benevolent', 'nurse', 'hairstylist', 'banker', 'waitress', 'waitress']
df['eligible'] = [No, Yes, No, Yes, No, No, No, No... | [
"This solution uses the groupby method to find rows which share job and eligible values. Subgroups which share the same year are then identified. A random index is selected to choose the ID to assign for the paired_ID.\nimport numpy as np\nimport pandas as pd\n\ndf = pd.DataFrame(columns=['ID', 'job', 'eligible', \... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074607527_pandas_python.txt |
Q:
Function in DolphinDB similar to numpy.clip()
Function numpy.clip() is used to clip(limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [2, 6] is specified, values smaller than 2 become 2, and values larger than 6 become 6.... | Function in DolphinDB similar to numpy.clip() | Function numpy.clip() is used to clip(limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [2, 6] is specified, values smaller than 2 become 2, and values larger than 6 become 6.
import numpy as np
in_array = [1, 2, 3, 4, 5, ... | [
"Function winsorize may work, to some extent, if you can specify the percentages to cut on each side of the vector.\nOr, you can use the user-defined function as follows with iif:\ndef clip(x,minValue,maxValue): iif(x>maxValue,maxValue,iif(x<minValue,minValue,x))\nin = [1, 2, 3, 4, 5, 6, 7, 8 ] \nclip(in,2,6)\n\nOu... | [
0
] | [] | [] | [
"dolphindb",
"numpy",
"python"
] | stackoverflow_0074595836_dolphindb_numpy_python.txt |
Q:
Python Pandas Pivot Table issue with margins : got "Grouper for 'something' not 1-dimensional"
I'm working with a df and a simple pivot table my purpose is to add the margins.
Everything works fine until I add the arg "margins=True".
here is my code :
df1=pd.DataFrame({'brand':['A','A','A','A','A','B','A','B','A',... | Python Pandas Pivot Table issue with margins : got "Grouper for 'something' not 1-dimensional" | I'm working with a df and a simple pivot table my purpose is to add the margins.
Everything works fine until I add the arg "margins=True".
here is my code :
df1=pd.DataFrame({'brand':['A','A','A','A','A','B','A','B','A','B','B','A','A'],
'type':['C','C','C','C','C','C','C','C','D','D','C','C','C'],
'Year':[2022,2022,20... | [
"I think it doesn't like that you use both type as index and value. A workaround would be to use a dummy column:\ntable_1 = pd.pivot_table(df1.assign(val=1), \n values='val', index=['brand','type'],\n columns=['Year','Month'], aggfunc={'val':len},\n ... | [
1
] | [] | [] | [
"margins",
"pandas",
"pivot_table",
"python"
] | stackoverflow_0074607735_margins_pandas_pivot_table_python.txt |
Q:
Django, pandas, excel: uploading files, parsing them with pandas in Django
I have a big command-line script for parsing data in Excel (with pandas) and I want to wrap it with Django. I've tried both uploading files thru request.FILES and pandas, but get stuck on uploading file and, for example, saving it (not nece... | Django, pandas, excel: uploading files, parsing them with pandas in Django | I have a big command-line script for parsing data in Excel (with pandas) and I want to wrap it with Django. I've tried both uploading files thru request.FILES and pandas, but get stuck on uploading file and, for example, saving it (not necessarily but just to check the upload for now).
Haven't had any problems with oth... | [
"I think you must save the form's content actually:\nform.save()\n\n"
] | [
0
] | [] | [] | [
"django",
"django_views",
"pandas",
"python"
] | stackoverflow_0074608110_django_django_views_pandas_python.txt |
Q:
How can I write columns 'name' attribute to excel in Pandas?
df=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df.index.name='class1'
df.columns.name='class2'
df.to_excel('...')
The index name attribute 'class1' can be written normally, but the columns 'name' attribute 'class2' can't. Please note that I am not talking a... | How can I write columns 'name' attribute to excel in Pandas? | df=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df.index.name='class1'
df.columns.name='class2'
df.to_excel('...')
The index name attribute 'class1' can be written normally, but the columns 'name' attribute 'class2' can't. Please note that I am not talking about the columns name 'A and B'. How can I write it?
| [
"Based on the information you have provided, you should try setting the column names with df.columns = ['column name 1', 'column name 2'] and so on before you export. If that answer does not help, could you provide some of the data and commands you are putting in along with the output you are getting? That could be... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074608194_pandas_python.txt |
Q:
Import "parselmouth.praat" could not be resolved
I'm trying to install praat-parselmouth everything is fine when I use Jupyter Notebook.
But when I tried to import this package on the VsCode I got the below error.
I've checked the Python interpreter and it's the same as the installed Python directory. How can I ... | Import "parselmouth.praat" could not be resolved | I'm trying to install praat-parselmouth everything is fine when I use Jupyter Notebook.
But when I tried to import this package on the VsCode I got the below error.
I've checked the Python interpreter and it's the same as the installed Python directory. How can I solve this?
| [
"The solution is given in the link you pasted.\nSometimes on Windows, the installation works, but importing Parselmouth fails with an error message saying . This error is cause by some missing system files, but can luckily be solved quite easily by installing the “Microsoft Visual C++ Redistributable for Visual Stu... | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074601422_python_visual_studio_code.txt |
Q:
"No artists with labels found to put in legend." error when changing the legend size in pyplot
I want to make my legend size bigger in Pyplot. I used this answer to do that. Here is my code.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
plt.rcParams['figure.figsize'] = [15, 7]
... | "No artists with labels found to put in legend." error when changing the legend size in pyplot | I want to make my legend size bigger in Pyplot. I used this answer to do that. Here is my code.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
plt.rcParams['figure.figsize'] = [15, 7]
lst = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,4,5,6]
plt.plot(lst)
plt.legend(fontsize="x-large") # Here I m... | [
"\"Artist\" is a term from matplotlib:\nhttps://matplotlib.org/stable/tutorials/intermediate/artists.html\nPresumably the error message means that there are no items in the legend whose font size can be changed.\nMaybe pass the fontsize argument to the same plt.legend call in which you create the legend, or call pl... | [
1
] | [] | [] | [
"legend",
"matplotlib",
"python"
] | stackoverflow_0074608230_legend_matplotlib_python.txt |
Q:
Statsmodel Multiple Linear Regression Error - Python
I am running (what I think is) as fairly straightforward multiple linear regression model fit using Stats model.
My code is as follows:
y = 'EXITS|20:00:00'
all_columns = "+".join(y_2015piv.columns - ['EXITS|20:00:00'])
reg_formula = "y~" + all_columns
lm= sm... | Statsmodel Multiple Linear Regression Error - Python | I am running (what I think is) as fairly straightforward multiple linear regression model fit using Stats model.
My code is as follows:
y = 'EXITS|20:00:00'
all_columns = "+".join(y_2015piv.columns - ['EXITS|20:00:00'])
reg_formula = "y~" + all_columns
lm= smf.ols(formula=reg_formula, data=y_2015piv).fit()
Because ... | [
"The first error that I got was this:\nPatsyError: numbers besides '0' and '1' are only allowed with **\nTemp ~ MEI+ CO2+ CH4+ N2O+ CFC-11+ CFC-12+ TSI+ Aerosols\n ^^\n\nAccording to this link: http://patsy.readthedocs.io/en/latest/builtins-reference.html#patsy.builtins.Q\nyou can use ... | [
8,
2,
0
] | [] | [] | [
"linear_regression",
"python",
"statsmodels"
] | stackoverflow_0037356559_linear_regression_python_statsmodels.txt |
Q:
How to get a list of built-in modules in python?
I would like to get a list of names of built-in modules in python such that I can test the popularity of function's naming conventions (underline, CamelCase or mixedCase).
I know there is a Global Module Index but I am wondering if there is a list of strings, which ... | How to get a list of built-in modules in python? | I would like to get a list of names of built-in modules in python such that I can test the popularity of function's naming conventions (underline, CamelCase or mixedCase).
I know there is a Global Module Index but I am wondering if there is a list of strings, which is easier to use :)
Update:
len(dir(__builtins__)) = 1... | [
"The compiled-in module names are in sys.builtin_module_names. For all importable modules, see pkgutil.iter_modules.\nRun these in a clean virtualenv to get (almost) only the modules that come with Python itself.\n\nNote that a “popularity poll” will necessarily include modules that use old, discouraged naming conv... | [
56,
24,
15,
7,
5,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008370206_python.txt |
Q:
how to parse "Id"= "name" with python
I'm trying to scrap data from a website which has the below element data. I need the Name, Roll No, Marks and Result status. I'm using this code
student_data = soup.findAll('div', attrs= {'class':'fontLight'})
and
for store in student_data:
name = store.h5.name.text
i ge... | how to parse "Id"= "name" with python | I'm trying to scrap data from a website which has the below element data. I need the Name, Roll No, Marks and Result status. I'm using this code
student_data = soup.findAll('div', attrs= {'class':'fontLight'})
and
for store in student_data:
name = store.h5.name.text
i get error
'NoneType' object has no attribute ... | [
"You can check on the id and value like this:\nfor store in student_data:\n id = store.h5.attrs['id']\n value = store.h5.text\n print(id, value)\n\nThen you can use if statements to check the id's. For example,\nfor store in student_data:\n id = store.h5.attrs['id']\n value = store.h5.text\n if id... | [
1
] | [] | [] | [
"element",
"html",
"parsing",
"python",
"web_scraping"
] | stackoverflow_0074607489_element_html_parsing_python_web_scraping.txt |
Q:
Functions code running, but dont know how to call a certain function
This code is running, but not properly analyzing budget, prompting, or returning values correctly. I am having trouble writing the correct functions. When I run it, it prompts the user for their budget, and amount spent, then does nothing
month =... | Functions code running, but dont know how to call a certain function | This code is running, but not properly analyzing budget, prompting, or returning values correctly. I am having trouble writing the correct functions. When I run it, it prompts the user for their budget, and amount spent, then does nothing
month = 0
months = 0
def DescribeProgram():
print("""\
This program uses a ... | [
"def DescribeProgram():\n \n print(\"\"\"\\\nThis program uses a for loop to monitor your budget.\nThe program will prompt you to enter your budget, and amount spent\nfor a certain month and calculate if your were under or over budget.\nYou will have the option of choosing how many months you would like to\nmonit... | [
0
] | [] | [] | [
"for_loop",
"function",
"loops",
"python",
"while_loop"
] | stackoverflow_0074607852_for_loop_function_loops_python_while_loop.txt |
Q:
How to create a list containing an arithmetic progression?
Here's an example of what I'm trying to achieve:
What I'm tring to do is make the sum of a starting number X, and sum it by Y, and with each sum, add the numbers to a previously empty list:
lst = []
i = -0.5
tot = 0.025
while i <= 100:
tot = tot + i
... | How to create a list containing an arithmetic progression? | Here's an example of what I'm trying to achieve:
What I'm tring to do is make the sum of a starting number X, and sum it by Y, and with each sum, add the numbers to a previously empty list:
lst = []
i = -0.5
tot = 0.025
while i <= 100:
tot = tot + i
i = i + 1
a = tot
print("value: ",tot)
print(a)
lst.append(... | [
"This is really about applying an incrementing multiplier to Y, so it is more suitably implemented by iterating over a range of multipliers.\nTo produce 4 items, for example:\ni = -0.5\ntot = 0.025\nlst = [i + tot * m for m in range(4)]\n\n"
] | [
0
] | [] | [] | [
"append",
"list",
"python"
] | stackoverflow_0074608361_append_list_python.txt |
Q:
How to listen event with Python threading
I'm trying to implement a multi thread program in python and am having troubles.
I try to design a program, when the program (main thread) receives a specific command,
The counter of the program will return to the previous number and continue counting down.
The following i... | How to listen event with Python threading | I'm trying to implement a multi thread program in python and am having troubles.
I try to design a program, when the program (main thread) receives a specific command,
The counter of the program will return to the previous number and continue counting down.
The following is the code I tried to write:
import threading
i... | [
"The threading module has a wait method that will block until notify or notify_all is called. This should accomplish what you're looking for in your first question. For question 2 you can either define a function that handles the exit case, or just recreate a thread to start form the beginning.\n",
"Simply it can... | [
0,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0064474965_multithreading_python.txt |
Q:
Split strings from nested list by delimiter
I'm trying to go from a pandas dataframe series of which the elements are strings with the following format:
'x ± a'
'y ± b'
'z ± c'
I'd like to extract the numbers x,y,z from this series into a numpy array:
X = np.array([x,y,z])
How can I do this?
I tried to turn the ... | Split strings from nested list by delimiter | I'm trying to go from a pandas dataframe series of which the elements are strings with the following format:
'x ± a'
'y ± b'
'z ± c'
I'd like to extract the numbers x,y,z from this series into a numpy array:
X = np.array([x,y,z])
How can I do this?
I tried to turn the series into a nested list, but then I am stuck on... | [
"You can use:\na = pd.to_numeric(df['col'].str.split('±').str[0], errors='coerce').to_numpy()\n\nOr (more efficient):\na = pd.to_numeric(df['col'].str.extract('(.*)\\s*±', expand=False), errors='coerce').to_numpy()\n\nExample output:\narray([10. , 20. , 33.3])\n\nUsed input:\ndf = pd.DataFrame({'col': ['10 ± 1', '2... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074608353_pandas_python.txt |
Q:
\django_school\\manage.py': [Errno 2] No such file or directory
I downloaded pip and django with python -m pip install django, I also downloaded crycrs_forms but when I click to python manage.py runserver it crashes and doesn't run:
How can I fix it?
A:
For better location of packages and files and better manag... | \django_school\\manage.py': [Errno 2] No such file or directory | I downloaded pip and django with python -m pip install django, I also downloaded crycrs_forms but when I click to python manage.py runserver it crashes and doesn't run:
How can I fix it?
| [
"For better location of packages and files and better management, you should use virtual environments.\n\nFirst create a folder (Django) and open it in vscode.\n\nThen use the following command in the terminal to create a new virtual environment (.venv)\npython -m venv .venv\n\n\n\nAfter the command is executed, se... | [
0
] | [] | [] | [
"django",
"python",
"visual_studio_code"
] | stackoverflow_0074601110_django_python_visual_studio_code.txt |
Q:
Writing a for loop in Python checking for divisibility
I am trying to write a program in Python with turtle graphics to create a game. The game is built on blocks hovering in the air, where there is space between some of these blocks. The goal is to move a ball from the left side to the right without falling throu... | Writing a for loop in Python checking for divisibility | I am trying to write a program in Python with turtle graphics to create a game. The game is built on blocks hovering in the air, where there is space between some of these blocks. The goal is to move a ball from the left side to the right without falling through the gaps.
I am experiencing some trouble with writing a f... | [
"It looks like you created draw_blocks incorrectly for what you are trying to do.\nIf you want it to only draw blocks when x is divisible by 2 or 5, you need to draw the block at the position of x times square_size. I've modified your draw_blocks function below, which fixes the issue:\ndef draw_blocks():\n for x... | [
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074606508_for_loop_python.txt |
Q:
comparing two sets and finding equation about them python
I have two sets
list1 = {1,2,3,4,5,6,7,8,9,10}
list2 = {10,20,30,40,50,60,70,80,90,100}
I want python to see if there is a relation between each number and if the relation is the same for each number(for this example it would be the same for each number an... | comparing two sets and finding equation about them python | I have two sets
list1 = {1,2,3,4,5,6,7,8,9,10}
list2 = {10,20,30,40,50,60,70,80,90,100}
I want python to see if there is a relation between each number and if the relation is the same for each number(for this example it would be the same for each number and the relation is *10)or if it is not it would print that they ... | [
"If you use sets, you cannot define a 1-to-1 relationship, as those are unordered.\nIf you have lists, you could use:\nlist1 = [1,2,3,4,5,6,7,8,9,10]\nlist2 = [10,20,30,40,50,60,70,80,90,100]\n\nratios = [b/a for a,b in zip(list1, list2)]\n\nOutput: [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0]\nOr u... | [
0
] | [] | [] | [
"compare",
"list",
"python"
] | stackoverflow_0074608447_compare_list_python.txt |
Q:
How can I create four columns from this 2d list
I'm new into python and pandas and I'm having hard time transforming this 2d list into four independent columns, I'm getting two columns with more than one data for every record. May be I created it the wrong way? I don't know.
Please help me out, I'm trying to make ... | How can I create four columns from this 2d list | I'm new into python and pandas and I'm having hard time transforming this 2d list into four independent columns, I'm getting two columns with more than one data for every record. May be I created it the wrong way? I don't know.
Please help me out, I'm trying to make results look like this:
These are the columns that I'... | [
"import pandas as pd\nresults = [[('three', 'beer'), ('zero', 'wine')], [('one', 'beer'), ('two', 'wine')]]\nPlayer1Qty = []\nPlayer1type = []\nPlayer2Qty = []\nPlayer2type = []\nfor tmp in results:\n Player1Qty.append(tmp[0][0])\n Player1type.append(tmp[0][1])\n Player2Qty.append(tmp[1][0])\n Player2ty... | [
0,
0
] | [] | [] | [
"arraylist",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074608320_arraylist_dataframe_pandas_python.txt |
Q:
Stuck on making a RSS feed discord bot
I'm new to this so please cut me some slack. I'm trying to get RSS feed news into my Discord guild but I hit a bump. I'm using import request to get the feed but I don't know how to have the bot output it in my channel. This is what I have in my bot file to run my bot:
import... | Stuck on making a RSS feed discord bot | I'm new to this so please cut me some slack. I'm trying to get RSS feed news into my Discord guild but I hit a bump. I'm using import request to get the feed but I don't know how to have the bot output it in my channel. This is what I have in my bot file to run my bot:
import hikari
bot = hikari.GatewayBot(token='')
... | [
"If you're trying to output to a specific channel, you need something like this:\nasync def on_ready():\n channel = client.get_channel(channel ID here)\n await channel.send(x.link)\n\nAs for the x.link part, that comes with feedparser, which you can get with import feedparser. You would then get the feed wi... | [
0
] | [] | [] | [
"discord",
"python",
"rss"
] | stackoverflow_0072509695_discord_python_rss.txt |
Q:
subprocess popen + curl + binary data
The following statement works as expected:
os.system("curl --data-binary \@"+input_file_path+" -o "+ file_name +" localhost:30")
But when trying it with subprocess.popen:
Popen(['curl','--data-binary','\@'+input_file_path, '-o', file_name,'localhost:30'], stdout=PIPE).communi... | subprocess popen + curl + binary data | The following statement works as expected:
os.system("curl --data-binary \@"+input_file_path+" -o "+ file_name +" localhost:30")
But when trying it with subprocess.popen:
Popen(['curl','--data-binary','\@'+input_file_path, '-o', file_name,'localhost:30'], stdout=PIPE).communicate()[0]
Curl seems to hang up(logs into ... | [
"how about using a library instead of calling system's curl? \n",
"You could try using the original string in subprocess.Popen with the additional keyword argument to Popen of shell=True:\nsubprocess.Popen(\"curl --data-binary \\@\"+input_file_path+\" -o \"+ file_name +\" localhost:30\",\n stdout=subprocess.PI... | [
3,
2,
0
] | [] | [] | [
"curl",
"popen",
"python"
] | stackoverflow_0002061420_curl_popen_python.txt |
Q:
How can I apply maths to a pandas dataframe comparing 2 specific row and column indexes
I have this dataframe
import pandas as pd
import numpy as np
np.random.seed(2022)
# make example data
close = np.sin(range(610)) + 10
high = close + np.random.rand(*close.shape)
open = high - np.random.rand(*close.shape)
low =... | How can I apply maths to a pandas dataframe comparing 2 specific row and column indexes | I have this dataframe
import pandas as pd
import numpy as np
np.random.seed(2022)
# make example data
close = np.sin(range(610)) + 10
high = close + np.random.rand(*close.shape)
open = high - np.random.rand(*close.shape)
low = high - 3
close[2] += 100
dates = pd.date_range(end='2022-06-30', periods=len(close))
# in... | [
"The first step you want to do can be done by df.loc[\"A\", \"High\"] > df.loc[\"C\", \"Low\"]. To apply this to all rows you could do something like below:\nfor i in range(2, len(df)):\n print(df[\"High\"][i-2] > df[\"Low\"][i])\n\nI'm sure there are better ways to do it, but this would work.\n",
"you can use... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074093315_dataframe_pandas_python.txt |
Q:
How to dynamically name dataframes?
Suppose I have a dataframe as follows:
s = df.head().to_dict()
print(s)
{'BoP transfers': {1998: 12.346282212735618,
1999: 19.06438060024298,
2000: 18.24888031473687,
2001: 24.860019912667006,
2002: 32.38242225822908},
'Current balance': {1998: -6.7953,
1999: -2.9895... | How to dynamically name dataframes? | Suppose I have a dataframe as follows:
s = df.head().to_dict()
print(s)
{'BoP transfers': {1998: 12.346282212735618,
1999: 19.06438060024298,
2000: 18.24888031473687,
2001: 24.860019912667006,
2002: 32.38242225822908},
'Current balance': {1998: -6.7953,
1999: -2.9895,
2000: -3.9694,
2001: 1.1716,
2002... | [
"i = 0\nres = []\nwhile i < df.shape[1]:\n res.append(df.iloc[:, i: (i + 3)])\n i = i + 3\nprint(res[0])\nprint(res[1])\nprint(res[2])\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"slice"
] | stackoverflow_0074608497_dataframe_pandas_python_slice.txt |
Q:
Split one column of a dataframe with xy coordinates into two columns, without a delimeter (every 2 values)
I have a .csv with xy coordinates, which then I read with pandas. The problem is that the .csv has the data in only one column (here, the 1st value is a X value, the 2nd value is a Y value, the 3rd value is a... | Split one column of a dataframe with xy coordinates into two columns, without a delimeter (every 2 values) | I have a .csv with xy coordinates, which then I read with pandas. The problem is that the .csv has the data in only one column (here, the 1st value is a X value, the 2nd value is a Y value, the 3rd value is a X value, and so on) as shown here
This csv is readed with pandas, and the resulting dataframe is in the same fo... | [
"Assuming the number of values is even, you can use:\nout = pd.DataFrame(df.iloc[:,0].to_numpy().reshape(-1,2), columns=['X', 'Y'])\n\nOutput:\n X Y\n0 792.0 610.0\n1 786.0 602.0\n\n"
] | [
0
] | [] | [] | [
"csv",
"multiple_columns",
"pandas",
"python",
"split"
] | stackoverflow_0074608524_csv_multiple_columns_pandas_python_split.txt |
Q:
Removing self-intersection from invalid polygon using python?
I need to union polygons of the shapefile using python.
https://i.stack.imgur.com/qY6gD.png
There are some self-intersection inside polygon and my python code always results in error.
import geopandas as gpd
from shapely.geometry import Polygon
from sha... | Removing self-intersection from invalid polygon using python? | I need to union polygons of the shapefile using python.
https://i.stack.imgur.com/qY6gD.png
There are some self-intersection inside polygon and my python code always results in error.
import geopandas as gpd
from shapely.geometry import Polygon
from shapely.validation import make_valid
from shapely.ops import cascaded_... | [
"This error message indicates the presence of null values:\nNo Shapely geometry can be created from null value\n\nYou must have a None or NaN in your geometry column. This is different from (and possibly in addition to) any issues you may have with self-intersections.\nYou can search for nulls, e.g. with the follow... | [
0
] | [] | [] | [
"geometry",
"geopandas",
"gis",
"python",
"shapely"
] | stackoverflow_0074600665_geometry_geopandas_gis_python_shapely.txt |
Q:
Shampoo cycle loop
I am having trouble figuring out how to stop the loop in my code:
def shampoo_instructions(num_cycles):
for num_cycles in range(1,num_cycles+1):
if num_cycles < 1:
print 'Too few.'
elif num_cycles > 4:
print 'Too many.'
else:
print... | Shampoo cycle loop | I am having trouble figuring out how to stop the loop in my code:
def shampoo_instructions(num_cycles):
for num_cycles in range(1,num_cycles+1):
if num_cycles < 1:
print 'Too few.'
elif num_cycles > 4:
print 'Too many.'
else:
print num_cycles, ': Lather a... | [
"Move your range check to be outside your actual looping, eg:\ndef shampoo_instructions(num_cycles):\n if num_cycles < 1:\n print 'Too few.'\n elif num_cyles > 4:\n print 'Too many.'\n else:\n for num_cycles in range(1,num_cycles+1):\n print num_cycles, 'lather and rinse.'\n... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0026268460_python.txt |
Q:
How do I load a bytes object WAV audio file in torchaudio?
I am trying to load a bytes-class object named "audio" to be loaded as a torchaudio object:
def convert_audio(audio, target_sr: int = 16000):
wav, sr = torchaudio.load(audio)
#(...) some other code
I cannot find any documentation online with i... | How do I load a bytes object WAV audio file in torchaudio? | I am trying to load a bytes-class object named "audio" to be loaded as a torchaudio object:
def convert_audio(audio, target_sr: int = 16000):
wav, sr = torchaudio.load(audio)
#(...) some other code
I cannot find any documentation online with instructions on how to load a bytes audio object inside Torchaud... | [
"If it's WAV format, torchaudio.load should be able to decode it from file-like object. Your code snippet looks good to me.\nThe following tutorial demonstrates it with different file-like objects.\nhttps://pytorch.org/audio/0.13.0/tutorials/audio_io_tutorial.html#loading-from-file-like-object\nStill, there are man... | [
0
] | [] | [] | [
"python",
"torch",
"torchaudio"
] | stackoverflow_0074605909_python_torch_torchaudio.txt |
Q:
Pandas DataFrame applying user defined function only using last row of data from DataFrame
I'm working with a fairly large DataFrame that has multiple columns. It looks something like this:
Date
Temp
Dewpt_Temp
Rainfall (cm)
Snowfall (cm)
12/16/2021
-1.6
-5.4
0
6.7
12/17/2021
-5.5
-12.4
0
0
..........
....
...... | Pandas DataFrame applying user defined function only using last row of data from DataFrame | I'm working with a fairly large DataFrame that has multiple columns. It looks something like this:
Date
Temp
Dewpt_Temp
Rainfall (cm)
Snowfall (cm)
12/16/2021
-1.6
-5.4
0
6.7
12/17/2021
-5.5
-12.4
0
0
..........
....
..........
.............
.............
I have formulas I want to apply to the DataFrame... | [
"Try this:\nnew_df[['e', 'e_s', 'rh']] = data.apply(lambda x: new_vars(x['Temp'], x['Dewpt_Temp']), axis=1)\n\nAnd in the function declaration:\ndef new_vars(temp, dewpt)\n\nAnd delete these two lines:\n temp = dataframe.Temp\n dewpt = dataframe.Dewpt_Temp\n\n",
"Can you try this:\nnew_df = pd.DataFrame()\nne... | [
0,
0,
0
] | [] | [] | [
"apply",
"function",
"pandas",
"python"
] | stackoverflow_0074606026_apply_function_pandas_python.txt |
Q:
Creating Function to Count Values Based on Datetime
I have data that look like this:
activity_date
company_name
new_company_status
calling
visit
quotation
po
03/10/2022
ABC
Yes
Yes
No
No
No
04/10/2022
ABC
No
No
No
Yes
Yes
05/10/2022
DEF
No
Yes
Yes
No
No
06/10/2022
XYZ
Yes
No
Yes
Yes
No
07/10/2022
DEF
No
No
N... | Creating Function to Count Values Based on Datetime | I have data that look like this:
activity_date
company_name
new_company_status
calling
visit
quotation
po
03/10/2022
ABC
Yes
Yes
No
No
No
04/10/2022
ABC
No
No
No
Yes
Yes
05/10/2022
DEF
No
Yes
Yes
No
No
06/10/2022
XYZ
Yes
No
Yes
Yes
No
07/10/2022
DEF
No
No
No
Yes
Yes
08/10/2022
XYZ
No
Yes
No
No
Yes
... | [
"Assuming a pandas dataframe, you can use boolean operations and groupby.any:\nquestion 1\n# define boolean masks\nm1 = df['new_company_status'].eq('Yes')\nm2 = df['calling'].eq('Yes')\n\n# count the number of companies\n# with at least one occurrence of m1 and m2\n(m1&m2).groupby(df['company_name']).any().sum()\n\... | [
0
] | [] | [] | [
"count",
"datetime",
"function",
"python"
] | stackoverflow_0074608543_count_datetime_function_python.txt |
Q:
sum up purchases of current year and month
I need to add the purchases of users in a list with the following conditions:
"Those customers who have a sum of purchases in the current year of 15,000 or more are entitled to a 20% discount. If they have also spent 3000 or more in the current month, they have an additio... | sum up purchases of current year and month | I need to add the purchases of users in a list with the following conditions:
"Those customers who have a sum of purchases in the current year of 15,000 or more are entitled to a 20% discount. If they have also spent 3000 or more in the current month, they have an additional 15%."
The list is the following:
purchases=[... | [
"You can get the current year and month from datetime.date.today() (See Datetime current year and month in Python)\nimport datetime\n\ntoday = datetime.date.today()\n\n# Current year: today.year\n# Current month today.month\n\nIterate over each element of purchases. The \"date\" key in each element tells you the da... | [
1
] | [] | [] | [
"date",
"list",
"python",
"python_3.x"
] | stackoverflow_0074608622_date_list_python_python_3.x.txt |
Q:
Accuracy and loss fluctuating in binary classification problem in deep learning
I'm currently working on a classification problem for stroke on UNet. The task is based the size of the lesion area(large - 1, small - 0). Note that the labels is actually produce by me(I will try to improve it) so they are not that ac... | Accuracy and loss fluctuating in binary classification problem in deep learning | I'm currently working on a classification problem for stroke on UNet. The task is based the size of the lesion area(large - 1, small - 0). Note that the labels is actually produce by me(I will try to improve it) so they are not that accurate. When I trained like 20 epochs, my accuracy waved around 0.5 and loss is aroun... | [
"there are many variances including samples and models to improve the accuracy of binary class-entropy as a single objective. To improves the accuracy first you need to use the correct measurement, the accuracy matric works correctly when you label with 0 to 1 as float since it is binary cross entropy it may reflec... | [
0
] | [] | [] | [
"classification",
"deep_learning",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0074608283_classification_deep_learning_machine_learning_python_tensorflow.txt |
Q:
Printing boolean numpy array without separators
I would like to print this array:
a = np.array([[0, 1, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=bool)
as
.8..
8888
....
....
without iterating over each element in a double loop. A terse function like this one:
def showGrid(g):
print(np.vectorize(l... | Printing boolean numpy array without separators | I would like to print this array:
a = np.array([[0, 1, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=bool)
as
.8..
8888
....
....
without iterating over each element in a double loop. A terse function like this one:
def showGrid(g):
print(np.vectorize(lambda x: '8' if x else '.')(g))
but without standard... | [
"First, use np.where to optimize your current code, which is the same and faster than the function wrapped with np.vectorize:\n>>> np.where(a, '8', '.')\narray([['.', '8', '.', '.'],\n ['8', '8', '8', '8'],\n ['.', '.', '.', '.'],\n ['.', '.', '.', '.']], dtype='<U1')\n\nTo concatenate the charact... | [
3
] | [] | [] | [
"arrays",
"numpy",
"pretty_print",
"python"
] | stackoverflow_0074608633_arrays_numpy_pretty_print_python.txt |
Q:
How to create new column based on average with certain conditions and ignore null in python dataframe?
I have 2 tables
date
James
Jamie
John
Allysia
Jean
2022-01-01
NaN
6
5
4
3
2022-01-02
7
6
7
NaN
5
names
groupings
James
guy
John
guy
Jamie
girl
Allysia
girl
Jean
girl
into
date
James
Jamie
John
Allysia
... | How to create new column based on average with certain conditions and ignore null in python dataframe? | I have 2 tables
date
James
Jamie
John
Allysia
Jean
2022-01-01
NaN
6
5
4
3
2022-01-02
7
6
7
NaN
5
names
groupings
James
guy
John
guy
Jamie
girl
Allysia
girl
Jean
girl
into
date
James
Jamie
John
Allysia
Jean
girl
guy
2022-01-01
NaN
6
5
4
3
5
5
2022-01-02
7
6
7
NaN
5
5.5
7
th... | [
"Assuming df and groupings your two input DataFrames:\nout = df.join(df.groupby(df.columns.map(groupings.set_index('names')['groupings']),\n axis=1).sum()\n )\n\nOutput:\n date James Jamie John Allysia Jean girl guy\n0 2022-01-01 NaN 6 5 4.0 ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074608652_python.txt |
Q:
Split pandas dataframe into groups of 20 and assign column value to each group
I have a df as follows.
TimeStamp,Value
t1,akak
t2,bb
t3,vvv
t5,ff
t6,44
t7,99
t8,kfkkf
t9,ff
t10,oo
I want to split df into sizes of 2 rows and assign class as group number.
TimeStamp,Value, class
t1,akak,c1
t2,bb,c1
t3,vv... | Split pandas dataframe into groups of 20 and assign column value to each group | I have a df as follows.
TimeStamp,Value
t1,akak
t2,bb
t3,vvv
t5,ff
t6,44
t7,99
t8,kfkkf
t9,ff
t10,oo
I want to split df into sizes of 2 rows and assign class as group number.
TimeStamp,Value, class
t1,akak,c1
t2,bb,c1
t3,vvv,c2
t4,ff,c2
t5,44,c3
t6,99,c3
t7,kfkkf,c4
t8,ff,c4
t9,oo,c5
t10,oo,c5
One ... | [
"You could do:\ndf['class'] = [i//2 for i in range(len(df))]\nBut this is a pretty limited answer; you might want to apply a certain value on your other columns to get the group ID, or you may have a specific label in mind to apply for the class column, in which case you could follow up with a map function on the s... | [
0,
0,
0,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074607663_dataframe_pandas_python.txt |
Q:
ImportError: cannot import name 'TFTModel' from 'darts.models'
I receive the error message
"ImportError: cannot import name 'TFTModel' from 'darts.models'" when trying to import the atribute "TFTmodel" from darts using the line
from darts.models import TFTModel
I have tried using "pip install statsforecast==0.6.0... | ImportError: cannot import name 'TFTModel' from 'darts.models' | I receive the error message
"ImportError: cannot import name 'TFTModel' from 'darts.models'" when trying to import the atribute "TFTmodel" from darts using the line
from darts.models import TFTModel
I have tried using "pip install statsforecast==0.6.0" however that leads to me not being able to use darts since the cur... | [
"This could possibly mean there is no TFTModel in that version. Have you checked documentation and other versions?\n",
"I think I figured it out.\nAs seen in the documentation it says it's in darts.models.forcasting, so try:\nfrom darts.models.forcasting import TFTModel\n\n"
] | [
0,
0
] | [] | [] | [
"libraries",
"python"
] | stackoverflow_0074608718_libraries_python.txt |
Q:
Return the last not null, nan, and non empty value from a python list
How can I return the last not null, not empty, and not nan from a list?
if not exists, then return "null" or a customized message!
I have tried these pieces of codes and none of them is bullet proof:
import numpy as np
listF=[0.0,np. NaN,2,0,0.... | Return the last not null, nan, and non empty value from a python list | How can I return the last not null, not empty, and not nan from a list?
if not exists, then return "null" or a customized message!
I have tried these pieces of codes and none of them is bullet proof:
import numpy as np
listF=[0.0,np. NaN,2,0,0.0,""]
print([j for j in listF if j][-1])#returns 2 while should retrun 0
l... | [
"You can use math.isnan (or numpy.isnan) to check the NA status. Combine it with a generator and next with a default value to handle cases without valid value:\nfrom math import isnan\n\ndef last_valid(lst):\n return next((x for x in reversed(lst) if x and not isnan(x)), None) # or 'null'\n\nlast_valid([])\n# No... | [
3,
1,
0
] | [] | [] | [
"arrays",
"list",
"numpy",
"python"
] | stackoverflow_0074608745_arrays_list_numpy_python.txt |
Q:
Pandas code to round values greater than 0.5 to 1
I am having a dataframe column and want to round it. If the value is equal to 0.5 it is getting rounded as 0, but i want it to be 1 if the value is greater than or equal to 0.5.
Could someone please help
A:
As mentionned by @ALoolz in a comment, pandas (and pyt... | Pandas code to round values greater than 0.5 to 1 | I am having a dataframe column and want to round it. If the value is equal to 0.5 it is getting rounded as 0, but i want it to be 1 if the value is greater than or equal to 0.5.
Could someone please help
| [
"As mentionned by @ALoolz in a comment, pandas (and python in general) is using a rounding to minimize bias when summing different elements, called Rounding half to even.\nAs Wikipedi says:\n\nRounding half to even\nA tie-breaking rule without positive/negative\nbias and without bias toward/away from zero is round... | [
0
] | [
"There seems to be an issue in pandas.round function which does not round 0.5 to 1. In that case you could use built-in round with applymap\nimport pandas as pd\nimport numpy as np\n\ndef getRound(x):\n return(round(x))\n\ndf = pd.DataFrame(np.random.random([3, 3]),\ncolumns=['A', 'B', 'C'], index=['first', 'sec... | [
-2
] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0054990394_pandas_python_python_3.x.txt |
Q:
How to define a matrix by vectorization (without for loop) in numpy?
I want to define an NxN matrix A, whose element A(i,j) is sin(i^2 + j).
In MATLAB, I can quickly define this matrix by employing vectorization.
N = 2000;
ii = 1:N;
A = sin(ii.^2 + ii');
How to achieve this in Python? Right now, I am using for lo... | How to define a matrix by vectorization (without for loop) in numpy? | I want to define an NxN matrix A, whose element A(i,j) is sin(i^2 + j).
In MATLAB, I can quickly define this matrix by employing vectorization.
N = 2000;
ii = 1:N;
A = sin(ii.^2 + ii');
How to achieve this in Python? Right now, I am using for loops, which are slow.
import numpy
N = 2000;
A = numpy.empty((N, N));
for i... | [
"This can be done with the use of numpy which allows for vectorization of arrays and array-like operations. I'm sure this can be reduced in size, but we can create an array in x and y before making a grid out of these points. We then apply the entire grid to the function A=sin(i**2+j). We then get (I assume ii' is ... | [
3,
3
] | [] | [] | [
"numpy",
"python",
"vectorization"
] | stackoverflow_0074608784_numpy_python_vectorization.txt |
Q:
Apply Ordinal Encoding to an entire column
I'm working with a dataset of movies to run a regression and predict the gross.
But because some columns have String values, I'm doing an Ordinal Encoding before I do the split and run the regression.
One example is the column containing the movie titles(shown below):
Ser... | Apply Ordinal Encoding to an entire column | I'm working with a dataset of movies to run a regression and predict the gross.
But because some columns have String values, I'm doing an Ordinal Encoding before I do the split and run the regression.
One example is the column containing the movie titles(shown below):
Series_Title
1 The Shawshank Redemption
2 T... | [
"Example\ndata = {'col': {1: 'A', 2: 'B', 3: 'C', 4:'A'}}\ndf = pd.DataFrame(data)\n\ndf:\n col\n1 A\n2 B\n3 C\n4 A\n\nOrdinal Encoding\ndf['col'] = pd.factorize(df['col'])[0]\n\nresult(df)\n col\n1 0\n2 1\n3 2\n4 0\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"linear_regression",
"machine_learning",
"pandas",
"python"
] | stackoverflow_0074608620_dataframe_linear_regression_machine_learning_pandas_python.txt |
Q:
Single source of truth for Python project version in presence of pyproject.toml
The pyproject.toml specification affords the ability to specify the project version, e.g.
[project]
name = "foo"
version = "0.0.1"
However, it is also a common Python idiom to put __version__ = "0.0.1" in foo/__init__.py so that users... | Single source of truth for Python project version in presence of pyproject.toml | The pyproject.toml specification affords the ability to specify the project version, e.g.
[project]
name = "foo"
version = "0.0.1"
However, it is also a common Python idiom to put __version__ = "0.0.1" in foo/__init__.py so that users can query it.
Is there a standard way of extracting the version from the pyproject.t... | [
"There are two approaches you can take here.\n\nKeep version in pyproject.toml and get it from the package metadata in the source code. So, in your foo/__init__.py or wherever:\n\nfrom importlib.metadata import version\n__version__ = version(__package__)\n\nimportlib.metadata.version is available since Python 3.8. ... | [
2
] | [] | [] | [
"pyproject.toml",
"python"
] | stackoverflow_0074608905_pyproject.toml_python.txt |
Q:
Moving a specific column of a dataframe to first column
I have a dataframe as follows:
s = df.head().to_dict()
print(s)
{'BoP transfers': {1998: 12.346282212735618,
1999: 19.06438060024298,
2000: 18.24888031473687,
2001: 24.860019912667006,
2002: 32.38242225822908},
'Current balance': {1998: -6.7953,
1... | Moving a specific column of a dataframe to first column | I have a dataframe as follows:
s = df.head().to_dict()
print(s)
{'BoP transfers': {1998: 12.346282212735618,
1999: 19.06438060024298,
2000: 18.24888031473687,
2001: 24.860019912667006,
2002: 32.38242225822908},
'Current balance': {1998: -6.7953,
1999: -2.9895,
2000: -3.9694,
2001: 1.1716,
2002: 5.7433... | [
"Here are a few ways I do it:\ncolumns = df.columns.tolist()\ncolumns.insert(0, columns.pop(columns.index(\"Gross foreign liabilities\")))\ndf = df.reindex(columns=columns)\n\nOR\ncol = [\"Gross foreign liabilities\"]\ndf = df[col + [x for x in df.columns if x not in col]]\n\n",
"You can use pop and insert:\nname... | [
1,
0,
0
] | [] | [] | [
"columnsorting",
"pandas",
"python"
] | stackoverflow_0074608944_columnsorting_pandas_python.txt |
Q:
List All Files in a Folder Sitting in a Data Lake
I'm trying to get an inventory of all files in a folder, which has a few sub-folders, all of which sit in a data lake. Here is the code that I'm testing.
import sys, os
import pandas as pd
mylist = []
root = "/mnt/rawdata/parent/"
path = os.path.join(root, "targe... | List All Files in a Folder Sitting in a Data Lake | I'm trying to get an inventory of all files in a folder, which has a few sub-folders, all of which sit in a data lake. Here is the code that I'm testing.
import sys, os
import pandas as pd
mylist = []
root = "/mnt/rawdata/parent/"
path = os.path.join(root, "targetdirectory")
for path, subdirs, files in os.walk(path... | [
"Databricks File System (DBFS) is a distributed file system mounted into an Azure Databricks workspace and available on Azure Databricks clusters. If you are using local file API you have to reference the Databricks filesystem. Azure Databricks configures each cluster node with a FUSE mount /dbfs that allows proces... | [
16,
2,
0
] | [] | [] | [
"azure_data_lake",
"azure_databricks",
"databricks",
"python",
"scala"
] | stackoverflow_0058751144_azure_data_lake_azure_databricks_databricks_python_scala.txt |
Q:
Error while downloading the requirements using pip install (setup command: use_2to3 is invalid.)
version pip 21.2.4
python 3.6
The command:
pip install -r requirements.txt
The content of my requirements.txt:
mongoengine==0.19.1
numpy==1.16.2
pylint
pandas==1.1.5
fawkes
The command is failing with this error
ERR... | Error while downloading the requirements using pip install (setup command: use_2to3 is invalid.) | version pip 21.2.4
python 3.6
The command:
pip install -r requirements.txt
The content of my requirements.txt:
mongoengine==0.19.1
numpy==1.16.2
pylint
pandas==1.1.5
fawkes
The command is failing with this error
ERROR: Command errored out with exit status 1:
command: /Users/*/Desktop/ml/*/venv/bin/python -c 'im... | [
"It looks like setuptools>=58 breaks support for use_2to3:\nsetuptools changelog for v58\nSo you should update setuptools to setuptools<58 or avoid using packages with use_2to3 in the setup parameters.\nI was having the same problem, pip==19.3.1\n",
"I install setuptools==58It worked for me. pip install setuptool... | [
152,
47,
2,
1,
1,
0
] | [] | [] | [
"pip",
"python",
"python_3.x",
"setuptools"
] | stackoverflow_0069100275_pip_python_python_3.x_setuptools.txt |
Q:
how can you use formatting like '0.2f' but on a string to left align the text?
I am trying to make a receipt-esk output, but the problem that I am running into is the text (which I want on the right side) is not being aligned and it looks very rough. Is there some function where I can format string literals in the... | how can you use formatting like '0.2f' but on a string to left align the text? | I am trying to make a receipt-esk output, but the problem that I am running into is the text (which I want on the right side) is not being aligned and it looks very rough. Is there some function where I can format string literals in the way that you can with decimals like format(var, '0.2f')
For the most part I have do... | [
"The method str.ljust sounds like what you are interested in. This will pad out the input string with spaces to the length specified.\n>>> 'test'.ljust(10)\n'test '\n\nAnd if you wanted it to justify to the right side then you could also use the related function str.rjust.\n"
] | [
0
] | [] | [] | [
"python",
"string",
"string_formatting"
] | stackoverflow_0074609059_python_string_string_formatting.txt |
Q:
How do i create code for a vlookup in python?
df
Season
Date
Team
Team_Season_Code
TS
L
Opponent
Opponent_Season_Code
OS
2019
20181109
Abilene_Chr
1_2019
94
Home
Arkansas_St
15_2019
73
2019
20181115
Abilene_Chr
1_2019
67
Away
Denver
82_2019
61
2019
20181122
Abilene_Chr
1_2019
72
N
Elon
70_2019
56
2019
2018112... | How do i create code for a vlookup in python? | df
Season
Date
Team
Team_Season_Code
TS
L
Opponent
Opponent_Season_Code
OS
2019
20181109
Abilene_Chr
1_2019
94
Home
Arkansas_St
15_2019
73
2019
20181115
Abilene_Chr
1_2019
67
Away
Denver
82_2019
61
2019
20181122
Abilene_Chr
1_2019
72
N
Elon
70_2019
56
2019
20181123
Abilene_Chr
1_2019
73
Away
Pacific
224_2... | [
"You can use a merge, after reworking a bit Overall_Season_Avg :\ndf.merge(Overall_Season_Avg\n .set_index(['Team_Season_Code', 'Team'])\n [['OS', 'TS']].add_prefix('O'),\n left_on=['Opponent_Season_Code', 'Opponent'],\n right_index=True, how='left'\n )\n\nOutput:\n Season ... | [
2,
0
] | [] | [] | [
"dataframe",
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074609047_dataframe_group_by_numpy_pandas_python.txt |
Q:
how to test spam mail classification
user_input = input().split()
user_data = [[]]
# X_test_encoded = tokenizer.texts_to_sequences(X_test)
# X_test_padded = pad_sequences(X_test_encoded, maxlen = max_len)
if (model.predict(X_test_padded).all() > 0.5):
print(f"[{user_input}] is spam")
else:
print(f"[{user_i... | how to test spam mail classification | user_input = input().split()
user_data = [[]]
# X_test_encoded = tokenizer.texts_to_sequences(X_test)
# X_test_padded = pad_sequences(X_test_encoded, maxlen = max_len)
if (model.predict(X_test_padded).all() > 0.5):
print(f"[{user_input}] is spam")
else:
print(f"[{user_input}] is non-spam")
from tensorflow.kera... | [
"I have trained a similar model based on a movie review dataset(positive or negative)\nmodel.predict(X_test_padded).all() > 0.5\n\nThe out of above will always be True so the if loop will execute all the time.\nInstead use\nmodel.predict(X_test_padded) > 0.5\n\nFor more details please refer to this gist. Thank You.... | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074350119_python_tensorflow.txt |
Q:
How to obtain Jupyter Notebook's path?
Is there a function to obtain a Notebook's path?
I've Googled a little on the subject but didn't find a simple way to do it... I want to obtain the Notebook's path so I can then use it elsewhere. This way I could save/use files in the same path as the notebook without worryi... | How to obtain Jupyter Notebook's path? | Is there a function to obtain a Notebook's path?
I've Googled a little on the subject but didn't find a simple way to do it... I want to obtain the Notebook's path so I can then use it elsewhere. This way I could save/use files in the same path as the notebook without worrying about where it got saved.
Right now my so... | [
"TLDR: You can't\nIt is not possible to consistently get the path of a Jupyter notebook. See ipython issue #10123 for more information. I'll quote Carreau:\n\nHere are some reasons why the kernel (in this case IPython):\n\nmay not be running from single file\neven if one file, the file may not be a notebook.\neven ... | [
35,
4,
3,
1,
0
] | [
"I know this is an old post, but it seems the path to the notebook can be found using\nos.path.abspath(\"mynotebook.ipynb\")\nIt's hardcoding the name of the notebook, but that should be relatively easy to keep in sync.\n",
"You can just use \"pwd\" which stands for print working directory.\nenter image descripti... | [
-1,
-4,
-4
] | [
"jupyter",
"jupyter_notebook",
"python"
] | stackoverflow_0052119454_jupyter_jupyter_notebook_python.txt |
Q:
How to do the program to replace the sting space with a given character using replace() method?
PYTHON PROBLEM
I have searched for the answer in many website, quora is example for that.
A:
Are you sure you even tried?
Check the following out. Is this what you want?
s='123 we wr 21'
s.replace(' ' ,'@')
s #123@we@... | How to do the program to replace the sting space with a given character using replace() method? | PYTHON PROBLEM
I have searched for the answer in many website, quora is example for that.
| [
"Are you sure you even tried?\nCheck the following out. Is this what you want?\ns='123 we wr 21'\ns.replace(' ' ,'@')\ns #123@we@wr@21\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074609098_python.txt |
Q:
from exceptions import PendingDeprecationWarning ModuleNotFoundError: No module named 'exceptions'
I am trying to create a word document with Python.
I did pip install python-docx in my terminal.
My code looks like this:
from docx import Document
document = Document()
document.save('Test.docx')
I could not cr... | from exceptions import PendingDeprecationWarning ModuleNotFoundError: No module named 'exceptions' | I am trying to create a word document with Python.
I did pip install python-docx in my terminal.
My code looks like this:
from docx import Document
document = Document()
document.save('Test.docx')
I could not create a new document. What am I missing? The existing answer to install python-docx did not work for me.
... | [
"you need to install\n\n\"python-docx\"\n\nby\npip install python-docx \n\n",
"Try pip freeze and check whether the module name is listed or not.\n",
"\nUninstall docx if installed\npip uninstall docx\n\n\nInstall python-docx\npip install python-docx\n\n\nImport docx\nimport docx\n\n\nImport Document from docx\... | [
8,
0,
0
] | [] | [] | [
"python",
"python_docx"
] | stackoverflow_0053019209_python_python_docx.txt |
Q:
When import docx in python3.3 I have error ImportError: No module named 'exceptions'
when I import docx I have this error:
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/docx-0.2.4-py3.3.egg/docx.py", line 30, in <module>
from exceptions import PendingDeprecationWarning
I... | When import docx in python3.3 I have error ImportError: No module named 'exceptions' | when I import docx I have this error:
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/docx-0.2.4-py3.3.egg/docx.py", line 30, in <module>
from exceptions import PendingDeprecationWarning
ImportError: No module named 'exceptions'
How to fix this error (python3.3, docx 0.2.4)?
| [
"If you are using python 3x don't do pip install docx instead go for\npip install python-docx \n\nIt is compatible with python 3.x\nOfficial Documentation available here: https://pypi.org/project/python-docx/\n",
"When want to use import docx, be sure to install python-docx, not docx.You can install the module by... | [
277,
27,
19,
15,
10,
8,
3,
3,
1,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"python_docx"
] | stackoverflow_0022765313_python_python_3.x_python_docx.txt |
Q:
How to fix spaCy en_training incompatible with current spaCy version
UserWarning: [W094] Model 'en_training' (0.0.0) specifies an under-constrained spaCy version requirement: >=2.1.4.
This can lead to compatibility problems with older versions,
or as new spaCy versions are released, because the model may say it'... | How to fix spaCy en_training incompatible with current spaCy version | UserWarning: [W094] Model 'en_training' (0.0.0) specifies an under-constrained spaCy version requirement: >=2.1.4.
This can lead to compatibility problems with older versions,
or as new spaCy versions are released, because the model may say it's compatible when it's not.
Consider changing the "spacy_version" in your... | [
"For spacy v2 models, the under-constrained requirement >=2.1.4 means >=2.1.4,<2.2.0 in effect, and as a result this model will only work with spacy v2.1.x.\nThere is no way to convert a v2 model to v3. You can either use the model with v2.1.x or retrain the model from scratch with your training data.\n",
"pip3 i... | [
3,
0
] | [] | [] | [
"python",
"spacy"
] | stackoverflow_0070880056_python_spacy.txt |
Q:
what is the fgets() equivalent in Python
I am currently working with file handling in Python.
I have problem in copying the string value of the file.
I wanted to copy the string from file and store it to a variable, just like in C
example: this is how we do in C
FILE *fptr = fopen("read.txt", "r");
fgets(charVar, ... | what is the fgets() equivalent in Python | I am currently working with file handling in Python.
I have problem in copying the string value of the file.
I wanted to copy the string from file and store it to a variable, just like in C
example: this is how we do in C
FILE *fptr = fopen("read.txt", "r");
fgets(charVar, 100, fptr);
where we store the string file to... | [
"You can pass the limit argument to readline for a file object which would have similar behavior of stopping on a max character or a newline. Example text file:\n01234567890123456789\n01234567890123456789\n\nwith open(\"test.txt\", \"r\") as f:\n while data := f.readline(8):\n print(\"line:\", data)\n\nOu... | [
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0074609187_c_python.txt |
Q:
How do I merge different Dataframes and label each dataframe in the merged dataframe in python?
lets say for example we have 2 Dataframes, df1 and df2;
df1 = pd.DataFrame({'id': ['A01', 'A02'],
'Name': ['ABC', 'PQR']})
df2 = pd.DataFrame({'id': ['B05', 'B06'],
'Name': ['XYZ'... | How do I merge different Dataframes and label each dataframe in the merged dataframe in python? | lets say for example we have 2 Dataframes, df1 and df2;
df1 = pd.DataFrame({'id': ['A01', 'A02'],
'Name': ['ABC', 'PQR']})
df2 = pd.DataFrame({'id': ['B05', 'B06'],
'Name': ['XYZ', 'TUV']})
I want to merge the two and label each dataframes, so it appears like this.
So basically... | [
"You can concat using the keys and names parameters, then reset_index:\n(pd.concat([df1, df2], keys=[1, 2], names=['class', None])\n .reset_index('class')\n)\n\nOutput:\n class id Name\n0 1 A01 ABC\n1 1 A02 PQR\n0 2 B05 XYZ\n1 2 B06 TUV\n\nOr without reset_index to get a MultiIndex... | [
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074609248_dataframe_numpy_pandas_python.txt |
Q:
Why am I getting this error when in the documentation it says to use it?
The problem I am having is that when I try to use the command it gives me the error, TypeError: Embed.init() got an unexpected keyword argument 'value'. It cites line 34 as the issue, does anyone know why this is happening?
@client.event
asyn... | Why am I getting this error when in the documentation it says to use it? | The problem I am having is that when I try to use the command it gives me the error, TypeError: Embed.init() got an unexpected keyword argument 'value'. It cites line 34 as the issue, does anyone know why this is happening?
@client.event
async def on_message(message)
if "!sell" in message.content:
tip = ran... | [
"Official documentation doesn't include value as a valid parameter\nhttps://discordpy.readthedocs.io/en/stable/api.html#embed\nclass discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)\nYou are probably reading outdated documentation somewhere.\n"
] | [
2
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074609261_discord.py_python.txt |
Q:
using class inheritance on tkinter python
please help, I am trying to create a button on a tkinter window with the use of python class inheritance but it does not show the button. I am new to inheritance in python and not sure how do this. please see my code. thanks in advance
from tkinter import *
class A:
d... | using class inheritance on tkinter python | please help, I am trying to create a button on a tkinter window with the use of python class inheritance but it does not show the button. I am new to inheritance in python and not sure how do this. please see my code. thanks in advance
from tkinter import *
class A:
def __init__(self):
self.root = Tk()
... | [
"It is not recommended (or should not) call tkinter mainloop() inside __init__() as mainloop() is a blocking function. Therefore super().__init__() will not return until the root window is closed. Since the button is created after super().__init__(), so the root window is blank.\nRemove self.root.mainloop() inside... | [
1
] | [] | [] | [
"inheritance",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074609066_inheritance_python_tkinter_user_interface.txt |
Q:
Python: How can I implement yield in my recursion?
How can I implement yield from in my recursion? I am trying to understand how to implement it but failing:
# some data
init_parent = [1020253]
df = pd.DataFrame({'parent': [1020253, 1020253],
'id': [1101941, 1101945]})
# look for parent child... | Python: How can I implement yield in my recursion? | How can I implement yield from in my recursion? I am trying to understand how to implement it but failing:
# some data
init_parent = [1020253]
df = pd.DataFrame({'parent': [1020253, 1020253],
'id': [1101941, 1101945]})
# look for parent child
def recur1(df, parents, parentChild=None, step=0):
... | [
"I'd say your biggest issue here is that recur1 isn't always guaranteed to return a generator. For example, suppose your stack calls into the else branch three times before calling into the if branch. In this case, the top three frames would be returning a generator received from the lower frame, but the lowest fro... | [
0
] | [] | [] | [
"pandas",
"python",
"recursion"
] | stackoverflow_0074608995_pandas_python_recursion.txt |
Q:
Is there anyway to fix 'int' is not subscriptable without changing it to string data type?
I'm making a list to store my direction:
direction = [(0, +24),(+24,0),(0, -24),(-24,0)]
And using that list in this function to determine the next direction the robot will take (or backtrack)
def backtrack(self,x,y,directi... | Is there anyway to fix 'int' is not subscriptable without changing it to string data type? | I'm making a list to store my direction:
direction = [(0, +24),(+24,0),(0, -24),(-24,0)]
And using that list in this function to determine the next direction the robot will take (or backtrack)
def backtrack(self,x,y,direction):
x_walls = round(sprite.xcor(), 0)
y_walls = round(sprite.ycor(), 0)
visited.app... | [
"I was confusing the object with the list, changing the list to another name then add it to the function make it work\nnew_x = x + sprite.directions[new_direction][0]\n new_y = y + sprite.directions[new_direction][1]\n\n"
] | [
0
] | [] | [] | [
"function",
"list",
"python",
"python_3.x"
] | stackoverflow_0074609023_function_list_python_python_3.x.txt |
Q:
How to list distinct values of pyspark dataframe wrt null values in another column
i have a pyspark dataframe:
rowNum Vehicle Production
1 1234 5678
2 null 1254
3 null 4567
4 null 4567
i want to pick all the distinct values of Produ... | How to list distinct values of pyspark dataframe wrt null values in another column | i have a pyspark dataframe:
rowNum Vehicle Production
1 1234 5678
2 null 1254
3 null 4567
4 null 4567
i want to pick all the distinct values of Production in a list format where Vehicle is null. How to achieve this?
result:
production li... | [
"I would do something like this:\n# Using Spark 3.3.0\n\n# Dataset as per the question\ndata = [\n [1, '1234', 5678]\n, [2, 'Null', 1254]\n, [3, 'Null', 4567]\n, [4, 'Null', 4567] \n]\n\ncols = ['rowNum', 'Vehicle', 'Production']\n\n# Creating Dataframe\ndf = spark.createDataFrame(data, cols... | [
1
] | [] | [] | [
"pyspark",
"python",
"python_3.x"
] | stackoverflow_0074608499_pyspark_python_python_3.x.txt |
Q:
How do I make 2 images appear side by side in Jupyter notebook (iPython)?
I want to display 2 PNG images in iPython side by side.
My code to do this is:
from IPython.display import Image, HTML, display
img_A = '\path\to\img_A.png'
img_B = '\path\to\img_B.png'
display(HTML("<table><tr><td><img src=img_A></td><td>... | How do I make 2 images appear side by side in Jupyter notebook (iPython)? | I want to display 2 PNG images in iPython side by side.
My code to do this is:
from IPython.display import Image, HTML, display
img_A = '\path\to\img_A.png'
img_B = '\path\to\img_B.png'
display(HTML("<table><tr><td><img src=img_A></td><td><img src=img_B></td></tr></table>"))
But it doesn't output the images, and ins... | [
"You can try using matplotlib. You can read image to numpy array by using mpimg.imread (documentation) from matplotlib, then you can use subplots (documentation) and for creating two columns for figures and finally imshow (documetation) to display images.\nimport matplotlib.pyplot as plt\nimport matplotlib.image as... | [
21,
13,
3,
1,
0,
0
] | [] | [] | [
"image",
"ipython",
"jupyter_notebook",
"python"
] | stackoverflow_0050559000_image_ipython_jupyter_notebook_python.txt |
Q:
How to pass data from one view to another one in Fastapi?
I have a variable set in one view in Fastapi and want to pass it to another one :
from fastapi import APIRouter, Request, Response
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="templates")
router = APIRouter()
@rout... | How to pass data from one view to another one in Fastapi? | I have a variable set in one view in Fastapi and want to pass it to another one :
from fastapi import APIRouter, Request, Response
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="templates")
router = APIRouter()
@router.get("/my-first-view")
async def function1(request: Request) ... | [] | [] | [
"Very little context information on this post, so I'll help out with fixes that change as little as possible.\nFirst of all, to fix your code you need a place to save the changes that you've made. A variable that only exists in a function is deleted at the end of that function.\nNow usually you'd give more informat... | [
-1
] | [
"fastapi",
"python"
] | stackoverflow_0074609265_fastapi_python.txt |
Q:
Killing a python thread
I would like to kill somehow a running thread from my GUI application via setting an event, but I can't use a for loop in my thread so I need some other solution to check the event
I have the following situation.
In a tkinter gui when I click a button I start a thread and set a global varia... | Killing a python thread | I would like to kill somehow a running thread from my GUI application via setting an event, but I can't use a for loop in my thread so I need some other solution to check the event
I have the following situation.
In a tkinter gui when I click a button I start a thread and set a global variable.
self.thread = StoppableT... | [
"This loop will run forever until you set the flag:\n def run(self):\n while not self.stopped():\n sleep(1)\n print('Test')\n\nYou don't actually need an event. A simple Boolean will do.\nFOLLOWUP\nHere's an example based on your code that shows how this works:\nimport threading\nfr... | [
1
] | [] | [] | [
"multithreading",
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0074609532_multithreading_python_python_3.x_tkinter.txt |
Q:
How to use multiple GPUs in pytorch?
I use this command to use a GPU.
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
But, I want to use two GPUs in jupyter, like this:
device = torch.device("cuda:0,1" if torch.cuda.is_available() else "cpu")
A:
Assuming that you want to distribute the d... | How to use multiple GPUs in pytorch? |
I use this command to use a GPU.
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
But, I want to use two GPUs in jupyter, like this:
device = torch.device("cuda:0,1" if torch.cuda.is_available() else "cpu")
| [
"Assuming that you want to distribute the data across the available GPUs (If you have batch size of 16, and 2 GPUs, you might be looking providing the 8 samples to each of the GPUs), and not really spread out the parts of models across difference GPU's. This can be done as follows:\nIf you want to use all the avail... | [
58,
22,
5,
1,
1,
1
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0054216920_python_pytorch.txt |
Q:
How to make Optuna get replicable results?
I'm using optuna to tune LGBM. Random seeds had been set but each time Optuna got different set of best params.
Here's my optuna code:
def get_hpo_params(opt_X_train, opt_X_val, opt_y_train, opt_y_val, n_trials=180, cat_features=""):
def objective(trial):
dtrain = lg... | How to make Optuna get replicable results? | I'm using optuna to tune LGBM. Random seeds had been set but each time Optuna got different set of best params.
Here's my optuna code:
def get_hpo_params(opt_X_train, opt_X_val, opt_y_train, opt_y_val, n_trials=180, cat_features=""):
def objective(trial):
dtrain = lgb.Dataset(opt_X_train, opt_y_train, categorical_... | [
"Ohh, I finally solved the problem. Need to set hash seed on my laptop using this method: https://gerrychain.readthedocs.io/en/latest/topics/reproducibility.html#set-pythonhashseed-0\nThis solution is mentioned in optuna for reproducing pruning behaviour: https://optuna.readthedocs.io/en/stable/reference/generated/... | [
0
] | [] | [] | [
"lightgbm",
"optuna",
"python",
"replicate"
] | stackoverflow_0074609322_lightgbm_optuna_python_replicate.txt |
Q:
Splitting text and numbers and adding a seperator
I have a string of the form:
Abu Dhabi1.90Morrisville Samp Army1.90
Deccan Gladiators1.40The Chennai Braves2.87
Bangla Tigers1.90Delhi Bulls1.90
New Zealand1.68India2.15
Australia1.09Draw14.00West Indies13.00
Sri Lanka1.51Afghanistan2.50
Tas Tigers1.28South Austral... | Splitting text and numbers and adding a seperator | I have a string of the form:
Abu Dhabi1.90Morrisville Samp Army1.90
Deccan Gladiators1.40The Chennai Braves2.87
Bangla Tigers1.90Delhi Bulls1.90
New Zealand1.68India2.15
Australia1.09Draw14.00West Indies13.00
Sri Lanka1.51Afghanistan2.50
Tas Tigers1.28South Australia3.50
Is there a regular expression that can be used ... | [
"What about using (?<=[\\d.])(?=[^\\d.\\n])|(?<=[^\\d.])(?=[\\d.]) to detect alternating numbers/non-numbers?\ntext = '''Abu Dhabi1.90Morrisville Samp Army1.90\nDeccan Gladiators1.40The Chennai Braves2.87\nBangla Tigers1.90Delhi Bulls1.90\nNew Zealand1.68India2.15\nAustralia1.09Draw14.00West Indies13.00\nSri Lanka1... | [
0,
0
] | [] | [] | [
"data_cleaning",
"python",
"strsplit",
"web_scraping"
] | stackoverflow_0074609093_data_cleaning_python_strsplit_web_scraping.txt |
Q:
TypeError: iText() missing 2 required positional arguments: 'text' and 'data_frame'
this is my function.py
def iText(text, data_frame):
url = requests.get("http://nlp.cs.aueb.gr/software_and_datasets/lingspam_public.tar.gz")
text = url\[-1\].strip()
label = url\[-1\].strip()
... | TypeError: iText() missing 2 required positional arguments: 'text' and 'data_frame' | this is my function.py
def iText(text, data_frame):
url = requests.get("http://nlp.cs.aueb.gr/software_and_datasets/lingspam_public.tar.gz")
text = url\[-1\].strip()
label = url\[-1\].strip()
data_frame = pd.DataFrame(text, label)
return text, data_frame
this my file test_... | [
"No, it's not right. Your iText function doesn't have any inputs, so it shouldn't have any parameters. Next, in your test function, you need to CALL iText and check what it returns:\ndef iText():\n url = requests.get(\"http://nlp.cs.aueb.gr/software_and_datasets/lingspam_public.tar.gz\")\n text = url[-1].st... | [
0
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074609547_pytest_python.txt |
Q:
Get parameter estimates from logistic regression model using pycaret
I am training and tuning a model in pycaret such as:
from pycaret.classification import *
clf1 = setup(data = train, target = 'target', feature_selection = True, test_data = test, remove_multicollinearity = True, multicollinearity_threshold = 0.... | Get parameter estimates from logistic regression model using pycaret | I am training and tuning a model in pycaret such as:
from pycaret.classification import *
clf1 = setup(data = train, target = 'target', feature_selection = True, test_data = test, remove_multicollinearity = True, multicollinearity_threshold = 0.4)
# create model
lr = create_model('lr')
# tune model
tuned_lr = tune_m... | [
"how about\nfor f, c in zip (optimized_lr.feature_names_in_,tuned.coef_[0]):\n print(f, c)\n\n"
] | [
0
] | [] | [] | [
"logistic_regression",
"pycaret",
"python",
"regression"
] | stackoverflow_0073023479_logistic_regression_pycaret_python_regression.txt |
Q:
My Python-3 Code is kinda confuzing if anyone can help i would like to know, I made a window
#imports
from tkinter import *
import os
#Window Creation
window = Tk()
window.title('Potato Defense')
window.configure(width=1500, height=1500)
window.configure(bg='lightblue')
photo = PhotoImage(file = r"TestButton.png"... | My Python-3 Code is kinda confuzing if anyone can help i would like to know, I made a window | #imports
from tkinter import *
import os
#Window Creation
window = Tk()
window.title('Potato Defense')
window.configure(width=1500, height=1500)
window.configure(bg='lightblue')
photo = PhotoImage(file = r"TestButton.png")
Button(window, text = 'Click Me !', image = photo).pack(side = TOP)
window.mainloop()
my code ... | [] | [] | [
"If your code is in the same directory as this file, you can simply do photo = PhotoImage(file = \"./TestButton.png\")\n"
] | [
-2
] | [
"button",
"python",
"python_3.x"
] | stackoverflow_0074609638_button_python_python_3.x.txt |
Q:
How To Automatically Create Objects Of Django Model While Creation Another Model Objects
I Want To Create Object For "ProductOut" Model When "CusOrder" Model Is Being Created
Here Is My Code
class CusOrder(models.Model):
cus_name = models.CharField(max_length=100)
cus_number = models.CharField(max_length=1... | How To Automatically Create Objects Of Django Model While Creation Another Model Objects | I Want To Create Object For "ProductOut" Model When "CusOrder" Model Is Being Created
Here Is My Code
class CusOrder(models.Model):
cus_name = models.CharField(max_length=100)
cus_number = models.CharField(max_length=11)
product = models.ManyToManyField(Product)
qty = models.IntegerField(default=0)
... | [
"refrence should have CusOrder instance and super should call before the creation as CusOrder object should be created first.\n def save(self,*args,**kwrgs):\n instance = super(CusOrder,self).save(*args,**kwrgs)\n p_instance = ProductOut.objects.create(\n stock_out = self.qty,\n ... | [
0
] | [] | [] | [
"django",
"django_models",
"django_modeltranslation",
"python"
] | stackoverflow_0074609592_django_django_models_django_modeltranslation_python.txt |
Q:
Install nodejs in python slim buster
I have a Dockerfile that starts with
FROM python:3.7-slim-buster
and I want to install node.js and npm in it. How can I install them in this image?
A:
This should work:
FROM python:3.7-slim-buster
# setup dependencies
RUN apt-get update
RUN apt-get install xz-utils
RUN apt-... | Install nodejs in python slim buster | I have a Dockerfile that starts with
FROM python:3.7-slim-buster
and I want to install node.js and npm in it. How can I install them in this image?
| [
"This should work:\nFROM python:3.7-slim-buster\n\n# setup dependencies\nRUN apt-get update\nRUN apt-get install xz-utils\nRUN apt-get -y install curl\n\n# Download latest nodejs binary\nRUN curl https://nodejs.org/dist/v14.15.4/node-v14.15.4-linux-x64.tar.xz -O\n\n# Extract & install\nRUN tar -xf node-v14.15.4-lin... | [
12,
2,
1
] | [] | [] | [
"docker",
"dockerfile",
"node.js",
"python"
] | stackoverflow_0065706138_docker_dockerfile_node.js_python.txt |
Q:
Getting HttpErrorResponse error in angular for Delete request
I am trying to send a Delete request from my movie.component.ts page to delete a review. But I am getting HttpErrorResponse error. Where am I going wrong?
here is a screenshot of the error message I am receiving in the console:
HttpErrorResponse
movie.c... | Getting HttpErrorResponse error in angular for Delete request | I am trying to send a Delete request from my movie.component.ts page to delete a review. But I am getting HttpErrorResponse error. Where am I going wrong?
here is a screenshot of the error message I am receiving in the console:
HttpErrorResponse
movie.component.ts
deleteReview(reviewID: any) {
this.webService.dele... | [
"Typo in web.service.ts. Forgot a slash after /reviews/. Second a typo on this.reviewIDw.\nSo in your error you see the value of reviewID is undefined. This can bring this CORS error, too. Then the route was not found.\nGreetings Florian\n"
] | [
0
] | [] | [] | [
"angular",
"python",
"typescript"
] | stackoverflow_0074607245_angular_python_typescript.txt |
Q:
Not Able to Run GEM5 with RISC-V: "!seWorkload occurred: Couldn't find appropriate workload object"
I am trying to run gem5 with RISC-V. I have the Linux 64-bits cross compiler ready and I have also installed and compiled gem5. I then tried to use the following tutorial to run gem5: https://canvas.kth.se/courses/2... | Not Able to Run GEM5 with RISC-V: "!seWorkload occurred: Couldn't find appropriate workload object" | I am trying to run gem5 with RISC-V. I have the Linux 64-bits cross compiler ready and I have also installed and compiled gem5. I then tried to use the following tutorial to run gem5: https://canvas.kth.se/courses/24933/pages/tutorial-simulating-a-cpu-with-gem5
I wrote a simple Hello World C program and compiled it usi... | [
"m5.util.addToPath('../../') is missing. This is used to add the common scripts to the path to your directory from where you are instantiating the simulation.\n"
] | [
0
] | [] | [] | [
"c++",
"gcc",
"gem5",
"python",
"riscv"
] | stackoverflow_0073614148_c++_gcc_gem5_python_riscv.txt |
Q:
How to reference python package when filename contains a period
I am using django and I have a file named models.admin.py and I want to do the following idea in models.py:
from "models.admin" import *
however, I get a syntax error for having double quotes. But if I just do
from models.admin import *
then I get ... | How to reference python package when filename contains a period | I am using django and I have a file named models.admin.py and I want to do the following idea in models.py:
from "models.admin" import *
however, I get a syntax error for having double quotes. But if I just do
from models.admin import *
then I get "ImportError: No module named admin"
Is there any way to import from ... | [
"Actually, you can import a module with an invalid name. But you'll need to use imp for that, e.g. assuming file is named models.admin.py, you could do\nimport imp\nwith open('models.admin.py', 'rb') as fp:\n models_admin = imp.load_module(\n 'models_admin', fp, 'models.admin.py',\n ('.py', 'rb', i... | [
40,
15,
4,
4,
3,
0
] | [
"You are not referencing files in the import statement, you are referencing modules and packages.\nPlease read the docs, they are very clear on that matter.\nAnyway, since you are using django, the usual approach won't work. If you want to keep models in separate files, rather than in models.py, you have to take ex... | [
-1
] | [
"import",
"module",
"package",
"python",
"python_import"
] | stackoverflow_0001828127_import_module_package_python_python_import.txt |
Q:
Exporting jupyter notebook to pdf with offline plotly graph; missing graphs
I am trying to create pdf export of my lesson plans and I use plotly offline for the graphs. In a MWE below, the plot will display in the Jupyter Notebook but will not show up when I export to pdf. I export using File-->Download as-->PDF v... | Exporting jupyter notebook to pdf with offline plotly graph; missing graphs | I am trying to create pdf export of my lesson plans and I use plotly offline for the graphs. In a MWE below, the plot will display in the Jupyter Notebook but will not show up when I export to pdf. I export using File-->Download as-->PDF via Latex (.pdf).
I'd like to make a pdf instead of using html. I understand it mi... | [
"You need to specify the appropriate Default Renderer (or Renderers, if you want to visualize it in the Notebook and also when exporting to PDF using the File-->Download as-->PDF via Latex (.pdf) option you mentioned).\nI have been struggling with this myself for some hours too, but the setup that ended up working ... | [
6,
2,
1,
1,
0
] | [] | [] | [
"jupyter_notebook",
"pdf",
"plotly",
"python"
] | stackoverflow_0045761893_jupyter_notebook_pdf_plotly_python.txt |
Q:
Splitting a tensorflow dataset into training, test, and validation sets from keras.preprocessing API
I'm new to tensorflow/keras and I have a file structure with 3000 folders containing 200 images each to be loaded in as data. I know that keras.preprocessing.image_dataset_from_directory allows me to load the data ... | Splitting a tensorflow dataset into training, test, and validation sets from keras.preprocessing API | I'm new to tensorflow/keras and I have a file structure with 3000 folders containing 200 images each to be loaded in as data. I know that keras.preprocessing.image_dataset_from_directory allows me to load the data and split it into training/validation set as below:
val_data = tf.keras.preprocessing.image_dataset_from_d... | [
"I could not find supporting documentation, but I believe image_dataset_from_directory is taking the end portion of the dataset as the validation split. shuffle is now set to True by default, so the dataset is shuffled before training, to avoid using only some classes for the validation split.\nThe split done by im... | [
3,
1,
1
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0066036271_keras_python_tensorflow.txt |
Q:
python create class with brackets
In python I can create class as follows:
class Car:
def __init__(self):
pass
But I have seen some people create class with empty brackets e.g.:
class Car():
def __init__(self):
pass
The second form works, so my question is which one is the correct (or pyt... | python create class with brackets | In python I can create class as follows:
class Car:
def __init__(self):
pass
But I have seen some people create class with empty brackets e.g.:
class Car():
def __init__(self):
pass
The second form works, so my question is which one is the correct (or pythonic) way of defining class. I know th... | [
"In python3, you can just ignore the brackets.\nIn other words, class Car is equivalent to class Car() and the former one is more pythonic. However, In python2, you have to use class Car(object) to suit python2's requirement.\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074609819_python_python_3.x.txt |
Q:
Login Issue "POST" 200 3689 (Python, Django)
I am quite new to Django and followed a tutorial to create a website. I'm not able to log in to an account. When I log in with any details (correct or incorrect), my 'login' page just reloads and nothing else happens (The expected result is that I go into a different pa... | Login Issue "POST" 200 3689 (Python, Django) | I am quite new to Django and followed a tutorial to create a website. I'm not able to log in to an account. When I log in with any details (correct or incorrect), my 'login' page just reloads and nothing else happens (The expected result is that I go into a different page when I log in correctly)
I am getting "POST /... | [
"You can Create a User like this. Django uses hashing technique to store users' passwords with some salt. If You are creating a user you have to call set_password method to store the password.\nfrom django.contrib.auth.models import User\n\nuser = User()\nuser.username = request.POST.get('username')\nuser.set_passw... | [
0,
0
] | [] | [] | [
"authentication",
"django",
"python",
"sqlite"
] | stackoverflow_0074606523_authentication_django_python_sqlite.txt |
Q:
Conversion of df one column values to multiple column values in pandas
id
date
decision
1
2022-11-10
improve
1
2022-11-10
checked
2
2021-09-12
checked
3
2020-08-22
checked
4
2019-11-10
complete
4
2019-11-10
revise
Converting above dataframe as
id
date
CR
Principal
1
2022-11-10
checked
improve
2
2021-09-1... | Conversion of df one column values to multiple column values in pandas |
id
date
decision
1
2022-11-10
improve
1
2022-11-10
checked
2
2021-09-12
checked
3
2020-08-22
checked
4
2019-11-10
complete
4
2019-11-10
revise
Converting above dataframe as
id
date
CR
Principal
1
2022-11-10
checked
improve
2
2021-09-12
checked
NA
3
2020-08-22
checked
NA
4
2019-11-10
... | [
"Use GroupBy.cumcount with ascending=False for counter in descending order and pivoting by 4 columns, then use rename - add keys to dictionary for rename if 3 or 4 duplicated decisions:\ndf = (df.assign(g = df.groupby(['id','date']).cumcount(ascending=False))\n .pivot(['id','date'], 'g', 'decision')\n ... | [
0
] | [] | [] | [
"dataframe",
"datatables",
"pandas",
"pivot",
"python"
] | stackoverflow_0074609858_dataframe_datatables_pandas_pivot_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.