content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to compare two lists in python, but part of the values
For example lest say I have those two lists:
x = ["hi [ICON]", "apple [ICON]", "world [ICON]" ]
y = ["hi", "apple"]
How can I tell if all of list y is inside of list x?
A:
You need to use any and all.
# First check each element of 'y' exist in at least ... | How to compare two lists in python, but part of the values | For example lest say I have those two lists:
x = ["hi [ICON]", "apple [ICON]", "world [ICON]" ]
y = ["hi", "apple"]
How can I tell if all of list y is inside of list x?
| [
"You need to use any and all.\n# First check each element of 'y' exist in at least one element of 'x'\n>>> [any(i in j for j in x) for i in y]\n[True, True]\n\n# Second check all elements of y exist in x.\n>>> all(any(i in j for j in x) for i in y) # <- You need this check two steps\nTrue\n\n",
"Another solution... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074423699_python.txt |
Q:
Legend for networkx draw function
So I have the following function to draw a problem im working on. Its basically a critical node detection problem or interdiction. I have some values x, and decision to attack to the node z. Basically I wanna color my graph with active and inactive nodes and nodes that are being t... | Legend for networkx draw function | So I have the following function to draw a problem im working on. Its basically a critical node detection problem or interdiction. I have some values x, and decision to attack to the node z. Basically I wanna color my graph with active and inactive nodes and nodes that are being treated/attack. Here is what I have so f... | [
"Is this what you're after?\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = nx.fast_gnp_random_graph(20,0.2)\n\nrednodes = [1,2,4,5]\nbluenodes = [10,12]\ngreennodes = [3,6,9]\nyellowgreennodes = [node for node in G.nodes() if\n node not in rednodes + greennodes + bluenodes]\npos =... | [
21,
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0032931484_networkx_python.txt |
Q:
Regex to match city names from text with numbers
I have a string with the names of a cities and the numbers of people living in them. I need to match only names of cities using Regex
city = "New York - 8 468 000 Los Angeles - 3 849 000 Berlin - 3 645 000"
tried this
[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$
but it returns "... | Regex to match city names from text with numbers | I have a string with the names of a cities and the numbers of people living in them. I need to match only names of cities using Regex
city = "New York - 8 468 000 Los Angeles - 3 849 000 Berlin - 3 645 000"
tried this
[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$
but it returns "None"
| [
"If you want all cities as a single string you can use [a-zA-Z]+ to disregard all numbers and return a single string:\ncities = \" \".join(re.findall(\"[a-zA-Z]+\", city))\n\nReturning:\n'New York Los Angeles Berlin'\n\nOtherwise if you want them separated, I would split by - first and then return using the same me... | [
1,
1,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0074423772_python_regex_string.txt |
Q:
Failed to make Dataset.filter() work in the model/official/resnet/resnet_run_loop.py file
In the official resnet model, I want to filters the dataset from test.bin by the value of 'label' when eval_only set to be True. I tried the tf.data.Dataset.filter() function to get only one class of test data but it didn't w... | Failed to make Dataset.filter() work in the model/official/resnet/resnet_run_loop.py file | In the official resnet model, I want to filters the dataset from test.bin by the value of 'label' when eval_only set to be True. I tried the tf.data.Dataset.filter() function to get only one class of test data but it didn't work.
dataset = dataset.filter(lambda inputs, label: tf.equal(label,15))
I put this code in the... | [
"When comparing two tensors it is returning a bool tensor like this <tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, True])> which is useless if you want to find an answer to the question \"Is this tensor equal to another tensor?\". Adding tf.reduce_all to it will return a tensor like this <tf.Tensor: shap... | [
0
] | [
"I faced the same problem in a different situation, and it turns out, as suggested in the comments, that the issue was caused by batching before filtering.\nYou can reproduce this using this example:\nimport pprint\nimport tensorflow as tf\n\ndataset = tf.data.Dataset.zip((\n tf.data.Dataset.range(0, 5),\n tf... | [
-2
] | [
"python",
"resnet",
"tensorflow"
] | stackoverflow_0053424304_python_resnet_tensorflow.txt |
Q:
Counter of lists of lists
I have a big dictionary coming from a simulation loop that looks something like this:
my_dict = {
'a': {
1: [[1,2,3], [1,2,3], [1,2,3], [1,3,5]],
2: [[2,44,57,18], [2,44,57,18], [2,44,57,23], [2,44,57,23]]},
'b': {
3: [[3,67,50], [3,67,50], [3,36]],
... | Counter of lists of lists | I have a big dictionary coming from a simulation loop that looks something like this:
my_dict = {
'a': {
1: [[1,2,3], [1,2,3], [1,2,3], [1,3,5]],
2: [[2,44,57,18], [2,44,57,18], [2,44,57,23], [2,44,57,23]]},
'b': {
3: [[3,67,50], [3,67,50], [3,36]],
4: [[4,12,34], [4,12]]}}
The ... | [
"You can convert the lists into tuples before calling Counter:\nfrom collections import Counter\n\nsummary = []\nfor name1, sub_dict in my_dict.items():\n for ind, lists in sub_dict.items():\n C = Counter(map(tuple, lists))\n total = sum(C.values())\n for arr, freq in C.items():\n ... | [
2
] | [] | [] | [
"counter",
"python"
] | stackoverflow_0074423818_counter_python.txt |
Q:
Advice on attribute naming convention for a Python-Pydantic-FastAPI/DynamoDB/React App
I'm building an App with a Python-Pydantic-FastAPI API, a DynamoDB persistence layer and a React front-end and am looking for advice on attribute naming conventions.
The dilemma is that these three basically have 3 different nam... | Advice on attribute naming convention for a Python-Pydantic-FastAPI/DynamoDB/React App | I'm building an App with a Python-Pydantic-FastAPI API, a DynamoDB persistence layer and a React front-end and am looking for advice on attribute naming conventions.
The dilemma is that these three basically have 3 different naming conventions.
Python: snake_case
DynamoDB: PascalCase
React: camelCase
So what do people ... | [
"DynamoDB doesn't care about which case you use, it can be a mix of you like, but of course you don't want a mix for your application side.\nI would suggest picking the case which you use in your application the most.\n"
] | [
0
] | [] | [] | [
"amazon_dynamodb",
"json",
"pydantic",
"python"
] | stackoverflow_0074423791_amazon_dynamodb_json_pydantic_python.txt |
Q:
Can't Print array element names (python)
I have an array of points and I'm looking to print the name of the points instead of the actual points.
A = (2,0)
B = (3, 4)
C = (5, 6)
array1 = [A, B, C]
when I do print(array1[0]) it ends up printing the values. But I want to print the letters such as A, B or C. How w... | Can't Print array element names (python) | I have an array of points and I'm looking to print the name of the points instead of the actual points.
A = (2,0)
B = (3, 4)
C = (5, 6)
array1 = [A, B, C]
when I do print(array1[0]) it ends up printing the values. But I want to print the letters such as A, B or C. How would I print the letters instead?
I've also tr... | [
"A variable doesn't usually contain its own name. This is simply something you can use to target whatever value that is being referenced.\nObviously, the best answer will be related to the really why you want to print \"A\". If you just want to print the letter \"A\", then simply do:\nprint(\"A\")\nObviously, that ... | [
1,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074423773_arrays_python.txt |
Q:
Appending zero rows to a 2D Tensor in PyTorch
Suppose I have a tensor 2D tensor x of shape (n,m). How can I extend the first dimension of the tensor by appending zero rows in x by specifying the indices of where the zero rows will be located in the resulting tensor? For a concrete example:
x = torch.tensor([[1,1,1... | Appending zero rows to a 2D Tensor in PyTorch | Suppose I have a tensor 2D tensor x of shape (n,m). How can I extend the first dimension of the tensor by appending zero rows in x by specifying the indices of where the zero rows will be located in the resulting tensor? For a concrete example:
x = torch.tensor([[1,1,1],
[2,2,2],
[3,... | [
"You can use torch.cat:\ndef insert_zeros(x, all_j):\n zeros_ = torch.zeros_like(x[:1])\n pieces = []\n i = 0\n for j in all_j + [len(x)]:\n pieces.extend([x[i:j],\n zeros_])\n i = j\n return torch.cat(pieces[:-1],\n dim=0 )\n\n# inser... | [
1,
1
] | [] | [] | [
"python",
"pytorch",
"tensor",
"zero_padding"
] | stackoverflow_0074423476_python_pytorch_tensor_zero_padding.txt |
Q:
Accessing global variable in my custom module from a master
In a master i have a global variable called "READ_ONLY_ON_STATES" which is a dictionary
READ_ONLY_ON_STATES = {"on_validation":[("readonly", True)]}
This is the dictionary defined in the master.
I now want to access this dictionary on my module and add an... | Accessing global variable in my custom module from a master | In a master i have a global variable called "READ_ONLY_ON_STATES" which is a dictionary
READ_ONLY_ON_STATES = {"on_validation":[("readonly", True)]}
This is the dictionary defined in the master.
I now want to access this dictionary on my module and add another key in that "READ_ONLY_ON_STATES" variable...
How to achive... | [
"What do you mean by \"in a master\"?\nAs destripador said, you can use ir.config_parameter model to set and read variables in run-time.\nIf you just need a constant static variable defined in a python script inside an odoo module, you'll need to import it manually.\nFor example, let's suppose READ_ONLY_ON_STATES i... | [
1,
1,
0
] | [] | [] | [
"odoo",
"odoo_15",
"python"
] | stackoverflow_0074406225_odoo_odoo_15_python.txt |
Q:
Numba: how to speed up numerical simulation requiring also GUI
I was just starting to learn about Numba to speed up for loops.
I've read it is impossible to call a non-jitted function from a numba jitted function. Therefore I don't think I can @jitclass(spec) my class or @njit the main algorithm function (compute(... | Numba: how to speed up numerical simulation requiring also GUI | I was just starting to learn about Numba to speed up for loops.
I've read it is impossible to call a non-jitted function from a numba jitted function. Therefore I don't think I can @jitclass(spec) my class or @njit the main algorithm function (compute()) leaving my code how it is, since every step of the simulation (o... | [
"\nthere is any alternative to Numba which I may benefit from.\n\ncython exists, and is more mature than numba, but it requires a compiler, so you only make compiled binaries, not JIT the functions, it provides static typing and it removes the interpreter overhead.\n\nthere is any possible logical change to the pro... | [
1
] | [] | [] | [
"numba",
"numpy",
"python",
"tkinter"
] | stackoverflow_0074423673_numba_numpy_python_tkinter.txt |
Q:
Replace csv file first column with list values in python
I want to replace csv file first column with list values in python
Data:
0 1 2 3 4 5 6 7 8 9
0 0 0 0.3 0 0.3 0 0.3 0 0 0
1 0 0.2 0 0 0 0 0.2 0.4 0.2 0
2 0 0 0.2 0.1 0.3 0.1 0 0.4 0 0
3 0 0 0.1 0... | Replace csv file first column with list values in python | I want to replace csv file first column with list values in python
Data:
0 1 2 3 4 5 6 7 8 9
0 0 0 0.3 0 0.3 0 0.3 0 0 0
1 0 0.2 0 0 0 0 0.2 0.4 0.2 0
2 0 0 0.2 0.1 0.3 0.1 0 0.4 0 0
3 0 0 0.1 0.2 0.1 0.1 0.2 0.1 0.1 0.1
4 0 0 0.2 0.1 0 0.1 0.2 0.2... | [
"Just use loc to modify the one column of your dataframe:\nexample = pd.DataFrame({0: [1, 2, 3],\n 2: [\"a\", \"b\", \"c\"]})\n\nreplacement_list = [\"ab\", \"cd\", \"ef\"]\nexample.loc[:, 2] = replacement_list\nprint(example)\n\n 0 2\n0 1 ab\n1 2 cd\n2 3 ef\n\nI encourage you to lo... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074423706_dataframe_pandas_python.txt |
Q:
Check for None in the input using a while loop
I am coding a Battleships game in Python and can use some help regarding the while loop to check whether a user has not input any data.
def getUserInput(self):
try:
x_row = input("Please Select the row coorinate (1-8)")
while x_row not... | Check for None in the input using a while loop | I am coding a Battleships game in Python and can use some help regarding the while loop to check whether a user has not input any data.
def getUserInput(self):
try:
x_row = input("Please Select the row coorinate (1-8)")
while x_row not in '12345678':
print("You are eithe... | [
"This occurance is quite interesting, because as of in python 3.11\nthe statement if input(\"some input here:\") == \"\":\\n print(\"nothing\")\\n else:\\n print(\"anything\") with an input of nothing returns nothing and with every else possible input returns anything.\nThis leaves us with two possibilities:\n\nYou... | [
0,
0
] | [] | [] | [
"is_empty",
"python",
"while_loop"
] | stackoverflow_0074423605_is_empty_python_while_loop.txt |
Q:
How to put an item into a dynamodb table using python?
so I'm trying to place a dictionary into a dynamodb table, yet I keep getting the error:
ERROR TypeError: cannot pickle '_thread.lock' object
The code is below:
def send_to_dynamo():
message = receive_from_queue()
database = boto3.resource('dynamodb'... | How to put an item into a dynamodb table using python? | so I'm trying to place a dictionary into a dynamodb table, yet I keep getting the error:
ERROR TypeError: cannot pickle '_thread.lock' object
The code is below:
def send_to_dynamo():
message = receive_from_queue()
database = boto3.resource('dynamodb')
table = database.Table("Email_Service")
logger.in... | [
"Looking at your issue it seems to be caused by a mix match of the JSON and the client you use. Your dict is using DynamoDB JSON, whereas you use Resource client which takes native JSON. Try save this:\ndict= {\n 'subject': \"Test email output\",\n 'recipients': \"email@email.com\",\n ... | [
0
] | [] | [] | [
"amazon_dynamodb",
"amazon_sqs",
"amazon_web_services",
"boto3",
"python"
] | stackoverflow_0074422397_amazon_dynamodb_amazon_sqs_amazon_web_services_boto3_python.txt |
Q:
How do you create a function to check the attribute of another field in a separate model?
class Trait(models.Model):
name = models.CharField(max_length=20)
animal_types = models.ManyToManyField(AnimalType)
# slots = models.CharField(default=None, null=True, max_length=4)
#slots is meant to hold a value ... | How do you create a function to check the attribute of another field in a separate model? | class Trait(models.Model):
name = models.CharField(max_length=20)
animal_types = models.ManyToManyField(AnimalType)
# slots = models.CharField(default=None, null=True, max_length=4)
#slots is meant to hold a value that determines where it can be placed in animal model
#i.e. null means anywhere, "2" means onl... | [
"you might want to try adding a model class to validate the data before inserting/updating into Animals & Traits\nclass AnimalTraits(models.Model):\n trait_name = models.ForeignKey(Trait)\n animal_type = models.ForeignKey(ANIMAL)\n slots = models.CharField(default=None, null=True, max_length=4)\n\nA sql query... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074423903_django_django_models_python.txt |
Q:
Improving background subtraction when encountering split objects in foreground masks
For a project I implemented a simple background subtraction using a median background estimation. The result is not bad, but often moving objects (people in my test examples) are cut in unconnected blobs.
I tried calling open and ... | Improving background subtraction when encountering split objects in foreground masks | For a project I implemented a simple background subtraction using a median background estimation. The result is not bad, but often moving objects (people in my test examples) are cut in unconnected blobs.
I tried calling open and close operations (I removed the close operation, because it seemed as if it wouldn't impro... | [
"I like the greyscale simplification.\nSimple is good.\nWe should make everything as simple as\npossible, but not simpler.\nLet's attack your model for a moment.\nAn evil clothing designer with an army\nof fashion models sends them walking\npast your camera, each wearing a red\nshirt that is slightly darker than\nt... | [
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074422225_opencv_python.txt |
Q:
Forcing python function parameters to not have order
I have a python function that takes a large amount of parameters :
def func(p1=0, p2=0, p3=0, p4=0, p5=0, ..., pN=0) -> None: pass
I wanted to force the user to set the parameters as keyword arguments.
I thought about one solution that seems off to me:
def func... | Forcing python function parameters to not have order | I have a python function that takes a large amount of parameters :
def func(p1=0, p2=0, p3=0, p4=0, p5=0, ..., pN=0) -> None: pass
I wanted to force the user to set the parameters as keyword arguments.
I thought about one solution that seems off to me:
def func(*_, p1=0, p2=0, p3=0, p4=0, p5=0, ..., pN=0) -> None: pas... | [
"This is already a standard method. It is defined in PEP3102\nIt's used in many libraries.\nTo give you one example: in pandas' drop function, all parameters after * are keywords only:\nDataFrame.drop(labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')\n\nNote that you don't... | [
2
] | [] | [] | [
"arguments",
"function",
"keyword_argument",
"python"
] | stackoverflow_0074424003_arguments_function_keyword_argument_python.txt |
Q:
Python - Extract Pay Ranges from job descriptions using Regex
I have a large panel data set that includes job descriptions. I would like to extract the wages/salaries from the job descriptions. However, there is a lot of variability in how the salaries are stated in the job descriptions. Here are a few examples:
“... | Python - Extract Pay Ranges from job descriptions using Regex | I have a large panel data set that includes job descriptions. I would like to extract the wages/salaries from the job descriptions. However, there is a lot of variability in how the salaries are stated in the job descriptions. Here are a few examples:
“The salary range in Colorado for this role is from USD $123,500 - $... | [
"Given the fact that in your answer you are stating that not all possible texts are contained in your example (for example using a text such as \"The budget this year will be from $150,000 to $200,000\") a regex will in my opinon not be the best approach for this issue. Under a NLP approach, you can use transformer... | [
4,
2
] | [] | [] | [
"pandas",
"python",
"regex"
] | stackoverflow_0074423899_pandas_python_regex.txt |
Q:
How can I access this div statement with Beautiful Soup?
First of all, I am not a coder so sorry in advance for a possible bad explanation.
I want to retrieve the html code inside the following div statement using Beautiful soup:
<div x-y-z> == $0
I usually would retrieve html code in soup like the following:
htm... | How can I access this div statement with Beautiful Soup? | First of all, I am not a coder so sorry in advance for a possible bad explanation.
I want to retrieve the html code inside the following div statement using Beautiful soup:
<div x-y-z> == $0
I usually would retrieve html code in soup like the following:
html = soup.find("div", class_="x-y-z")
My problem here is that ... | [
"You can use CSS selector:\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(\"<div x-y-z>Something</div>\", \"html.parser\")\n\nprint(soup.select_one(\"div[x-y-z]\"))\n\nPrints:\n<div x-y-z=\"\">Something</div>\n\n\nOr bs4 API:\nprint(soup.find(\"div\", {\"x-y-z\": True}))\n\nPrints:\n<div x-y-z=\"\">Somethin... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0074424116_beautifulsoup_html_python.txt |
Q:
scrape a specific div value with beautifulsoup in nested div
I currently try scrape a value at this specific website for a school project https://data.census.gov/cedsci/table?q=53706%20income&tid=ACSST5Y2020.S1901
it's the first one below if you search Median income (dollars), which should be the median income of ... | scrape a specific div value with beautifulsoup in nested div | I currently try scrape a value at this specific website for a school project https://data.census.gov/cedsci/table?q=53706%20income&tid=ACSST5Y2020.S1901
it's the first one below if you search Median income (dollars), which should be the median income of the area, the comp-id keep changing for some reason
This median in... | [
"Try with this:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n#set up Chrome driver\noptions=webdriver.ChromeOptions()\n\n\n#Define web driver as a Chrome driver... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium"
] | stackoverflow_0074423857_beautifulsoup_python_selenium.txt |
Q:
Python Pandas DataFrame: conditional column based on other column values
Description of the problem:
I'am trying to simulate a machine whose operation mode "B" occurs if "VALUE" is greater or equal to 5 in the last 3 previous time steps- which means "VALUE">= 5 for at least 3 minutes.The Operation mode "B" keeps t... | Python Pandas DataFrame: conditional column based on other column values | Description of the problem:
I'am trying to simulate a machine whose operation mode "B" occurs if "VALUE" is greater or equal to 5 in the last 3 previous time steps- which means "VALUE">= 5 for at least 3 minutes.The Operation mode "B" keeps to be "B" for the next time steps as long as "VALUE" is greater or equal to 5 a... | [
"Modified Solution. I edited my solution thanks to a subtle point made by dear mozway:\nimport pandas as pd\n\ndf2['status'] = df2['VALUE'].mask(df2['VALUE'].shift().rolling(3, min_periods=3).min() >= 5, 'B')\n\nm1 = df2['status'].shift().eq('B')\nm2 = df2['status'].shift(2).eq('B')\n\n\ndf2['status'] = (df2['statu... | [
1
] | [] | [] | [
"conditional_statements",
"counter",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074422930_conditional_statements_counter_dataframe_pandas_python.txt |
Q:
How can I get a specific field of a csv file?
I need a way to get a specific item(field) of a CSV. Say I have a CSV with 100 rows and 2 columns (comma seperated). First column emails, second column passwords. For example I want to get the password of the email in row 38. So I need only the item from 2nd column row... | How can I get a specific field of a csv file? | I need a way to get a specific item(field) of a CSV. Say I have a CSV with 100 rows and 2 columns (comma seperated). First column emails, second column passwords. For example I want to get the password of the email in row 38. So I need only the item from 2nd column row 38...
Say I have a csv file:
aaaaa@aaa.com,bbbbb
c... | [
"import csv\nmycsv = csv.reader(open(myfilepath))\nfor row in mycsv:\n text = row[1]\n\nFollowing the comments to the SO question here, a best, more robust code would be:\nimport csv\nwith open(myfilepath, 'rb') as f:\n mycsv = csv.reader(f)\n for row in mycsv:\n text = row[1]\n ............\n... | [
31,
8,
8,
8,
0,
0
] | [
"import csv\ninf = csv.reader(open('yourfile.csv','r'))\nfor row in inf:\n print row[1]\n\n"
] | [
-1
] | [
"csv",
"python"
] | stackoverflow_0005757743_csv_python.txt |
Q:
Get rid of extra comma added in the csv while updating column values
I wrote a code to update particular column values in the CSV through pandas data frame. After the code execution, what I see is an extra column added at the start. This comma causes a misalignment of my CSV structure. For e.g. I updated age colum... | Get rid of extra comma added in the csv while updating column values | I wrote a code to update particular column values in the CSV through pandas data frame. After the code execution, what I see is an extra column added at the start. This comma causes a misalignment of my CSV structure. For e.g. I updated age column value in the CSV as 30 which was 26 earlier for each of the rows, what I... | [
"If fixing the original CSV file is not an option, relabel the columns and drop the last one:\ndf.rename(columns=dict(zip(df.columns, df.columns[1:]))).dropna(axis=1)\n# Name Age Gender\n#0 Pratik 30 Male\n#1 Sarvesh 30 Male\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074423566_pandas_python.txt |
Q:
Python: Extract the key and value from a groupby statement in Pandas
I have this movie dataframe, i would like to group it so that i get the gerne that appears most in each year:
data = {'year' : [2000,2000,2001,2001, 2001,2001,2002,2002,2002,2002], 'movie': ['movie1','movie2', 'movie3', 'movie4', 'movie5', 'movie... | Python: Extract the key and value from a groupby statement in Pandas | I have this movie dataframe, i would like to group it so that i get the gerne that appears most in each year:
data = {'year' : [2000,2000,2001,2001, 2001,2001,2002,2002,2002,2002], 'movie': ['movie1','movie2', 'movie3', 'movie4', 'movie5', 'movie6', 'movie7', 'movie8', 'movie9', 'movie10'], 'genre': ['action', 'action'... | [
"you can use Series.mode:\ndfx=movie.groupby(['year'])['genre'].agg(pd.Series.mode)\nprint(dfx)\n'''\nyear genre\n2000 action\n2001 comedy\n2002 horror\n\n'''\nprint(type(movie.groupby(['year'])['genre']))\n'''\n<class 'pandas.core.groupby.generic.SeriesGroupBy'>\n'''\n\n"
] | [
2
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074424151_group_by_pandas_python.txt |
Q:
Adding to a starting value in a list each time for loop runs?
I'm trying to add value z to starting value x each time the following for loop runs. The output I'm expecting is 1000,1021,1042,1063... or x, x+z, x+z+z, x+z+z+z...
When I run the following, I only get 1000,1021 as the output.
Why am I only getting a li... | Adding to a starting value in a list each time for loop runs? | I'm trying to add value z to starting value x each time the following for loop runs. The output I'm expecting is 1000,1021,1042,1063... or x, x+z, x+z+z, x+z+z+z...
When I run the following, I only get 1000,1021 as the output.
Why am I only getting a list of two values when the range is 0-1000? I'm obviously very new t... | [
"The code in your query is independent of the loop variable i, the loop is running for 1000 times but it does not do anything.\nBefore the loop exits, it adds two elements to y i.e. x and sum(x,z), which are 1000 and 1021, hence you get the output [1000 1021]\nYou can try the below code to increment every time by z... | [
0
] | [] | [] | [
"addition",
"for_loop",
"python"
] | stackoverflow_0074424176_addition_for_loop_python.txt |
Q:
scipy.optimize curve_fit() won't converge even with proper parameters
I'm having trouble trying to find the parameters of a gaussian curve fit.
The site https://mycurvefit.com/ provides a good answer fairly quickly. However, my implementation with python's curve_fit(), from the scipy.optimize library, is not provi... | scipy.optimize curve_fit() won't converge even with proper parameters | I'm having trouble trying to find the parameters of a gaussian curve fit.
The site https://mycurvefit.com/ provides a good answer fairly quickly. However, my implementation with python's curve_fit(), from the scipy.optimize library, is not providing good results (even when inputting the answers).
For instance, the equa... | [
"your problem is to try to fit an equation with three unknowns (a, b and c), with three points, this can have sometimes convergence issues. You need to give more values in the arrays you use to fit, the number of point use for fitting should be at least one more than the number of unknowns, in your case the minimum... | [
0,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0074304917_python_scipy.txt |
Q:
unsuccessful installation of python-weka-wrapper3
I just want to install python-weka-wrapper3 package and I get the following error message (I also tried some other installations but still did not work):
Microsoft Windows [Version 10.0.19045.2251]
(c) Microsoft Corporation. Vse pravice pridržane.
C:\Users\lesko>p... | unsuccessful installation of python-weka-wrapper3 | I just want to install python-weka-wrapper3 package and I get the following error message (I also tried some other installations but still did not work):
Microsoft Windows [Version 10.0.19045.2251]
(c) Microsoft Corporation. Vse pravice pridržane.
C:\Users\lesko>pip install python-weka-wrapper3
Collecting python-weka-... | [
"Instead of compiling from source (always an issue under Windows), you could either install pre-compiled binaries or install through anaconda.\n"
] | [
0
] | [] | [] | [
"error_handling",
"python",
"python_3.x",
"weka"
] | stackoverflow_0074420953_error_handling_python_python_3.x_weka.txt |
Q:
Remove 10 Rows in Dataframe of each Label
I have a dataframe with 6 different labels and would like to remove 10 rows of each label and add this to another dataframe as a test data set and remove them from the original df. Would appreciate any help!
I am able to sample 10 rows of each label type
df_tester ... | Remove 10 Rows in Dataframe of each Label | I have a dataframe with 6 different labels and would like to remove 10 rows of each label and add this to another dataframe as a test data set and remove them from the original df. Would appreciate any help!
I am able to sample 10 rows of each label type
df_tester = pd.concat(g.sample(10) for idx, g in df.group... | [
"Assuming the indices are unique, you can use:\ndf_tester = df.groupby('Label').sample(n=10)\n\ndf = df.drop(df_tester.index)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074424177_dataframe_python.txt |
Q:
Parse error when importing csv dataframe with dask and pandas
I am trying to import a very large .csv file as:
import dask.dataframe as dd
import pandas as pd
#TO DO
dd_subf1_small = dd.read_csv('subf1_small.csv', dtype={'Unnamed: 0': 'float64','oecd_subfield':'object','paperid':'object'}, sep=None, engine = 'pyt... | Parse error when importing csv dataframe with dask and pandas | I am trying to import a very large .csv file as:
import dask.dataframe as dd
import pandas as pd
#TO DO
dd_subf1_small = dd.read_csv('subf1_small.csv', dtype={'Unnamed: 0': 'float64','oecd_subfield':'object','paperid':'object'}, sep=None, engine = 'python').persist()
but I am getting the following error:
-----------... | [
"As the error says, your CSV file probably contains rows with 5 values instead of 3.\nYou have two options:\n\nFound those rows and fix/remove them from the file. This might be challenging given the file is huge.\nuse paramter on_bad_lines=\"skip\" to let pandas skip them and continue loading the file.\n\nLearn mor... | [
1
] | [] | [] | [
"dask",
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074424037_dask_dataframe_pandas_python_python_3.x.txt |
Q:
Expert system in Python with certain order of questions
I need to create expert system and I have one question. I'm using experta from Python and 3.8.0 is my version of Python interpreter in PyCharm. Here is my simple code:
from experta import *
class Greetings(KnowledgeEngine):
@DefFacts()
def _initial_a... | Expert system in Python with certain order of questions | I need to create expert system and I have one question. I'm using experta from Python and 3.8.0 is my version of Python interpreter in PyCharm. Here is my simple code:
from experta import *
class Greetings(KnowledgeEngine):
@DefFacts()
def _initial_action(self):
yield Fact(action="greet")
yield... | [
"Salience allows to do this. This value, by default 0, determines the priority of the rule in relation to the others. Rules with a higher salience will be fired before rules with a lower one. That how we can order rules in our own way.\n"
] | [
1
] | [] | [] | [
"expert_system",
"python"
] | stackoverflow_0074394190_expert_system_python.txt |
Q:
Sums generated with given integers
I'm trying to make a program that calculates the different sums that can be generated with the given integers. I'm not quite getting the hang of things, and I don't really understand where and what to edit in the code.
I'm trying to follow the following rule (examples)
list [1,2,... | Sums generated with given integers | I'm trying to make a program that calculates the different sums that can be generated with the given integers. I'm not quite getting the hang of things, and I don't really understand where and what to edit in the code.
I'm trying to follow the following rule (examples)
list [1,2,3] has 6 possible sums: 1, 2, 3, 4, 5 an... | [
"There are mainly two things you might want to modify: (i) add the case where you append list2[0] itself, and (ii) use set to take unique numbers:\ndef sums(list2):\n if len(list2) == 1:\n return {list2[0]}\n else:\n new_list = [list2[0]] # NOTE THAT THIS LINE HAS BEEN CHANGED\n for x in ... | [
1
] | [] | [] | [
"python",
"sum"
] | stackoverflow_0074424041_python_sum.txt |
Q:
How to solve seaborn scatterplot ValueError: string of single character colors as a color sequence is not supported?
I am plotting a bunch of lines using seaborn to color them based on a variable, then I've done some peakfinding to label the specific peaks. For some reason, sns.lineplot works exactly as expected, ... | How to solve seaborn scatterplot ValueError: string of single character colors as a color sequence is not supported? | I am plotting a bunch of lines using seaborn to color them based on a variable, then I've done some peakfinding to label the specific peaks. For some reason, sns.lineplot works exactly as expected, however, when trying to use sns.scatterplot with almost identical parameters it throws a value error about my colors being... | [
"Updating seaborn and matplotlib worked, so my guess is that there was a bug that got corrected.\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0074405410_matplotlib_python_seaborn.txt |
Q:
How do I encrypt and decrypt a string in python?
I have been looking for sometime on how to encrypt and decrypt a string. But most of it is in 2.7 and anything that is using 3.2 is not letting me print it or add it to a string.
So what I'm trying to do is the following:
mystring = "Hello stackoverflow!"
encoded = ... | How do I encrypt and decrypt a string in python? | I have been looking for sometime on how to encrypt and decrypt a string. But most of it is in 2.7 and anything that is using 3.2 is not letting me print it or add it to a string.
So what I'm trying to do is the following:
mystring = "Hello stackoverflow!"
encoded = encode(mystring,"password")
print(encoded)
jgAKLJK34... | [
"I had troubles compiling all the most commonly mentioned cryptography libraries on my Windows 7 system and for Python 3.5.\nThis is the solution that finally worked for me.\nfrom cryptography.fernet import Fernet\nkey = Fernet.generate_key() #this is your \"password\"\ncipher_suite = Fernet(key)\nencoded_text = ci... | [
72,
40,
16,
13,
8,
3,
1,
0,
0
] | [
"For Encryption\n def encrypt(my_key=KEY, my_iv=IV, my_plain_text=PLAIN_TEXT): \n\n key = binascii.unhexlify('ce975de9294067470d1684442555767fcb007c5a3b89927714e449c3f66cb2a4')\n iv = binascii.unhexlify('9aaecfcf7e82abb8118d8e567d42ee86')\n\n padder = PKCS7Padder()\n padded_text = padder.en... | [
-4
] | [
"encryption",
"python",
"python_3.x"
] | stackoverflow_0027335726_encryption_python_python_3.x.txt |
Q:
python : How to add different markers to different Y values
I'm trying to visualize data where each X value has multiple Y values and I would like to distinguish each Y value visaully. This is the example code
xLables = ['A1','A2','A3','A4','A5']
YValues = [[1,2,3,4],[1,2,3,4,5,6,7],[1,2,3],[5,6,7],[1,2,3]]
X = [... | python : How to add different markers to different Y values | I'm trying to visualize data where each X value has multiple Y values and I would like to distinguish each Y value visaully. This is the example code
xLables = ['A1','A2','A3','A4','A5']
YValues = [[1,2,3,4],[1,2,3,4,5,6,7],[1,2,3],[5,6,7],[1,2,3]]
X = [xLables[i] for i, data in enumerate(YValues) for j in range(len(d... | [
"\nMy solution is particularly ad hoc, but it replicates your target drawing using your data, so that I feel confident posting her here.\nimport matplotlib.pyplot as plt\n\nlabels = ['A1','A2','A3','A4','A5']\nY2D = [[1,2,3,4],[1,2,3,4,5,6,7],[1,2,3],[5,6,7],[1,2,3]]\n\n# prepare a dictionary with the characteristi... | [
3,
2,
1,
0
] | [] | [] | [
"matplotlib",
"plot",
"python",
"scatter_plot"
] | stackoverflow_0074421500_matplotlib_plot_python_scatter_plot.txt |
Q:
Why does my very basic Python file give an import error?
I am experimenting with using assert testing but it seems like importing modules isn't working for my code unless I do it a very specific, but seemingly identical (in terms of what it actually does) way.
I have one file named gz.py, which has the following l... | Why does my very basic Python file give an import error? | I am experimenting with using assert testing but it seems like importing modules isn't working for my code unless I do it a very specific, but seemingly identical (in terms of what it actually does) way.
I have one file named gz.py, which has the following lines of code:
def sumnum(a,b):
return a+b
I also have a f... | [
"Calling the test_sumnum() function in test_x.py seems to work. I have updated the script to\nimport pytest\nfrom gz import sumnum\n\ndef test_sumnum():\n assert sumnum(5,5) == 11,'wrong'\ntest_sumnum()\n\n#Output\nTraceback (most recent call last):\n File \"test_x.py\", line 6, in <module>\n test_sumnum()\n... | [
0
] | [] | [] | [
"assert",
"import",
"module",
"python"
] | stackoverflow_0074424281_assert_import_module_python.txt |
Q:
Flask server - no access for other devices on the network
The Flask server is up and running on my laptop (Ubuntu), with debugger ON:
(venv) deeman@carbon:~/flask_dir/venv/dox$ flask --app hello_w run
* Serving Flask app 'hello_w'
* Debug mode: on
WARNING: This is a development server. Do not use it in a produc... | Flask server - no access for other devices on the network | The Flask server is up and running on my laptop (Ubuntu), with debugger ON:
(venv) deeman@carbon:~/flask_dir/venv/dox$ flask --app hello_w run
* Serving Flask app 'hello_w'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Runni... | [] | [] | [
"Thank you all. @DaveW.Smith provide the solution in my case, which was:\nto simply pass --host=0.0.0.0 as an argument, as bellow:\n$ flask --app hello_w run --host=0.0.0.0\n"
] | [
-1
] | [
"flask",
"python"
] | stackoverflow_0074423925_flask_python.txt |
Q:
Calculate cumulative count of a pandas dataframe column
I have created this pandas dataframe:
import numpy as np
import pandas as pd
ds = {"col1":[1,2,3,2,2,2,3,4,1,0,0,0,0,0,1,2,3,5]}
df = pd.DataFrame(data=ds)
which looks like this:
print(df)
col1
0 1
1 2
2 3
3 2
4 2
5 2
6 ... | Calculate cumulative count of a pandas dataframe column | I have created this pandas dataframe:
import numpy as np
import pandas as pd
ds = {"col1":[1,2,3,2,2,2,3,4,1,0,0,0,0,0,1,2,3,5]}
df = pd.DataFrame(data=ds)
which looks like this:
print(df)
col1
0 1
1 2
2 3
3 2
4 2
5 2
6 3
7 4
8 1
9 0
10 0
11 0
12 0
1... | [
"Consider using cumcount() after groupby(). Add +1 to start counting from 1 instead of 0:\ndf['col2'] = df.groupby('col1').cumcount()+1\n\nReturns:\n col1 col2\n0 1 1\n1 2 1\n2 3 1\n3 2 2\n4 2 3\n5 2 4\n6 3 2\n7 4 1\n8 1 2\n9 ... | [
1,
1
] | [] | [] | [
"cumulative_frequency",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074424343_cumulative_frequency_dataframe_pandas_python.txt |
Q:
TSNE plot dissapears quickly
i would like to use t-SNE algorithm on mnist dataset for purpose of dimension reduction, later i want to use reduced data for visualization purpose(possible clustering or classification), here is my code :
`import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from ... | TSNE plot dissapears quickly | i would like to use t-SNE algorithm on mnist dataset for purpose of dimension reduction, later i want to use reduced data for visualization purpose(possible clustering or classification), here is my code :
`import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
impor... | [
"i tried a few experiment and found solution : set block argument as true and here is result\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\nimport seaborn as sns\nfrom sklearn.preprocessing import StandardScaler\ndf =pd.read_csv('mnist_train.csv')\... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074424278_matplotlib_python.txt |
Q:
Can Python Embeddable Package Install IDLE Separately?
A Python embeddable package can install pip separately (pip with embedded python), but can it also install IDLE separately? As the embeddable package has pythonw.exe already, I tried to externally load idle.pyw with it, but more seem to be needed.
A:
The IDL... | Can Python Embeddable Package Install IDLE Separately? | A Python embeddable package can install pip separately (pip with embedded python), but can it also install IDLE separately? As the embeddable package has pythonw.exe already, I tried to externally load idle.pyw with it, but more seem to be needed.
| [
"The IDLE IDE is part of the CPython standard library. It is usually an option packaged with tkinter, _tkinter, and, on Windows and Mac, an appropriate version of tcl/tk. Unless embedded Python comes with tkinter and _tkinter and tcl/tk is available, installing IDLE would be useless as well as difficult. It is n... | [
0
] | [] | [] | [
"embeddable",
"python",
"python_idle"
] | stackoverflow_0074418849_embeddable_python_python_idle.txt |
Q:
How to change the underscores to letters in python hangman?
I am working on a hangmen project in python. However I do not know how to change the underlines to the letters inside the word if guessed properly. Here is my code:
import random
#pick word
with open("Words.txt", "r") as file:
allText = file.read()
... | How to change the underscores to letters in python hangman? | I am working on a hangmen project in python. However I do not know how to change the underlines to the letters inside the word if guessed properly. Here is my code:
import random
#pick word
with open("Words.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
word = random.choic... | [
"Rather than keeping a word of underscores and replace guessed letters in it, just regenerate the display word each round, generating by going over the answer word letter by letter, and for every letter that is in your guessed letters list, copy the correct letter and for letters that haven't been guessed, replace ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074424323_python.txt |
Q:
How can I sort a list of String based on character inside of them?
I have a list of Strings that looks like that:
['training_tech26.txt', 'training_tech41.txt', 'training_tech68.txt', 'training_tech84.txt', 'training_tech52.txt', 'training_sales17.txt', 'training_sales2.txt', 'training_tech47.txt', 'training_sales... | How can I sort a list of String based on character inside of them? | I have a list of Strings that looks like that:
['training_tech26.txt', 'training_tech41.txt', 'training_tech68.txt', 'training_tech84.txt', 'training_tech52.txt', 'training_sales17.txt', 'training_sales2.txt', 'training_tech47.txt', 'training_sales23.txt', 'training_sales3.txt', 'training_tech9.txt', 'training_tech12.t... | [
"There is python third party library for string natural sorting called natsort:\nfrom natsort import natsorted\ntech_res = ['training_tech26.txt', 'training_tech41.txt', 'training_tech68.txt', 'training_tech84.txt', 'training_tech52.txt', 'training_sales17.txt', 'training_sales2.txt', 'training_tech47.txt', 'traini... | [
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074424201_list_python.txt |
Q:
List of strings replace each instance of a certain value in each string with another value
I have a list of times of events in strings (i.e. ['Apr 24th 10:00 p.m.','Apr 26th 7:00 p.m.']).
I'd like to replace each instance of the number 10 with the number 7, 8 with the number 5 etc. Is there any way to have a list ... | List of strings replace each instance of a certain value in each string with another value | I have a list of times of events in strings (i.e. ['Apr 24th 10:00 p.m.','Apr 26th 7:00 p.m.']).
I'd like to replace each instance of the number 10 with the number 7, 8 with the number 5 etc. Is there any way to have a list of values (i.e. [10,9,8,7,6,5]) that wherever one of those values is found in a string then that... | [
"Yes, there is a cleaner way to do it. Also, it will prevent many headeaches, such as changing PM to AM or changing the date, things like that. Instead of manipulating the string, simply use the datetime package.\nFirst, you need to modify your strings so they can be in a format that can be recognized as a datetime... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074423822_python.txt |
Q:
Tensorflow Keras TypeError: Cannot instantiate typing_extensions.Concatenate
I'm creating a model using Tensorflow and Keras, this is code I have copied from a tutorial, but I'm receiving this error:
TypeError: Cannot instantiate typing_extensions.Concatenate
This is the code that returns this error.
from numpy im... | Tensorflow Keras TypeError: Cannot instantiate typing_extensions.Concatenate | I'm creating a model using Tensorflow and Keras, this is code I have copied from a tutorial, but I'm receiving this error:
TypeError: Cannot instantiate typing_extensions.Concatenate
This is the code that returns this error.
from numpy import zeros
from numpy import ones
from numpy.random import randn
from numpy.random... | [
"It seems that replacing\nmerge = Concatenate()([in_image, li])\n\nwith\nmerge = tf.concat(([in_image, li]), axis=3)\n\nfixes this.\n"
] | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074423991_keras_python_tensorflow.txt |
Q:
sklearn module not found when using VSCode, but works fine in Jupyter Notebook?
I have looked at several questions and tried their respective answers, but I cannot seem to understand why VSCode is unable to find the sklearn module.
I use a virtual conda environment called ftds, in which I have scikit-learn success... | sklearn module not found when using VSCode, but works fine in Jupyter Notebook? | I have looked at several questions and tried their respective answers, but I cannot seem to understand why VSCode is unable to find the sklearn module.
I use a virtual conda environment called ftds, in which I have scikit-learn successfully show up when I run conda list. In jupyter notebook, I use the same ftds environ... | [
"I figured out the issue: the python library name for sklearn is scikit-learn\nInstalling scikit-learn with pip install scikit-learn.\nI saw that after typing pip show sklearn it says that the package is deprecated in favor of scikit-learn. So i tried installing that after which sklearn worked with no problems.\n",... | [
1,
0,
0
] | [] | [] | [
"anaconda",
"python",
"scikit_learn",
"visual_studio_code"
] | stackoverflow_0073208411_anaconda_python_scikit_learn_visual_studio_code.txt |
Q:
Python Tkinter and loops
I am trying to write a program that would help me practice my vocabulary. Basically I want to have it display a window once every 30 minutes which contains the words i'm currently learning. Here's my code:
import time
from tkinter import *
window = Tk()
date = time.ctime()
text = Text(win... | Python Tkinter and loops | I am trying to write a program that would help me practice my vocabulary. Basically I want to have it display a window once every 30 minutes which contains the words i'm currently learning. Here's my code:
import time
from tkinter import *
window = Tk()
date = time.ctime()
text = Text(window, width=40, height=10)
wind... | [
"Im also new to python and never touched tkinter. The code works as intended if you place all lines inside the while loop. Any downside to this?\n"
] | [
1
] | [] | [] | [
"loops",
"python",
"tkinter",
"window"
] | stackoverflow_0074424362_loops_python_tkinter_window.txt |
Q:
Why am I getting IndexError: list index out of range error even though I have a proper list
with open('Input','r') as f:
while len(a)>0:
a=f.readline() #I am going to search for a command to execute in the txt file
w_in_line=a.split(',') #words in line
command_word_box=w_in_line[0].s... | Why am I getting IndexError: list index out of range error even though I have a proper list | with open('Input','r') as f:
while len(a)>0:
a=f.readline() #I am going to search for a command to execute in the txt file
w_in_line=a.split(',') #words in line
command_word_box=w_in_line[0].split()#I took the command word out of the line
command_word=str(command_word_box[0])
... | [
"The problem happens when you read the last (blank!) line of the file. You check the condition len(a) before reading the next line, which is too early. Solution:\na=f.readline()\nwhile len(a) > 0:\n w_in_line=a.split(',') #words in line\n # The rest of your loop here\n a=f.readline()\n\nA much better appro... | [
1
] | [] | [] | [
"index_error",
"python",
"python_3.x"
] | stackoverflow_0074424451_index_error_python_python_3.x.txt |
Q:
Need to find only first href of each product
I need to get only the first href of each product.
Can someone give me a hint? Now i get more than one href of each
import requests
from bs4 import BeautifulSoup
baseurl = 'https://www.roco.cc/'
headers = {
'UserAgent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKi... | Need to find only first href of each product | I need to get only the first href of each product.
Can someone give me a hint? Now i get more than one href of each
import requests
from bs4 import BeautifulSoup
baseurl = 'https://www.roco.cc/'
headers = {
'UserAgent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.15... | [
"Try:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.roco.cc/ren/products/locomotives/steam-locomotives.html?p={}\"\n\n\nproductlinks = []\nfor p in range(1, 3): # <--- increase number of pages here\n soup = BeautifulSoup(requests.get(url.format(p)).content, \"html.parser\")\n\n for... | [
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074424488_python_web_scraping.txt |
Q:
Automatic insertion of a colon after 'def', 'if' etc
I recently switched to Vim at the request of a friend after Sublime Text 2 decided it didn't believe a module was installed even though it was...I digress.
I've managed to set up some stuff to make editing Python (currently me only language) easier. However, the... | Automatic insertion of a colon after 'def', 'if' etc | I recently switched to Vim at the request of a friend after Sublime Text 2 decided it didn't believe a module was installed even though it was...I digress.
I've managed to set up some stuff to make editing Python (currently me only language) easier. However, there's one feature I'm missing from Sublime. It would automa... | [
"Rather than use imaps like @CG Mortion's answer suggests, I would strongly advise you to use iabbrs for these sorts of small fixes instead.\nWith an imap you would never be able to type \"define\" in insert mode unless you paused between pressing 'd', 'e', or 'f', or did one of a number of other hacky things to pr... | [
8,
6,
1,
0,
0,
0
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0011507039_python_vim.txt |
Q:
How To Run Nested Async Functions In Python?
Can anyone help me figure out how to run MethodTwo() asynchronously with the rest of the program?
Here is the code:
import asyncio
from asgiref.sync import sync_to_async
def MethodTwo():
print("MethodTwo")
async def MethodOne():
print("MethodOne")
await sy... | How To Run Nested Async Functions In Python? | Can anyone help me figure out how to run MethodTwo() asynchronously with the rest of the program?
Here is the code:
import asyncio
from asgiref.sync import sync_to_async
def MethodTwo():
print("MethodTwo")
async def MethodOne():
print("MethodOne")
await sync_to_async(MethodTwo)()
async def Main():
pr... | [
"With the asyncio.to_thread() method (added in Python3.10) this is easy.\nimport asyncio\nimport time\n\ndef MethodTwo():\n print(\"MethodTwo\")\n time.sleep(2.0)\n print(\"MethodTwo done\")\n\nasync def MethodOne():\n print(\"MethodOne\")\n await asyncio.sleep(2.5)\n print(\"MethodOne done\")\n\n... | [
0
] | [] | [] | [
"python",
"python_2.x",
"python_3.x",
"python_asyncio"
] | stackoverflow_0074414873_python_python_2.x_python_3.x_python_asyncio.txt |
Q:
How to collect the responses from aiohttp sessions
I'm working with asyncio and aiohttp to call an API many times. While can print the responses, I want to collate the responses into a combined structure - a list or pandas dataframe etc.
In my example code I'm connecting to 2 urls and printing a chunk of the resp... | How to collect the responses from aiohttp sessions | I'm working with asyncio and aiohttp to call an API many times. While can print the responses, I want to collate the responses into a combined structure - a list or pandas dataframe etc.
In my example code I'm connecting to 2 urls and printing a chunk of the response. How can I collate the responses and access them al... | [
"Thanks @python_user that's exactly what I was missing and the returned type is indeed a simple list. I think I'd tried to pick up the responses inside the await part which doesn't work.\nMy updated PoC code below.\nAdapting this for the API, JSON and pandas should now be easy : )\nimport asyncio, aiohttp\n\nasync ... | [
1
] | [] | [] | [
"aiohttp",
"python",
"python_asyncio"
] | stackoverflow_0074411118_aiohttp_python_python_asyncio.txt |
Q:
How to set allow_null=True for all ModelSerializer fields in Django REST framework
I have a ModelSerializer . I want to set allow_null=True for all of the fields of the serializer . But I don't want to do it manually, I mean- I don't want to write allow_null=True for every field . Is there any shortcut? Is there a... | How to set allow_null=True for all ModelSerializer fields in Django REST framework | I have a ModelSerializer . I want to set allow_null=True for all of the fields of the serializer . But I don't want to do it manually, I mean- I don't want to write allow_null=True for every field . Is there any shortcut? Is there anything like read_only_fields=() ?
This is my Serializer
class ProductPublicListSerializ... | [
"I think you can achieve it by overriding get_fields in your ModelSerializer class, so:\nclass ProductPublicListSerializer(serializers.ModelSerializer):\n ...\n def get_fields(self):\n fields = dict(super().get_fields())\n for field_name, field_class in fields.items():\n field_class.a... | [
2
] | [] | [] | [
"django",
"django_rest_framework",
"django_serializer",
"python",
"serialization"
] | stackoverflow_0074420830_django_django_rest_framework_django_serializer_python_serialization.txt |
Q:
Storing multiple arrays in a np.zeros or np.ones
I'm trying to initialize a dummy array of length n using np.zeros(n) with dtype=object. I want to use this dummy array to store n copies of another array of length m.
I'm trying to avoid for loop to set values at each index.
I tried using the below code but keep get... | Storing multiple arrays in a np.zeros or np.ones | I'm trying to initialize a dummy array of length n using np.zeros(n) with dtype=object. I want to use this dummy array to store n copies of another array of length m.
I'm trying to avoid for loop to set values at each index.
I tried using the below code but keep getting error -
temp = np.zeros(10, dtype=object)
arr = n... | [
"np.tile() is a built-in function that repeats a given array reps times. It looks like this is exactly what you need, i.e.:\nres = np.tile(arr, 2)\n\n",
">>> arr = np.array([1.1,1.2,1.3,1.4,1.5])\n>>> arr\narray([1.1, 1.2, 1.3, 1.4, 1.5])\n>>> np.array([arr]*10)\n\narray([[1.1, 1.2, 1.3, 1.4, 1.5],\n [1.1,... | [
0,
0
] | [] | [] | [
"numpy_ndarray",
"python"
] | stackoverflow_0074424631_numpy_ndarray_python.txt |
Q:
Getting lenght of the list
My current program prints all the different sums that are generated with the given integers. Instead of the program printing the content of the list, I would want to print only the lenght of the list.
def sums(items):
if len(items) == 1:
return items
else:
new_li... | Getting lenght of the list | My current program prints all the different sums that are generated with the given integers. Instead of the program printing the content of the list, I would want to print only the lenght of the list.
def sums(items):
if len(items) == 1:
return items
else:
new_list = []
for i in items:
... | [
"Use len()\nif __name__ == \"__main__\":\n print(len(sums([1, 2, 3]))) \n print(len(sums([2, 2, 3]))) \n\n",
"Do not change the function, you are getting the error because it is recursive (returning value is important), change this section instead\nif __name__ == \"__main__\":\n print(len(... | [
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074424661_list_python.txt |
Q:
Why does 2d index update a list but not 1d?
I am trying to understand indexing in a list. I try:
x= [1,2,3,[4]]
x[0]=[34]
x[3][0]=95
which gives
[1, 2, 3, [95]]
but why is it not:
[34 2, 3, [95]]
?
Edit: apologies my code was:
x= [1,2,3,[4]]
y=list(x)
x[0]=[34]
x[3][0]=95
print (y)
Which gives the results I st... | Why does 2d index update a list but not 1d? | I am trying to understand indexing in a list. I try:
x= [1,2,3,[4]]
x[0]=[34]
x[3][0]=95
which gives
[1, 2, 3, [95]]
but why is it not:
[34 2, 3, [95]]
?
Edit: apologies my code was:
x= [1,2,3,[4]]
y=list(x)
x[0]=[34]
x[3][0]=95
print (y)
Which gives the results I stated.
| [
"In this case, I believe python list mutability doing strange things.\nWhen you call\ny = list(x)\n\nIt copies each element in the list x over to the list y.\nThis means it avoids mutability in the first dimension, but because the third element is copied normally under the hood, and it is a list, it remains mutable... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074404847_python.txt |
Q:
Recursively rename .json files sequentially in subdirectories
I am trying to rename a bunch of .JSON files that exist in subfolders in my Google Drive by traversing the root folder with glob function. Since there are thousands of subfolders,
There are two issues I am having with the code I am running to rename tho... | Recursively rename .json files sequentially in subdirectories | I am trying to rename a bunch of .JSON files that exist in subfolders in my Google Drive by traversing the root folder with glob function. Since there are thousands of subfolders,
There are two issues I am having with the code I am running to rename those files:
First issue is when running the code (even without the re... | [
"The first issue is due to the fact that glob does not return files in the order you expect. The most efficient way to fix this depends on the structure of the original filenames.\nThe second issue is due to the fact that you do not take into account the path the file to be renamed is located in and always use src ... | [
0
] | [] | [] | [
"google_colaboratory",
"python"
] | stackoverflow_0074424315_google_colaboratory_python.txt |
Q:
How to exclude null values in queryset for charts.js
I am trying to get the count of infringements in the market place for the logged in user.
The logged user is part of a group. The problem I am having is its still counting values for marketplace items that doesn't belong to the group. It adds 0 in the queryset b... | How to exclude null values in queryset for charts.js | I am trying to get the count of infringements in the market place for the logged in user.
The logged user is part of a group. The problem I am having is its still counting values for marketplace items that doesn't belong to the group. It adds 0 in the queryset breaking my charts,
u = request.user.groups.all()[0].id
m... | [
"You can filter out the Marketplaces, so not in the .annotate(..) clause [Django-doc]:\nu = request.user.groups.all()[0].id\nmar_count = Marketplace.objects.filter(groups=u).annotate(\n infringement_count=Count('infringement')\n)\nThe count will always be one (or zero if ingrigment is None).\nOne of the problems... | [
3
] | [] | [] | [
"django",
"exclude_constraint",
"filtering",
"python"
] | stackoverflow_0074424645_django_exclude_constraint_filtering_python.txt |
Q:
Find exact change project
I'm doing a lab for school to find the exact change. For example 126 is the input the answer would be 1 dollar 1 quarter 1 penny. grammar matters too. I can't get the pennies part to work. It seems to stop working after 104. Also, I'm sure there are simpler ways to write the code, but thi... | Find exact change project | I'm doing a lab for school to find the exact change. For example 126 is the input the answer would be 1 dollar 1 quarter 1 penny. grammar matters too. I can't get the pennies part to work. It seems to stop working after 104. Also, I'm sure there are simpler ways to write the code, but this is all we learned so far.
mon... | [
"if you did this for the pennies it should work. I am sure this is a bit late, I'm taking the same class now. but hopefully this helps the next person.\nif remaining_cents >=1:\n pennies = remaining_cents // 1\n remaining_cents = pennies\n if pennies > 1:\n print(remaining_cents, 'Pennies')\n eli... | [
0
] | [] | [] | [
"coin_change",
"python"
] | stackoverflow_0070706402_coin_change_python.txt |
Q:
How to use pdb correctly without executing the whole file first
This is my .pdbrc file contents:
b 2
c
This is my code.py contents:
print('1st line')
print('2nd line')
print('3rd line')
And when I run this command in terminal:
python3 -m pdb code.py
I get this output:
1st line
2nd line
3rd line
Breakpoint 1 at /... | How to use pdb correctly without executing the whole file first | This is my .pdbrc file contents:
b 2
c
This is my code.py contents:
print('1st line')
print('2nd line')
print('3rd line')
And when I run this command in terminal:
python3 -m pdb code.py
I get this output:
1st line
2nd line
3rd line
Breakpoint 1 at /Users/mypc/code.py:2
1st line
> /Users/mypc/code.py(2)<module>()
-> p... | [
"Name your file (almost) anything other than code.py.\nThe problem is that code.py is a Python core module:\n\nNAME\ncode - Utilities needed to emulate Python's interactive interpreter.\nMODULE REFERENCE\nhttps://docs.python.org/3.10/library/code.html\n\nThis module is used by pdb, so when you name your file code.p... | [
1
] | [] | [] | [
"pdb",
"python"
] | stackoverflow_0074424564_pdb_python.txt |
Q:
Open Whatsapp Windows app directly from python program using url
According to this FAQ page of Whatsapp on How to link to WhatsApp from a different app
Using the URL
whatsapp://send?phone=XXXXXXXXXXXXX&text=Hello
can be used to open the Whatsapp app on a Windows PC and perform a custom action.
It does work when it... | Open Whatsapp Windows app directly from python program using url | According to this FAQ page of Whatsapp on How to link to WhatsApp from a different app
Using the URL
whatsapp://send?phone=XXXXXXXXXXXXX&text=Hello
can be used to open the Whatsapp app on a Windows PC and perform a custom action.
It does work when it is opened in a browser. The URL opens Whatsapp installed and composes... | [
"You can use cmd exe to do such a job. Just try\nimport subprocess\n\nsubprocess.Popen([\"cmd\", \"/C\", \"start whatsapp://send?phone=XXXXXXXXXXXXX&text=Hello\"], shell=True)\n\nedit:\nif you want to pass '&'(ampersand) in cmd shell you need to use escape char '^' for it.\nplease try that one\nsubprocess.Popen([\"... | [
3
] | [
"Using this command\nstart whatsapp://send?phone=XXXXXXXXXXXXX^&text=Hello\nnot working after updated to new WhatsApp Desktop App (UWP) for windows.\nyou have other idea for send text message to destination user.\n"
] | [
-2
] | [
"automation",
"python",
"url",
"whatsapp",
"windows"
] | stackoverflow_0063583084_automation_python_url_whatsapp_windows.txt |
Q:
Python Dictionary - using input to add up all of the values in a dictionary
I am about half way through an intro to python course. I very recently started studying lists/dictionaries. I was trying to create my own python code to try to learn how to work with dictionaries better. Basically, what I am trying to do i... | Python Dictionary - using input to add up all of the values in a dictionary | I am about half way through an intro to python course. I very recently started studying lists/dictionaries. I was trying to create my own python code to try to learn how to work with dictionaries better. Basically, what I am trying to do is get a user's input as to what section of a video series they are on and then ou... | [
"Your code looks so close to being correct. I made a slight modification, but otherwise it's all your code:\nvideo_dict = {\n 1 : 9, # Section 1 is 9 minutes\n 2 : 75,\n 3 : 174,\n 4 : 100\n}\n\n\n\ncurrent_section = int(input('What section are you currently on?'))\n\ntotal_time = 0\nfor key, value i... | [
2,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074424693_dictionary_python.txt |
Q:
List of Lists with one Element in each list turn to list of items that aren't lists
I have a list of lists each of those lists having one element. Is there a "pythonic" way to turn this into a list of elements that aren't lists outside of using the loop displayed below?
un_list = []
for x in home_times:
y=x[0]... | List of Lists with one Element in each list turn to list of items that aren't lists | I have a list of lists each of those lists having one element. Is there a "pythonic" way to turn this into a list of elements that aren't lists outside of using the loop displayed below?
un_list = []
for x in home_times:
y=x[0]
un_list.append(y)
| [
"You can use list comprehension like this:\nsample_input = [[1], [2], [3]] # list of lists having one element\noutput = [i[0] for i in sample_input]\n\nAnd this is the output:\n[1, 2, 3]\n\nRead more about list comprehension here.\n",
"Another way, using sum function.\nlst=[['5'], [3],['7'],['B'],[4]]\noutput= s... | [
0,
0
] | [] | [] | [
"arrays",
"iteration",
"list",
"python"
] | stackoverflow_0074424704_arrays_iteration_list_python.txt |
Q:
Object post has no attribute post.title - API attribute error
Building an API and getting an error that doesn't make sense. Here is the code:
from typing import Optional
from fastapi import Body, FastAPI, Response,status
import psycopg2
import time
from pydantic import BaseModel
from psycopg2.extras import RealD... | Object post has no attribute post.title - API attribute error | Building an API and getting an error that doesn't make sense. Here is the code:
from typing import Optional
from fastapi import Body, FastAPI, Response,status
import psycopg2
import time
from pydantic import BaseModel
from psycopg2.extras import RealDictCursor
app = FastAPI()
while True:
try :
conn=psyco... | [
"The error says it all post has no attribute title, which is triggered on the line\ncursor.execute(\"\"\"insert into posts (title,content,published) VALUES(%s,%s,%s) RETURNING * \"\"\",(post.title,post.content,post.published))\nThe variable post does not have the field title (and I guess the other two as well).\nTh... | [
1
] | [] | [] | [
"api",
"fastapi",
"postgresql",
"python"
] | stackoverflow_0074424322_api_fastapi_postgresql_python.txt |
Q:
remove entry in counter object if value meets condition
Is there a way to remove entries from a counter object if the value matches a certain condition. For example:
Counter({'a': 1142,'b':1004,'c':100,'d':5})
I want to drop all indexes where it is less than 1000, so I just have 'a' and 'b' left. I know I can loo... | remove entry in counter object if value meets condition | Is there a way to remove entries from a counter object if the value matches a certain condition. For example:
Counter({'a': 1142,'b':1004,'c':100,'d':5})
I want to drop all indexes where it is less than 1000, so I just have 'a' and 'b' left. I know I can loop through each and then delete if it doesnt match the conditi... | [
"I think it can be useful for you:\nfrom collections import Counter\ncounter = Counter({'a': 1142, 'b': 1004, 'c': 100, 'd':5})\nCounter({k: c for k, c in counter.items() if c >= 1000})\n\nOutput:\nCounter({'a':1142 , 'b': 1004})\n\nThis way is more effective as you mentioned.\n",
"You can use a simple loop to de... | [
1,
0
] | [] | [] | [
"counter",
"python"
] | stackoverflow_0074424846_counter_python.txt |
Q:
How to avoid overlapping of dates in a mysql table
I am making a movie theatre management system in Python using mySQL and I need to make it so that if a datetime range is to be inserted such that it overlaps with another show that an error would be brought up.
For example, if I have a certain movie at 8PM in hall... | How to avoid overlapping of dates in a mysql table | I am making a movie theatre management system in Python using mySQL and I need to make it so that if a datetime range is to be inserted such that it overlaps with another show that an error would be brought up.
For example, if I have a certain movie at 8PM in hall 1, and if i tried to insert another movie at the same t... | [
"This can be done in a 3-step process:\n\nIdentify available time slots based on current schedule\nCheck if the new schedule fits in available time slots\nInsert the new schedule if a time slot available\n\nFirst, simplify the schema and sample data to focus on the main question (note that reserved schedules are in... | [
0
] | [] | [] | [
"mysql",
"overlap",
"python"
] | stackoverflow_0074423716_mysql_overlap_python.txt |
Q:
How to write many rows to excel file portion by portion to decrease consumption of RAM
I want to write ~500.000 rows to excel file with openpyxl. These rows are generated on flight (all of them can't be stored in RAM simultaneously because of big size). So I want to generate first 50.000 rows (which I can store in... | How to write many rows to excel file portion by portion to decrease consumption of RAM | I want to write ~500.000 rows to excel file with openpyxl. These rows are generated on flight (all of them can't be stored in RAM simultaneously because of big size). So I want to generate first 50.000 rows (which I can store in memory) and dump them to file on disk. Then I want to delete these rows from RAM, generate ... | [
"Can't say for sure, try putting the row content filling logic into a function, what you call many times(500 000) after it.\nimport openpyxl\n\ndef row_content(sheet):\n row = []\n # ... Fill row with data\n sheet.append(row)\n\nbook = openpyxl.Workbook()\nbook.remove(book.active)\nsheet = book.create_shee... | [
0
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0074424655_openpyxl_python.txt |
Q:
Extract nodes from json based on user input
I need to extract object from the given json based on the node chain passed by user and neglect those which are not in
user input, then create a new json object
my master json is :
{
"menustructure":
[
{
"node":"Admin",
"pat... | Extract nodes from json based on user input | I need to extract object from the given json based on the node chain passed by user and neglect those which are not in
user input, then create a new json object
my master json is :
{
"menustructure":
[
{
"node":"Admin",
"path":"admin",
"child":[
... | [
"Glom addresses exactly this problem.\n"
] | [
0
] | [] | [] | [
"glom",
"json",
"python",
"python_3.x"
] | stackoverflow_0074423257_glom_json_python_python_3.x.txt |
Q:
How to remove 2 buttons by pressing one?
I want to remove the buttons "play" and "help" by pressing just on button "play". How can I do that? I need that the button "play" destroy himself and in addition destroy the button "help"
This is my code:
from tkinter import *
import tkinter.messagebox
from random import *... | How to remove 2 buttons by pressing one? | I want to remove the buttons "play" and "help" by pressing just on button "play". How can I do that? I need that the button "play" destroy himself and in addition destroy the button "help"
This is my code:
from tkinter import *
import tkinter.messagebox
from random import *
window = Tk()
window.title("Simon")
window.ge... | [
"I would make a click_play_button function\ndef click_play_button():\n start_btn.destroy()\n help_btn.destroy()\n\nAnd call on it when pressing the play button\nstart_btn = Button(window, width=12, height=2, text=\"Play\",\n bg=\"grey\", font=(\"Ariel\", 18), command=click_play_button)\nstar... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074424821_python_tkinter.txt |
Q:
Fastapi How to restrict token creation to defined users
I have a dictionary of users with (username, password) as key, value pair.
i would like to restrict the authorisation creation to only users in my dictionary.
So any other user who is not in the dictionary shouldn't be able to create a token.
I try this but i... | Fastapi How to restrict token creation to defined users | I have a dictionary of users with (username, password) as key, value pair.
i would like to restrict the authorisation creation to only users in my dictionary.
So any other user who is not in the dictionary shouldn't be able to create a token.
I try this but it's not working, I can still create token to a new user.
... | [
"You never compare anything against form_data.username - the only thing you do is that you start looping over the user, and you check whether the first users password match - well, the user's password. This will always be true.\nInstead, retrieve the user you're looking for and compare the password if present:\n@ap... | [
2
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0074424836_fastapi_python.txt |
Q:
'module' object is not callable. Error while AI file execution
I am trying to make an AI using openai and I have ran into a problem. My python version in 3.8.3
Here is my code:
fileopen = open("Data\\Api.txt","r")
API = fileopen.read()
fileopen.close()
import openai
from dotenv import load_dotenv
openai.api_key ... | 'module' object is not callable. Error while AI file execution | I am trying to make an AI using openai and I have ran into a problem. My python version in 3.8.3
Here is my code:
fileopen = open("Data\\Api.txt","r")
API = fileopen.read()
fileopen.close()
import openai
from dotenv import load_dotenv
openai.api_key = API
load_dotenv()
completion = openai.Completion()
def ReplyBrain... | [
"You wrote this\nimport openai\n...\n FileLog = openai(\"\",\"r\")\n\nand complained of a \"not callable\" diagnostic.\nWell, the module is not callable.\nIt is unclear what you were hoping\nthat pair of args might accomplish.\nIf you refer to their documentation\nand to the OpenAI Cookbook,\nyou will find numer... | [
0
] | [] | [] | [
"openai",
"python"
] | stackoverflow_0074423236_openai_python.txt |
Q:
How to create calculated column off variable result of same row? Pandas & Python 3
Fairly new to python, I have been struggling with creating a calculated column based off of the variable values of each item.
I Have this table below with DF being the dataframe name
I am trying to create a 'PE Comp' Column that ge... | How to create calculated column off variable result of same row? Pandas & Python 3 | Fairly new to python, I have been struggling with creating a calculated column based off of the variable values of each item.
I Have this table below with DF being the dataframe name
I am trying to create a 'PE Comp' Column that gets the PE value for each ticker, and divides it by the **Industry ** average PE Ratio.
M... | [
"You can use the Pandas Groupby transform:\nThe following takes the PE Ratio column and divides it by the mean of the grouped industries (expressed three different ways in order of speed of calculation):\nimport pandas as pd\n\ndf = pd.DataFrame({\"PE Ratio\": [1,2,3,4,5,6,7],\n \"Industry\": list... | [
1,
0
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074424842_dataframe_group_by_pandas_python_python_3.x.txt |
Q:
randomly replacing a specific value in a dataset with frac in pandas
I've got a dataset with some missing values as " ?" in just one column
I want to replace all missing values with other values in that column (Feature1) like this:
Feature1_value_counts = df.Feature1.value_counts(normalize=True)
the code above gi... | randomly replacing a specific value in a dataset with frac in pandas | I've got a dataset with some missing values as " ?" in just one column
I want to replace all missing values with other values in that column (Feature1) like this:
Feature1_value_counts = df.Feature1.value_counts(normalize=True)
the code above gives me the number I can use for frac in pandas
Feature1 contains 15 set of... | [
"You can take advantage of the p parameter of numpy.random.choice:\nimport numpy as np\n\n# ensure using real NaNs for missing values\ndf['Feature1'] = df['Feature1'].replace('?', np.nan)\n\n# count the fraction of the non-NaN value\ncounts = df['Feature1'].value_counts(normalize=True)\n# identify the rows with NaN... | [
0
] | [] | [] | [
"dataframe",
"dataset",
"pandas",
"python",
"str_replace"
] | stackoverflow_0074424967_dataframe_dataset_pandas_python_str_replace.txt |
Q:
Django forms template dropdown with unique identifier for each iteration of a forloop
I am trying to generate a unique ID for each iteration of a for loop item.
The item generated is a drop down menu and the number of times it s generated will depend on the number of incidents that are active.
The the problem I am... | Django forms template dropdown with unique identifier for each iteration of a forloop | I am trying to generate a unique ID for each iteration of a for loop item.
The item generated is a drop down menu and the number of times it s generated will depend on the number of incidents that are active.
The the problem I am having is that the ID of the dropdown is the same for each dropdown menu. In this case id=... | [
"I'll put this as an answer for now, since it's too long for a comment, and then I'll delete / adjust it.\nIf I understand what you're after correctly, then you don't want a formset for IncidentStatus, indeed perhaps you don't need a an IncidentStatus model at all. You seem to have about 10-15 different choices fo... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"javascript",
"python"
] | stackoverflow_0074423518_django_django_forms_django_templates_javascript_python.txt |
Q:
I'm not able to move to next page using scrapy
I'm trying to do web scraping on reclameaqui site (www.reclameaqui.com.br). The code is already done, but I'm not able to iretate over lista-reclamacoes/?pagina=1, lista-reclamacoes/?pagina=2, lista-reclamacoes/?pagina=3 and get its contents:
'''
This spider file cont... | I'm not able to move to next page using scrapy | I'm trying to do web scraping on reclameaqui site (www.reclameaqui.com.br). The code is already done, but I'm not able to iretate over lista-reclamacoes/?pagina=1, lista-reclamacoes/?pagina=2, lista-reclamacoes/?pagina=3 and get its contents:
'''
This spider file contains the spider logic and scraping code.
In order t... | [
"You can try the next example\nimport scrapy\nfrom ..items import ComplaintItem\nimport json\n\n\nclass ComplaintScraper(scrapy.Spider):\n name = \"complaintScraper\" \n\n start_urls = [f\"https://iosearch.reclameaqui.com.br/raichu-io-site-search-v1/query/companyComplains/10/{item}?company=98\" for item in r... | [
0
] | [] | [] | [
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0074424367_python_scrapy_web_scraping.txt |
Q:
Change time series frequency, ffill values until the next input but with a limit
I have data with timestamps, I want to make it into 1min time series and fill the missing values in rows that are created with the last input. However, also have a limit on the ffill function as well. So, if the next input is missing ... | Change time series frequency, ffill values until the next input but with a limit | I have data with timestamps, I want to make it into 1min time series and fill the missing values in rows that are created with the last input. However, also have a limit on the ffill function as well. So, if the next input is missing for too long, leave NaN.
Data:
timestamp pay
2020-10-10 23:32 50
2020-10-... | [
"i think you can use resample and ffill with limit option. Can you try this:\nmask = df.set_index('timestamp').sort_index().resample('1Min').ffill(limit=1440)\n\n",
"Based on Clegane's very good answer I would like to add there is no need for sort_index() and the limit should be 1339 (1 value + 1339 makes the ful... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"time_series"
] | stackoverflow_0074424457_dataframe_pandas_python_time_series.txt |
Q:
Is there a way to get my for loop to work in all cases of this slice?
so what my code is essentially trying to do is return a total of all the numbers in a list, but not add numbers in the list that are between 6 and 9. Anyways, it took me a while but I found a solution that kinda works. But the issue is that if I... | Is there a way to get my for loop to work in all cases of this slice? | so what my code is essentially trying to do is return a total of all the numbers in a list, but not add numbers in the list that are between 6 and 9. Anyways, it took me a while but I found a solution that kinda works. But the issue is that if I introduce a second 6 or a 9, it throws me the wrong answer.
`
def summer_6... | [
"def summer_69(arr):\n r = 0\n c = False\n for n in arr:\n if not c:\n if n == 6:\n c = True\n continue\n r+=n\n else:\n if n == 9:\n c = False\n return r\n\nprint(summer_69([4, 5, 6, 7, 8, 9]))\n\n\nprint(summer... | [
0
] | [] | [] | [
"enumeration",
"for_loop",
"list",
"python",
"python_3.x"
] | stackoverflow_0074425031_enumeration_for_loop_list_python_python_3.x.txt |
Q:
How to substitute value in numpy 2d array?
I have a very easy question but somehow I'm having trouble with it...
I'm creating an 81x41 string 2d-array with numpy. I then iterate through all positions of this array and want to put a certain string inside each position.
For some reason, it doesn't assign the variabl... | How to substitute value in numpy 2d array? | I have a very easy question but somehow I'm having trouble with it...
I'm creating an 81x41 string 2d-array with numpy. I then iterate through all positions of this array and want to put a certain string inside each position.
For some reason, it doesn't assign the variable to the position. It remains empty.
How can I d... | [
"You should use dtype=object. When creating an array with dtype=str the array can only contain strings with equal or lower length than the maximum element. Since your array is empty, that length is 0.\n",
"You can use dtype='object' which will assign a pointer and will allow you to put whatever in the cell. If yo... | [
0,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074424158_arrays_numpy_python.txt |
Q:
How to merge two time series dataframes with different end dates and keep the longer end date
I have two time series with same sampling frequency but different end dates. I want to combine them into one and keep the total time range instead of the intersection. Leave the data outside the intersection NaN.
I've tri... | How to merge two time series dataframes with different end dates and keep the longer end date | I have two time series with same sampling frequency but different end dates. I want to combine them into one and keep the total time range instead of the intersection. Leave the data outside the intersection NaN.
I've tried:
df_to_merge= [df1, df2]
df_merged = reduce(lambda left,right: pd.merge(left,right, on='timestam... | [
"You can perform a join operation:\ndf_merged = df1.join(df2,how='right')\n\nBy using right you ensure all values from the right (longer df) will be kept.\nFor example:\ndf1 = pd.DataFrame({'timestamp':pd.to_datetime(pd.Series(['2020-10-10 23:32',\n '2020-10-1... | [
4
] | [] | [] | [
"dataframe",
"pandas",
"python",
"time_series"
] | stackoverflow_0074425097_dataframe_pandas_python_time_series.txt |
Q:
I wrote a calculator together with a error handling but I do not understand why it doesnt work?
def arithmetic_sequence():
a = float(input('Type the first term'))
d = float(input('Type the difference'))
n = float(input("Type the number of values"))
if a == ValueError:
print("Write a value")... | I wrote a calculator together with a error handling but I do not understand why it doesnt work? | def arithmetic_sequence():
a = float(input('Type the first term'))
d = float(input('Type the difference'))
n = float(input("Type the number of values"))
if a == ValueError:
print("Write a value")
elif d == ValueError:
print("Write a value")
elif n == ValueError:
print("Wr... | [
"When Python can't convert the user's string into a float it will raise a ValueError not return one. You need to catch the error like so:\ntry:\n a = float(input(\"Type the first term\"))\nexcept ValueError:\n print(\"Write a value\")\n\n",
"def arithmetic_sequence():\n try:\n a = float(input('Typ... | [
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074425090_python_python_3.x.txt |
Q:
Removing non numeric characters from a string
I have been given the task to remove all non numeric characters including spaces from a either text file or string and then print the new result next to the old characters for example:
Before:
sd67637 8
After:
676378
As i am a beginner i do not know where to start wi... | Removing non numeric characters from a string | I have been given the task to remove all non numeric characters including spaces from a either text file or string and then print the new result next to the old characters for example:
Before:
sd67637 8
After:
676378
As i am a beginner i do not know where to start with this task. Please Help
| [
"The easiest way is with a regexp\nimport re\na = 'lkdfhisoe78347834 (())&/&745 '\nresult = re.sub('[^0-9]','', a)\n\nprint result\n>>> '78347834745'\n\n",
"Loop over your string, char by char and only include digits:\nnew_string = ''.join(ch for ch in your_string if ch.isdigit())\n\nOr use a regex on your strin... | [
107,
29,
11,
3,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_3.3",
"python_3.x"
] | stackoverflow_0017336943_python_python_3.3_python_3.x.txt |
Q:
unable to display data to html table from python file
I am trying to display the data that I am getting from the database, I am having trouble to display them into html table.
store.py
def book_list():
# Define the query for the DB
query = "SELECT * FROM " + DBtable`
## Execute the query
... | unable to display data to html table from python file | I am trying to display the data that I am getting from the database, I am having trouble to display them into html table.
store.py
def book_list():
# Define the query for the DB
query = "SELECT * FROM " + DBtable`
## Execute the query
mycursor.execute(query)
results = mycursor.fetch... | [
"Your problem seems to be with how you are trying to access your data within row. You need to index your value out of the row variable. If Author is in the second spot, then row[1] will give you the author value. But this can only happen if you do proper string formatting, like f\"Author:{row[1]}\"\n\nf\"<div id=\\... | [
0
] | [] | [] | [
"for_loop",
"html",
"python"
] | stackoverflow_0074425052_for_loop_html_python.txt |
Q:
How to build a cycle plot in Python Altair?
I'd like to plot the following graph in Altair. Any ideas?
I have this dataset:
I've tried
alt.Chart(df).mark_line().encode(
x='Month',
y='Mean'
)
but the output is completely wrong.
A:
Since I don't have the exact dataframe or how you wrangled it, I am assu... | How to build a cycle plot in Python Altair? | I'd like to plot the following graph in Altair. Any ideas?
I have this dataset:
I've tried
alt.Chart(df).mark_line().encode(
x='Month',
y='Mean'
)
but the output is completely wrong.
| [
"Since I don't have the exact dataframe or how you wrangled it, I am assuming the column \"Mean\" refers to the mean of strike reports in the dataset.\nYou can create this sort of plot by layering the three graphs:\n\nmark_line with a point (total strike reports) for each year\nmark_area\nmark_line for the mean (me... | [
1
] | [] | [] | [
"altair",
"python",
"time_series",
"timeserieschart",
"visualization"
] | stackoverflow_0074333072_altair_python_time_series_timeserieschart_visualization.txt |
Q:
How to iterate through multiple outlook accounts using win32com.client
I have a requirement where in i need to handle 3 outlook accounts set in one profile. The scenario is similar for all 3 accounts, i just need to run through the scenario in 3 accounts one by one. Use case is as follows
Account_One has a folder ... | How to iterate through multiple outlook accounts using win32com.client | I have a requirement where in i need to handle 3 outlook accounts set in one profile. The scenario is similar for all 3 accounts, i just need to run through the scenario in 3 accounts one by one. Use case is as follows
Account_One has a folder in it : Folder_One. I will receive a mail in this folder with unique id in s... | [
"Replace the line\nroot = namespace.Folders[account]\n\nwith\nroot = namespace.Folders.Item(account)\n\n"
] | [
0
] | [] | [] | [
"office_automation",
"outlook",
"python",
"pywin32",
"win32com"
] | stackoverflow_0074406363_office_automation_outlook_python_pywin32_win32com.txt |
Q:
Inheritance set-up
I'm working on creating a deck of cards as a class, and I think I have messed up the inheritance.
import random as rand
class Card:
def __init__(self, suit, value, color, whole):
self.suit = suit
self.value = value
self.color = color
self.whole = whole
d... | Inheritance set-up | I'm working on creating a deck of cards as a class, and I think I have messed up the inheritance.
import random as rand
class Card:
def __init__(self, suit, value, color, whole):
self.suit = suit
self.value = value
self.color = color
self.whole = whole
def __repr__(self):
... | [
"Neither of these should be subclasses of Card. A deck is a collection of cards:\nfrom itertools import product\nimport random\n\n\nclass Card:\n def __init__(self, suit, value):\n self.suit = suit\n self.value = value\n if suit in [\"Diamonds\", \"Hearts\"]:\n self.color = \"Red\... | [
0
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0074425044_inheritance_python.txt |
Q:
How to send numpy array over network in Android using chaquo to a Python server using sockets
I'm making a face recognition app that uses local camera to capture the face and encodes it into a 128-d numpy array via chaquopy. What I want to make is to send that numpy array over network to a server. The problem is I... | How to send numpy array over network in Android using chaquo to a Python server using sockets | I'm making a face recognition app that uses local camera to capture the face and encodes it into a 128-d numpy array via chaquopy. What I want to make is to send that numpy array over network to a server. The problem is I dont know how to send a numpy array via network or a chaquopy-PyObject efficiently. Please give me... | [
"You could convert the array directly to bytes using tobytes, or at a slightly higher level using save. See this question for further discussion.\n"
] | [
0
] | [] | [] | [
"android",
"chaquopy",
"java",
"python",
"sockets"
] | stackoverflow_0074412780_android_chaquopy_java_python_sockets.txt |
Q:
str.get() not grabbing correct element after str.split
I have a dataFrame containing a column of names and I want to extract the last name and make that a new column. However, I am running into a problem.
Here is a toy example of my dataframe:
Candidate_Name Party State District O... | str.get() not grabbing correct element after str.split | I have a dataFrame containing a column of names and I want to extract the last name and make that a new column. However, I am running into a problem.
Here is a toy example of my dataframe:
Candidate_Name Party State District Office Year Img_U... | [
"You are using:\nif df[\"Candidate_Name\"].eq('Jr.').all()\n\nWhich translates to if df['Candidate_Name'] == 'Jr.' which is not the case. Also, using .all() is causing another unintended behaviour. You should vectorize it and use either in or contains(). Consider using this:\ndf[\"Last_Name\"] = np.where(df['Candid... | [
1,
1
] | [] | [] | [
"pandas",
"python",
"string"
] | stackoverflow_0074424989_pandas_python_string.txt |
Q:
Insert data from pandas to oracle sql developer table
I receive some data in excel files and I would like to process it in pandas in order to have the proper format and then insert it into a table in sql developer.
I found several tutorials in the internet and I tried the following code but I can't understand why ... | Insert data from pandas to oracle sql developer table | I receive some data in excel files and I would like to process it in pandas in order to have the proper format and then insert it into a table in sql developer.
I found several tutorials in the internet and I tried the following code but I can't understand why is not working.
import cx_Oracle
import datetime as dt
impo... | [
"You already have a dataframe.\nUse df.to_sql().\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html\n\nDuring debugging, consider creating a new\ntable with that call, one which you're prepared\nto DROP between runs.\nConsider paring your large df\ndown to one that has just a c... | [
0,
0
] | [] | [] | [
"oracle_sqldeveloper",
"pandas",
"python"
] | stackoverflow_0074423153_oracle_sqldeveloper_pandas_python.txt |
Q:
How to create a stacked area chart using hvplot or holoviews in python?
I am trying to replicate the graph below using hvplot or holoviews.
This is the data that I am working with.
The data contains a 'Cluster' column that consist of 11 clusters, each cluster has 24 hours to it. Each hour has an associated power... | How to create a stacked area chart using hvplot or holoviews in python? | I am trying to replicate the graph below using hvplot or holoviews.
This is the data that I am working with.
The data contains a 'Cluster' column that consist of 11 clusters, each cluster has 24 hours to it. Each hour has an associated power output, corresponding to a specific technology. Using this data I would like... | [
"I was able to generate something closer to what I desired, however, it was not using hvplot or holoviews. The plot was generated using the pandas.plot() methods, although I felt I should share my solution.\nIt was how the data was structured within the pandas data frame, I needed to pivot the data frame on the Clu... | [
1
] | [] | [] | [
"holoviews",
"hvplot",
"python",
"stacked_area_chart",
"visualization"
] | stackoverflow_0074295562_holoviews_hvplot_python_stacked_area_chart_visualization.txt |
Q:
Python `requirements.txt` and `setup.py` pick several ranges for the same package
I am developing 2 packages, package A that depends on package B. I am currently restricting the versioning of package B<2.0,>1.7 in the requirements.txt and setup.py of package A which works just fine.
The thing is that I have a way ... | Python `requirements.txt` and `setup.py` pick several ranges for the same package | I am developing 2 packages, package A that depends on package B. I am currently restricting the versioning of package B<2.0,>1.7 in the requirements.txt and setup.py of package A which works just fine.
The thing is that I have a way to publish internal beta versions with the version numbering 0.0bx where x is a random ... | [
"You say that you are publishing B with\n\nversion numbering 0.0bx where x is a random number\n\nyet you also explain that that version numbering\nscheme is causing you interoperability grief.\nConsider adopting SemVer instead.\nYou don't have to externally publish\neach of the minor / patch revs that\nyou make ava... | [
1
] | [] | [] | [
"pip",
"python",
"requirements.txt",
"setup.py",
"setuptools"
] | stackoverflow_0074421870_pip_python_requirements.txt_setup.py_setuptools.txt |
Q:
Multiprocessing code to calculate pi never finishes
I want to calculate pi. The procedure is simple:
Make a 1x1 square and draw a circle in the square. Then divide by 4.
Take two random values (x, y).
If x2 + y2 ≤ 1 than the point is in the circle.
Repeat the above N times.
Count the inner points (I'll call it K)... | Multiprocessing code to calculate pi never finishes | I want to calculate pi. The procedure is simple:
Make a 1x1 square and draw a circle in the square. Then divide by 4.
Take two random values (x, y).
If x2 + y2 ≤ 1 than the point is in the circle.
Repeat the above N times.
Count the inner points (I'll call it K) and divide by all number of executions and multiply by f... | [
"import time\nimport random\nfrom multiprocessing import Pool\nstart = time.perf_counter()\n\nN = 100000000\nprocess_num = 96\n\ndef calc_pi(end):\n count_inbound = 0\n for x in range(end):\n the_x = random.random()\n the_y = random.random()\n if((the_x**2 + the_y**2) <= 1):\n ... | [
0,
-1
] | [
"I have test the same code on my mac.\nIt works just fine.\n0.25 for multi process and 0.45 for single process.\nJust change \n[N/process_num for x in range(process_num)]\nto\n[int(N/process_num for x in range(process_num)]\n"
] | [
-1
] | [
"multiprocessing",
"pi",
"python"
] | stackoverflow_0050389746_multiprocessing_pi_python.txt |
Q:
Find minimum number of columns in matrix necessary to ensure all rows are unique
Say I have an m x n matrix consisting purely of dummy variables i.e. all values in the matrix are either 0 or 1.
[0 1 ... 1 1
1 1 ... 1 0
0 1 ... 0 0
| | \ | |
0 0 ... 1 1
1 1 ... 0 0
0 0 ... 0 0]
What is the most efficient m... | Find minimum number of columns in matrix necessary to ensure all rows are unique | Say I have an m x n matrix consisting purely of dummy variables i.e. all values in the matrix are either 0 or 1.
[0 1 ... 1 1
1 1 ... 1 0
0 1 ... 0 0
| | \ | |
0 0 ... 1 1
1 1 ... 0 0
0 0 ... 0 0]
What is the most efficient method of finding the fewest possible columns of the matrix necessary to ensure all row... | [
"This can be formulated as a set cover problem, see here: https://stackoverflow.com/a/36452133/4039466. Your sets are the columns, and the space you're covering is the set of pairs of rows. This is probably doable for 1000 linear variables and 250,000 constraints.\n"
] | [
1
] | [] | [] | [
"algorithm",
"matrix",
"python"
] | stackoverflow_0067307468_algorithm_matrix_python.txt |
Q:
Subsetting a data frame based on argument n+
I have a dataframe of various products and their respective cost. I have a function that subsets the dataframe rows using the argument 'n'. For example, if n=6, 6 rows will be returned. This, however, means that the 7th row (which may have the same price as the 6th) is ... | Subsetting a data frame based on argument n+ | I have a dataframe of various products and their respective cost. I have a function that subsets the dataframe rows using the argument 'n'. For example, if n=6, 6 rows will be returned. This, however, means that the 7th row (which may have the same price as the 6th) is not given in the output.
I want to be able to subs... | [
"I think you're looking for nlargest\nExample\nimport numpy as np\nimport pandas as pd\n\nnp.random.seed(0)\n\n# random integer costs between 0 and 5 (non-inclusive)\ncost = np.random.randint(0, 5, size=(10))\n\n# 10 unique items with associated costs\ndf = pd.DataFrame({\"item\": list(\"abcdefghij\"), \"cost\": co... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074425213_pandas_python.txt |
Q:
AWS assume-role-with-web-identity from GCP account using Boto3 and Google Python libraries
Using the following aws sts assume-role-with-web-identity AWS CLI command within my GCP account I can return a set of temporary security credentials.
aws sts assume-role-with-web-identity \
--role-arn arn:aws:iam::123456... | AWS assume-role-with-web-identity from GCP account using Boto3 and Google Python libraries | Using the following aws sts assume-role-with-web-identity AWS CLI command within my GCP account I can return a set of temporary security credentials.
aws sts assume-role-with-web-identity \
--role-arn arn:aws:iam::12345678:role/from-gcp \
--role-session-name my-session \
--web-identity-token $(gcloud auth p... | [
"I recommend the boto_session_manager library. It is a thin wrapper around boto3 but makes the work more user friendly.\n# suppose this is how you usually use boto3 to do work\n\ns3_client = boto3.client(\"s3\")\ns3_client.put_object(...)\n\n# with boto_session_manager, you can do\nfrom boto_session_manager import ... | [
0
] | [] | [] | [
"amazon_web_services",
"google_cloud_platform",
"python"
] | stackoverflow_0074403160_amazon_web_services_google_cloud_platform_python.txt |
Q:
How to compare the lenghts of lists in lists efficiently?
I have 2 lists a and b which contain sublists that have different lenghts, and i want to find a sublist in a and a sublist in b that have the same length.
My approach was:
for j in range(0, len(a)-1):
for k in range(0, len(b)-1):
if len(a[j]) ==... | How to compare the lenghts of lists in lists efficiently? | I have 2 lists a and b which contain sublists that have different lenghts, and i want to find a sublist in a and a sublist in b that have the same length.
My approach was:
for j in range(0, len(a)-1):
for k in range(0, len(b)-1):
if len(a[j]) == len(b[k]):
Problem being that a and b can both contain around... | [
"If the indices are the same size, I would sort each of the lists by the length of each sublist and go from there.\na.sort(key=len)\nb.sort(key=len)\n\nfor item in zip(a,b):\n sublist_a,sublist_b = item\n if len(sublist_a) == len(sublist_b):\n return sublist_a #or whatever you need\n\n\nIf the sizes of... | [
2,
2
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074425204_loops_python.txt |
Q:
ParserError: Source file requires different compiler version
I tried all that you mentioned in the discussion here (in other questions) and at https://github.com/smartcontractkit/full-blockchain-solidity-course-py/discussions/522 , however it is not solving the issue for me, I also noticed that the current compile... | ParserError: Source file requires different compiler version | I tried all that you mentioned in the discussion here (in other questions) and at https://github.com/smartcontractkit/full-blockchain-solidity-course-py/discussions/522 , however it is not solving the issue for me, I also noticed that the current compiler version remains (current compiler is 0.6.12+commit.27d51765.Wind... | [
"The solution to the error is\n// SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 <0.9.0;\n\nUse this instead, hope this helps\n",
"i had the same issue. i had this compiler setting:\npragma solidity >=0.4.22 <0.9.0;\n\nSince we are importing from openzeppelin, I visied github repo and saw that it uses prag... | [
6,
1,
1,
0
] | [] | [] | [
"brownie",
"ethereum",
"python",
"smartcontracts",
"solidity"
] | stackoverflow_0070459922_brownie_ethereum_python_smartcontracts_solidity.txt |
Q:
Python chess FileExporter and open() function don't export a game
I've been working on project in python chess playing with lichess opening explorer API. I have succeeded in doing all the hard work and finally got the PGN tree that I wanted but when I try to export my PGN tree to a text file all I am left with is ... | Python chess FileExporter and open() function don't export a game | I've been working on project in python chess playing with lichess opening explorer API. I have succeeded in doing all the hard work and finally got the PGN tree that I wanted but when I try to export my PGN tree to a text file all I am left with is empty file.
I was trying to export my PGN file using a method proposed ... | [
"Embarrassing, this block of code is performed in a loop. I should have waited until the script end. Everything works fine.\n"
] | [
0
] | [] | [] | [
"python",
"python_chess"
] | stackoverflow_0074425270_python_python_chess.txt |
Q:
Creating a function to convert Fahrenheit to Celsius
I'm new to python and have started learning about functions. I am having trouble with homework to create my function to convert Fahrenheit to Celsius. Please see my code below.
def convert_f_to_c(temp_in_fahrenheit):
celsius = float(temp_in_fahrenheit - 32.... | Creating a function to convert Fahrenheit to Celsius | I'm new to python and have started learning about functions. I am having trouble with homework to create my function to convert Fahrenheit to Celsius. Please see my code below.
def convert_f_to_c(temp_in_fahrenheit):
celsius = float(temp_in_fahrenheit - 32.00) * float(5.00 / 9.00)
return round(celsius)
co... | [
"It seems like temp_in_fahrenheit is a string when it should be a float. Just change how the float function is called.\n\n#wrong\nfloat(temp_in_fahrenheit - 32)\n\n#better\nfloat(temp_in_fahrenheit) - 32\n\n\n",
"Make sure to pass a float to your function, not a string, then you won't need to construct floats (in... | [
5,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074425351_function_python.txt |
Q:
How to upgrade all Python packages with pip?
Is it possible to upgrade all Python packages at one time with pip?
Note: that there is a feature request for this on the official issue tracker.
A:
There isn't a built-in flag yet. Starting with pip version 22.3, the --outdated and --format=freeze have become mutuall... | How to upgrade all Python packages with pip? | Is it possible to upgrade all Python packages at one time with pip?
Note: that there is a feature request for this on the official issue tracker.
| [
"There isn't a built-in flag yet. Starting with pip version 22.3, the --outdated and --format=freeze have become mutually exclusive. Use Python, to parse the json output:\npip --disable-pip-version-check list --outdated --format=json | python -c \"import json, sys; print('\\n'.join([x['name'] for x in json.load(sys... | [
2754,
810,
787,
442,
272,
155,
95,
78,
76,
70,
48,
45,
30,
29,
27,
27,
26,
23,
21,
20,
16,
14,
13,
13,
11,
10,
10,
10,
9,
9,
9,
8,
7,
6,
6,
5,
5,
5,
5,
5,
4,
4,
3,
2,
2,
2,
2,
1,
1,
1,
0,
0,
0
] | [
"pip list --outdated --format=freeze | grep -v '^\\-e' | cut -d = -f 1 | xargs -n1 pip install -U\n\n"
] | [
-1
] | [
"pip",
"python"
] | stackoverflow_0002720014_pip_python.txt |
Q:
Calculate circular shift pairs in a list
A circular shift moves some of the digits in a number to the beginning of the number, and shifts all other digits forward to the next position. For example, all of the circular shifts of 564 are 564, 645, 456.
Lets say two numbers of equal length a and b are circular pairs ... | Calculate circular shift pairs in a list | A circular shift moves some of the digits in a number to the beginning of the number, and shifts all other digits forward to the next position. For example, all of the circular shifts of 564 are 564, 645, 456.
Lets say two numbers of equal length a and b are circular pairs if a can become b via circular shifting. Using... | [
"\nReplace every number in the array with its greatest cyclic shift. 1234, for example, would become 4123\nCount the occurrences of each resulting number\nIf a number occurs n times, that represents n(n-1)/2 cyclic shift pairs. Add them all up.\n\n",
"Not very elegant as not much time but the following should b... | [
1,
1,
0
] | [] | [] | [
"algorithm",
"bit_shift",
"data_structures",
"optimization",
"python"
] | stackoverflow_0073990339_algorithm_bit_shift_data_structures_optimization_python.txt |
Q:
How do i set text background transparent in Python?
I have tryed in many ways but i dont find solution for the problem
i want to put the text background transparent
#Text where the background is black
Download=Label(root,text="00",font="calibri 40 bold",bg="#000000",fg="white")
Download.place(x=320,y=261,anchor="c... | How do i set text background transparent in Python? | I have tryed in many ways but i dont find solution for the problem
i want to put the text background transparent
#Text where the background is black
Download=Label(root,text="00",font="calibri 40 bold",bg="#000000",fg="white")
Download.place(x=320,y=261,anchor="center")
i want to turn black background to transparent b... | [
"tkinter Label does not support transparent. But you can use Canvas as the background and its drawing function .create_text(...) to draw some text on it with transparency.\nBelow is a simple example:\nimport tkinter as tk\n\nroot = tk.Tk()\n\ncanvas = tk.Canvas(root, width=400, height=300, highlightthickness=0)\nca... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074421530_python_tkinter.txt |
Q:
CSV to AVRO using python
I have the following csv :
field1;field2;field3;field4;field5;field6;field7;field8;field9;field10;field11;field12;
eu;4523;35353;01/09/1999; 741 ; 386 ; 412 ; 86 ; 1.624 ; 1.038 ; 469 ; 117 ;
and I want to convert it to avro. I have created the following avro schema:
{"namespace": "foreca... | CSV to AVRO using python | I have the following csv :
field1;field2;field3;field4;field5;field6;field7;field8;field9;field10;field11;field12;
eu;4523;35353;01/09/1999; 741 ; 386 ; 412 ; 86 ; 1.624 ; 1.038 ; 469 ; 117 ;
and I want to convert it to avro. I have created the following avro schema:
{"namespace": "forecast.avro",
"type": "record",
... | [
"When I run your code as written I get an error TypeError: Expected 12 arguments, got 13 at for row in map(forecastRecord._make, reader): because your CSV ends in a ; and therefore has 13 fields.\nOnce I remove those trailing ;s, I can run the example and get the same error about the schema mismatch. The reason is ... | [
7,
0
] | [] | [] | [
"avro",
"csv",
"python"
] | stackoverflow_0052892387_avro_csv_python.txt |
Q:
Dict merge in a dict comprehension
In python 3.5, we can merge dicts by using double-splat unpacking
>>> d1 = {1: 'one', 2: 'two'}
>>> d2 = {3: 'three'}
>>> {**d1, **d2}
{1: 'one', 2: 'two', 3: 'three'}
Cool. It doesn't seem to generalise to dynamic use cases, though:
>>> ds = [d1, d2]
>>> {**d for d in ds}
Synt... | Dict merge in a dict comprehension | In python 3.5, we can merge dicts by using double-splat unpacking
>>> d1 = {1: 'one', 2: 'two'}
>>> d2 = {3: 'three'}
>>> {**d1, **d2}
{1: 'one', 2: 'two', 3: 'three'}
Cool. It doesn't seem to generalise to dynamic use cases, though:
>>> ds = [d1, d2]
>>> {**d for d in ds}
SyntaxError: dict unpacking cannot be used i... | [
"It's not exactly an answer to your question but I'd consider using ChainMap to be an idiomatic and elegant way to do what you propose (merging dictionaries in-line):\n>>> from collections import ChainMap\n>>> d1 = {1: 'one', 2: 'two'}\n>>> d2 = {3: 'three'}\n>>> ds = [d1, d2]\n>>> dict(ChainMap(*ds))\n{1: 'one', 2... | [
34,
18,
2,
1,
0,
0
] | [] | [] | [
"dict_comprehension",
"dictionary",
"python",
"python_3.5",
"syntax_error"
] | stackoverflow_0037584544_dict_comprehension_dictionary_python_python_3.5_syntax_error.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.