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 add a row in a special form
I have a pandas.DataFrame of the form
index df df1
0 0 111
1 1 111
2 2 111
3 3 111
4 0 111
5 2 111
6 3 111
7 0 111
8 2 111
9 3 111... | How to add a row in a special form | I have a pandas.DataFrame of the form
index df df1
0 0 111
1 1 111
2 2 111
3 3 111
4 0 111
5 2 111
6 3 111
7 0 111
8 2 111
9 3 111
10 0 111
11 1 ... | [
"You can set a custom grouping to detect when the increasing numbers in \"df\" reset to a lower (or equal) value.\nThen reindex using the product of the unique values in \"df\" and the unique groups.\nFinally, rework the output with a combination of fillna/reset_index/rename_axis:\n# uncomment below if \"index\" is... | [
5,
5,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0069188655_pandas_python.txt |
Q:
Pandas: rolling total of checked out vs checked in items
I have a large data set that I need to calculate the number of checked out items vs the number of checked in items.
Sample data where rollingTotalCheckedOut describes the expected value. While items are checked out, the number of checked out items increases.... | Pandas: rolling total of checked out vs checked in items | I have a large data set that I need to calculate the number of checked out items vs the number of checked in items.
Sample data where rollingTotalCheckedOut describes the expected value. While items are checked out, the number of checked out items increases. When items are checked back in, the number of checked out ite... | [
"Here is what I got. not exactly your calculation but I can't immediately see an error. Will check again. But honestly I am not sure why you have a 5 in the end. Previous period ended but new just started.\nimport pandas as pd\ndf = pd.DataFrame([\n ['A', 1624990605, 1627102404, 1],\n ['A', 16... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074383603_pandas_python.txt |
Q:
Pydantic add descriptions to dynamic model
I was wondering if there is a way to assign description when creating a model dynamically. The static equivalent would be
from pydantic import BaseModel, Field, create_model
class MainModel(BaseModel):
value1: int = Field(-1, description="desc1")
value2: int = Fi... | Pydantic add descriptions to dynamic model | I was wondering if there is a way to assign description when creating a model dynamically. The static equivalent would be
from pydantic import BaseModel, Field, create_model
class MainModel(BaseModel):
value1: int = Field(-1, description="desc1")
value2: int = Field(-2, description="desc2")
print(MainModel.sc... | [
"Not sure if this is what you want, but if does give a similar JSON to what your static equivalent does. Look into FieldInfo.\nfrom pydantic import create_model\nfrom pydantic.fields import FieldInfo\n\n\nattrs = {\n \"value1\": (int, FieldInfo(-1, description=\"desc1\")),\n \"value2\": (int, FieldInfo(-2, de... | [
1
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0074383570_pydantic_python.txt |
Q:
Custom dependency graph
Is there a way to use Spacy to create custom dependency graph i.e. to manually specify which words are connected.
If not is there other tool to create similar looking dep-diagrams ? with arcs..
if as a bonus can also draw in text mode ..that would be cool.
A:
You can modify the .head or .... | Custom dependency graph | Is there a way to use Spacy to create custom dependency graph i.e. to manually specify which words are connected.
If not is there other tool to create similar looking dep-diagrams ? with arcs..
if as a bonus can also draw in text mode ..that would be cool.
| [
"You can modify the .head or .dep_ attribute on tokens to change the dependency graph, or you can just pass any data to displaCy, as described in the docs. Example:\nex = {\n \"words\": [\n {\"text\": \"This\", \"tag\": \"DT\"},\n {\"text\": \"is\", \"tag\": \"VBZ\"},\n {\"text\": \"a\", \"t... | [
2
] | [] | [] | [
"dependencies",
"graph",
"python",
"spacy"
] | stackoverflow_0074379537_dependencies_graph_python_spacy.txt |
Q:
Unable to send keys in python selenium
I am on a shopify site (https://lab401.com/) trying to build a checkout bot, the problem I am having is when I reach the stage to enter my card details, it is giving me this error:
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
... | Unable to send keys in python selenium | I am on a shopify site (https://lab401.com/) trying to build a checkout bot, the problem I am having is when I reach the stage to enter my card details, it is giving me this error:
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
My code is:
driver.switch_to.frame(d... | [
"Each of those fields are in another iframe. Simply switch to the others.\n(//iframe[@class='card-fields-iframe'])[1]\n(//iframe[@class='card-fields-iframe'])[2]\n\n"
] | [
0
] | [] | [] | [
"bots",
"python",
"selenium"
] | stackoverflow_0074382169_bots_python_selenium.txt |
Q:
AssertionError: The environment must specify an action space
i am use the openAI gym library.I have download a new environemnt,but I get this error.
AssertionError: The environment must specify an action space. https://www.gymlibrary.dev/content/environment_creation/
it says that i didn't specify an action space.... | AssertionError: The environment must specify an action space | i am use the openAI gym library.I have download a new environemnt,but I get this error.
AssertionError: The environment must specify an action space. https://www.gymlibrary.dev/content/environment_creation/
it says that i didn't specify an action space.
But i did.
class MoleculeEnv(gym.Env):
metadata = {'render.mo... | [
"I lower my gym version to 0.18.0.That fixed my error.\n"
] | [
0
] | [] | [] | [
"openai_gym",
"python",
"pytorch",
"reinforcement_learning"
] | stackoverflow_0074383694_openai_gym_python_pytorch_reinforcement_learning.txt |
Q:
Lab #3 combining python codes after importing files where do I start?
Need help figuring out where to start after I import my two previous question files. Everything I've tried doesn't seem to want to take. So I scrapped it and trying to figure out where to begin again
1. In a file called FirstName_LastName_Main... | Lab #3 combining python codes after importing files where do I start? | Need help figuring out where to start after I import my two previous question files. Everything I've tried doesn't seem to want to take. So I scrapped it and trying to figure out where to begin again
1. In a file called FirstName_LastName_Main.py import Question_1.py and Question_2.py modules.
2. Prompt and read in ... | [
"#SSince it decided to show weirdly above sharing the files below. This is question_2\n...\namount = input()\nif amount <= 0:\n print(\" No Change \")\n\nelse:\n dollar = int(amount / 100)\n\n amount = amount % 100\n\n quarter = int(amount / 25)\n\n amount = amount % 25\n\n dime = int(amount / 10)\n\n amount = amou... | [
1
] | [] | [] | [
"lab",
"python"
] | stackoverflow_0074383781_lab_python.txt |
Q:
How to Find the Minimum Value in the Binary Search Tree
How can I find the minimum node in this binary search tree. I can't make it work.
....................................................................
....................................................................
class BinarySearchTree:
def __init... | How to Find the Minimum Value in the Binary Search Tree | How can I find the minimum node in this binary search tree. I can't make it work.
....................................................................
....................................................................
class BinarySearchTree:
def __init__(self, root):
self.root = root
self.left = ... | [
"def find_min(self):\n # traverse left subtree\n current = self\n while self.left is not None:\n current = self.left\n return current.root\n\ntree = BinarySearchTree(\"10\")\ntree.insert(\"20\")\ntree.insert(\"30\")\nprint(tree.search(\"20\")) # output: True\nprint(tree.search(\"40\")) # output... | [
1
] | [] | [] | [
"binary_search_tree",
"data_structures",
"find",
"python"
] | stackoverflow_0074383641_binary_search_tree_data_structures_find_python.txt |
Q:
SecretManagerServiceClient raises 403 Permission denied CONSUMER_INVALID in Google App Engine but `gcloud secrets versions access` works
Background:
I'm trying to deploy a Django app to the Google App Engine (GAE) standard environment in the python39 runtime
The database configuration is stored in a Secret Manage... | SecretManagerServiceClient raises 403 Permission denied CONSUMER_INVALID in Google App Engine but `gcloud secrets versions access` works | Background:
I'm trying to deploy a Django app to the Google App Engine (GAE) standard environment in the python39 runtime
The database configuration is stored in a Secret Manager secret version, similar to Google's GAE Django tutorial (link)
The app is run as a user-managed service account server@myproject.iam.gservic... | [
"You have granted the incorrect role. Have a look to that documentation page.\n\nSecret Viewer role allows you to view the secret and versions but NOT the content.\nSecret Accessor role allows you to access to secret version content.\n\n",
"Sigh. This was a terrible case of a hard-to-read typo in the app.yaml fil... | [
0,
0
] | [] | [] | [
"django",
"google_app_engine",
"google_cloud_platform",
"google_secret_manager",
"python"
] | stackoverflow_0074367521_django_google_app_engine_google_cloud_platform_google_secret_manager_python.txt |
Q:
Extract a subset of key-value pairs from dictionary?
I have a big dictionary object that has several key value pairs (about 16), but I am only interested in 3 of them. What is the best way (shortest/efficient/most elegant) to subset such dictionary?
The best I know is:
bigdict = {'a':1,'b':2,....,'z':26}
subdict ... | Extract a subset of key-value pairs from dictionary? | I have a big dictionary object that has several key value pairs (about 16), but I am only interested in 3 of them. What is the best way (shortest/efficient/most elegant) to subset such dictionary?
The best I know is:
bigdict = {'a':1,'b':2,....,'z':26}
subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']}
... | [
"You could try:\ndict((k, bigdict[k]) for k in ('l', 'm', 'n'))\n\n... or in Python 3 Python versions 2.7 or later (thanks to Fábio Diniz for pointing that out that it works in 2.7 too):\n{k: bigdict[k] for k in ('l', 'm', 'n')}\n\nUpdate: As Håvard S points out, I'm assuming that you know the keys are going to be ... | [
559,
143,
31,
29,
17,
7,
7,
6,
4,
2,
2,
1,
0,
0
] | [] | [] | [
"associative_array",
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0005352546_associative_array_dictionary_python_python_3.x.txt |
Q:
Getting empty list when scraping web page content using xpath in Python
When i try to import some data using xpath from the url in the following code i get an empty list:
import requests
from lxml import html
url = 'https://www.sofascore.com/team/football/palmeiras/1963'
browsers = {'User-Age... | Getting empty list when scraping web page content using xpath in Python | When i try to import some data using xpath from the url in the following code i get an empty list:
import requests
from lxml import html
url = 'https://www.sofascore.com/team/football/palmeiras/1963'
browsers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \(KHTML, l... | [
"You are getting an empty list because //*[@id=\"__next\"]/div/main/div/div[2]/div[2]/div/div[2]/div[3]/div[2]/div[2]/div[1]/span[1] XPath locator matches nothing on that page.\nLong absolute XPath locators are extremely unreliable and fragile.\n",
"Information in that page is being pulled by javascript (after in... | [
0,
0,
0
] | [] | [] | [
"lxml",
"python",
"python_requests",
"web_scraping",
"xpath"
] | stackoverflow_0074130829_lxml_python_python_requests_web_scraping_xpath.txt |
Q:
Create column from different column values replacing values
I would like to take the different values from my data frame and replace these values for the variables zip_code and id in the string query.
Example
This is my query
UPDATE hospitals
SET zip_code = 96761
WHERE id =
'o5FOLOdM1UtOXDB5_WDbWA'
AND zip_code = ... | Create column from different column values replacing values | I would like to take the different values from my data frame and replace these values for the variables zip_code and id in the string query.
Example
This is my query
UPDATE hospitals
SET zip_code = 96761
WHERE id =
'o5FOLOdM1UtOXDB5_WDbWA'
AND zip_code = 9676
This is the input data frame
name zip_code new_zip... | [
"assuming your original dataframe is named 'df', then this should work:\ndf['query'] = 'UPDATE hospitals SET zip_code = ' + df['new_zip_code'].astype(str) + \" WHERE id = '\" + df['id'].astype(str) + \"' AND zip_code = \" + df['zip_code'].astype(str)\n\n",
"import pandas as pd\n \n# Initializing data\ndata = [{... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"str_replace"
] | stackoverflow_0074383808_dataframe_pandas_python_str_replace.txt |
Q:
negative zero in python
I encountered negative zero in output from python; it's created for example as follows:
k = 0.0
print(-k)
The output will be -0.0.
However, when I compare the -k to 0.0 for equality, it yields True. Is there any difference between 0.0 and -0.0 (I don't care that they presumably have differ... | negative zero in python | I encountered negative zero in output from python; it's created for example as follows:
k = 0.0
print(-k)
The output will be -0.0.
However, when I compare the -k to 0.0 for equality, it yields True. Is there any difference between 0.0 and -0.0 (I don't care that they presumably have different internal representation; ... | [
"Check out −0 (number) in Wikipedia\nBasically IEEE does actually define a negative zero.\nAnd by this definition for all purposes:\n-0.0 == +0.0 == 0\n\nI agree with aaronasterling that -0.0 and +0.0 are different objects. Making them equal (equality operator) makes sure that subtle bugs are not introduced in the ... | [
43,
20,
17,
14,
1,
0,
0
] | [] | [] | [
"floating_accuracy",
"floating_point",
"python",
"zero"
] | stackoverflow_0004083401_floating_accuracy_floating_point_python_zero.txt |
Q:
How to mark the duplicated items in dataframe?
I am trying to mark the index number for each duplicated item in the below dataframe.
Column_A
0 Kitten
1 Kitten
2 Judy
3 Lamb
4 Momo
5 Judy
The new dataframe I want is as follows. As you can see, the items which have more than one (such as "Jud... | How to mark the duplicated items in dataframe? | I am trying to mark the index number for each duplicated item in the below dataframe.
Column_A
0 Kitten
1 Kitten
2 Judy
3 Lamb
4 Momo
5 Judy
The new dataframe I want is as follows. As you can see, the items which have more than one (such as "Judy") are marked.
Column_B Column_A
0 Kitten_1 ... | [
"try this:\nout = (df.Column_A.str.cat((df.groupby('Column_A')\n .cumcount()+1).astype('str'), sep='_')\n .rename('Column_B')\n .to_frame()\n .join(df))\nprint(out)\n>>>\n\n Column_B Column_A\n0 Kitten_1 Kitten\n1 Kitten_2 Kitten\n2 Judy_1 Judy\n3 ... | [
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074383440_dataframe_pandas_python.txt |
Q:
"ModuleNotFoundError: No module named 'rich'" even though I installed with pip
I'm trying to import the rich python module into my code, but I keep getting a 'ModuleNotFoundError' even thought I used pip install --user rich after getting the error, but I still get the same error, I was wondering if anyone has enco... | "ModuleNotFoundError: No module named 'rich'" even though I installed with pip | I'm trying to import the rich python module into my code, but I keep getting a 'ModuleNotFoundError' even thought I used pip install --user rich after getting the error, but I still get the same error, I was wondering if anyone has encountered a similar problem and knows how to fix it? Thanks.
| [
"Your install of pip may not be using the same Python version that you are trying to import Rich with. Try installing Rich with the following:\npython -m pip install rich\n\n",
"If the following won't work\npython -m pip install rich\n\nThen it should be something to do with dependency conflicts.\nI'm having a pa... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0072149472_python.txt |
Q:
How to approach doing a full time load for my data in Oracle to MariaDB?
I'm not sure how to go about doing a one time load of the existing data I have in Oracle to MariaDB. I have DBeaver which I am using to access the databases. I saw an option in DBeaver to migrate the data from Source (Oracle) to Target (Maria... | How to approach doing a full time load for my data in Oracle to MariaDB? | I'm not sure how to go about doing a one time load of the existing data I have in Oracle to MariaDB. I have DBeaver which I am using to access the databases. I saw an option in DBeaver to migrate the data from Source (Oracle) to Target (MariaDB) with a few clicks, but I'm not sure if that's the best approach.
Is writin... | [
"Option 1 DBeaver\nIf DBeaver is willing to try it in a few clicks I'd try and see what it gives for some small tables.\nOption 2 MariaDB connect\nAlternately there MariaDB connect engine using ODBC or JDBC.\nNote you don't need to create table structure for all, but do need the list of table and generate CREATE TA... | [
0
] | [] | [] | [
"cdata",
"mariadb",
"oracle",
"python"
] | stackoverflow_0074382899_cdata_mariadb_oracle_python.txt |
Q:
How can I compare a set to an array in Python?
I'm trying to get all unique URLs on a web page e.g. https://www.ig.com/uk/trading-strategies (there can be duplicates) and then compare them to URLs in an array and if the URLs are unique to write data to a Google Sheet.
I'm really struggling getting all the unique U... | How can I compare a set to an array in Python? | I'm trying to get all unique URLs on a web page e.g. https://www.ig.com/uk/trading-strategies (there can be duplicates) and then compare them to URLs in an array and if the URLs are unique to write data to a Google Sheet.
I'm really struggling getting all the unique URLs on a webpage e.g. https://www.ig.com/uk/trading-... | [
"\nI thought I could append unique URLs to a list then to a set and then to a tuple to compare against the array but that doesn't seem to be working.\n\nInstead, you could just only add URLs that haven't been added already by adding maintaining and checking against a list of URLs that have been added already. Try\n... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074380801_python.txt |
Q:
Add categorical variable based on conditional selections / dataframe masks
I made three conditional selections on my dataframe. So lets say:
final_df[(final_df['acceptance_advice'] == 'standard') & (final_df['acceptance'] == 'ok')]
final_df[(final_df['acceptance_advice'] == 'not accepted') & (final_df['acceptance'... | Add categorical variable based on conditional selections / dataframe masks | I made three conditional selections on my dataframe. So lets say:
final_df[(final_df['acceptance_advice'] == 'standard') & (final_df['acceptance'] == 'ok')]
final_df[(final_df['acceptance_advice'] == 'not accepted') & (final_df['acceptance'] == 'ok')]
final_df[(final_df['acceptance_advice'] == 'postponed') & (final_df[... | [
"Maybe like this?\nimport pandas as pd\n\n# Data thing - we can skip it\nid = [0,1,2,3,4,5]\nacceptance_advice = ['standard','not accepted','postponed','standard','not accepted','postponed']\nacceptance = ['ok','ok','declined','ok','ok','declined']\n\ndata = [id, acceptance_advice, acceptance]\ndf = pd.DataFrame(c... | [
0,
0,
0
] | [] | [] | [
"categorical",
"mask",
"pandas",
"python"
] | stackoverflow_0074346292_categorical_mask_pandas_python.txt |
Q:
How can i choose just one value from this list with random lib?
Hello i want to randomly choose just 1 value from Animal key anyone can help me?
import random
dict = {
"Animals": ["Elephant", "Lion", "Snake"]
}
a1 = random.choice(list(dict.values()))
print(a1)
this outputs whole value part. how can i make... | How can i choose just one value from this list with random lib? | Hello i want to randomly choose just 1 value from Animal key anyone can help me?
import random
dict = {
"Animals": ["Elephant", "Lion", "Snake"]
}
a1 = random.choice(list(dict.values()))
print(a1)
this outputs whole value part. how can i make python just randomly choose 1 of them
| [
"Try this, list(dict.values()) -> [[\"Elephant\", \"Lion\", \"Snake\"]] this will convert the dict values to list of list so when you are chosing values you are get one list as answer in your case only single list is created so you are getting that list only\nimport random\n\ndict_ = {\n\n \"Animals\": [\"Eleph... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074384086_python.txt |
Q:
How to convert .webp to .apng in python?
I'm trying to convert animate image in .webp to .apng ; i've tried the following:
from PIL import Image, ImageSequence
from apng import APNG
im = Image.open('/content/animate_w.webp')
#im.save('/content/animate_w.apng', 'apng', save_all = True, optimize = True, background=0... | How to convert .webp to .apng in python? | I'm trying to convert animate image in .webp to .apng ; i've tried the following:
from PIL import Image, ImageSequence
from apng import APNG
im = Image.open('/content/animate_w.webp')
#im.save('/content/animate_w.apng', 'apng', save_all = True, optimize = True, background=0) # not work
im.save('/content/animate_w.png',... | [
"You have the correct direction, you just need to add steps to extract the frames from the webp file.\nI hope the following code can add more ideas on how to achieve it.\nI am using webptools to extract the frames\nfrom webptools import webpmux_getframe\nfrom PIL import Image, ImageSequence\nfrom apng import APNG\n... | [
1,
0
] | [] | [] | [
"animation",
"image",
"png",
"python",
"webp"
] | stackoverflow_0071461852_animation_image_png_python_webp.txt |
Q:
RuntimeError: DataLoader worker exited unexpectedly
I am new to PyTorch and Machine Learning so I try to follow the tutorial from here:
https://medium.com/@nutanbhogendrasharma/pytorch-convolutional-neural-network-with-mnist-dataset-4e8a4265e118
By copying the code step by step I got the following error for no rea... | RuntimeError: DataLoader worker exited unexpectedly | I am new to PyTorch and Machine Learning so I try to follow the tutorial from here:
https://medium.com/@nutanbhogendrasharma/pytorch-convolutional-neural-network-with-mnist-dataset-4e8a4265e118
By copying the code step by step I got the following error for no reason. I tried the program on another computer and it gives... | [
"If you are working on jupyter notebook. The problem is more likely to be num_worker. You should set num_worker=0. You can find here some solutions to follow. Because unfortunately, jupyter notebook has some issues with running multiprocessing.\n",
"Totally agreed!\nSet your dataloader as below:\ndataloader = Dat... | [
3,
1,
0
] | [] | [] | [
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0071261347_machine_learning_python_pytorch.txt |
Q:
how to check is certain time dimension persent in datetime column in pandas?
how can I check whether a particular section (ex: year or day) is present in the DateTime column in pandas? it's something like you want to examine the time gap between two rows in hours, but first, you need to check that the hour's secti... | how to check is certain time dimension persent in datetime column in pandas? | how can I check whether a particular section (ex: year or day) is present in the DateTime column in pandas? it's something like you want to examine the time gap between two rows in hours, but first, you need to check that the hour's section is present in DateTime.
desired outcome:
datetime
is hours present
2020... | [
"I can't workout what you're asking, so hopefully this overkill helps;\nimport pandas as pd\nimport numpy as np\nimport datetime\n\n# create dummy dataframe with mock data\ndf = pd.DataFrame({'datetime': ['2021-01-01 00:00:00', '2021-01-02 00:00:00', '2021-01-03 00:00:00', '2021-01-04 00:00:00', '2021-01-05 00:00:0... | [
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074383825_datetime_pandas_python.txt |
Q:
python: Parsing error when converting to tflite model
I'm currently trying to convert an object detection model to a tflite model. I've used the https://www.tensorflow.org/lite/convert/index tutorial and achieved to convert a few different models to tflite, but my problem has arrived with a not-so-developed model:... | python: Parsing error when converting to tflite model | I'm currently trying to convert an object detection model to a tflite model. I've used the https://www.tensorflow.org/lite/convert/index tutorial and achieved to convert a few different models to tflite, but my problem has arrived with a not-so-developed model: faced (https://github.com/iitzco/faced). I've used the sam... | [
"To convert your model to tflite format you have to save your model in tensorflow save format using tf.keras.models.save_model()\nThen you can convert that save model to tflite using\n# Convert the model\nconverter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) # path to the SavedModel directory\ntflit... | [
0
] | [] | [] | [
"object_detection",
"python",
"tensorflow",
"tensorflow_lite"
] | stackoverflow_0068636789_object_detection_python_tensorflow_tensorflow_lite.txt |
Q:
Repeating same operation for multiple columns of another df
I'm quite new to python and pandas so I hope I can get some help.
I have a train_df that looks like this:
x y1 y2 y3 y4
0 -20.0 -0.702864 10.392012 1.013891 -8794.9050
1 -19.9 -0.591605 9.450884 1.231116 -8667.2340... | Repeating same operation for multiple columns of another df | I'm quite new to python and pandas so I hope I can get some help.
I have a train_df that looks like this:
x y1 y2 y3 y4
0 -20.0 -0.702864 10.392012 1.013891 -8794.9050
1 -19.9 -0.591605 9.450884 1.231116 -8667.2340
2 -19.8 -0.983952 10.240055 0.675153 -8541.5720
And an ide... | [
"Merge/join the the two dataframes by index and then for each yx column of train_df, compute the squared deviation:\ntrain_df = pd.DataFrame(data=[ [-20.0,-0.702864,10.392012,1.013891,-8794.9050], [-19.9,-0.591605,9.450884,1.231116,-8667.2340], [-19.8,-0.983952,10.240055,0.675153,-8541.5720] ], columns=[\"x\",\"y1\... | [
1
] | [] | [] | [
"data_analysis",
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074373884_data_analysis_data_science_dataframe_pandas_python.txt |
Q:
How to convert data into timeseries for column groups
I have data with timestamps. Users do tasks, and the timestamp is recorded. Each user is identified by a 'uid'. I want to convert this data into 10-minute granular time series, but for each user separately. So, timestamp goes in chronological order for uid=1 se... | How to convert data into timeseries for column groups | I have data with timestamps. Users do tasks, and the timestamp is recorded. Each user is identified by a 'uid'. I want to convert this data into 10-minute granular time series, but for each user separately. So, timestamp goes in chronological order for uid=1 separately, then for uid=2 and so on.
From:
timestamp ... | [
"grouped by uid column and resample 10T\nimport numpy as np\n\n(df.groupby('uid')\n .resample(rule='10T')['var'].sum()\n .reset_index(level=0)\n .replace({0: np.NaN}))\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074384084_dataframe_pandas_python.txt |
Q:
Problem to login Gmail account with Selenium Python
I'm writing a Python code using Selenium to optimize tasks on Google Sites.
For this to be possible, you need to log into your Gmail account.
I can't log into the account because Google doesn't recognize the valid browser.
Any solution to this problem?
A:
You c... | Problem to login Gmail account with Selenium Python | I'm writing a Python code using Selenium to optimize tasks on Google Sites.
For this to be possible, you need to log into your Gmail account.
I can't log into the account because Google doesn't recognize the valid browser.
Any solution to this problem?
| [
"You can bypass bot detection with SeleniumBase in uc mode.\nFirst pip install seleniumbase. Then you can run:\nfrom seleniumbase import SB\n\nwith SB(uc=True) as sb:\n sb.open(\"https://www.google.com/gmail/about/\")\n sb.click('a[data-action=\"sign in\"]')\n sb.type('input[type=\"email\"]', \"test123@gma... | [
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074383141_python_selenium.txt |
Q:
Django - display value of an @property field in a filter
Good evening guys, I have the following model structure in my project:
`
class Foo(models.Model):
foo_name = models.TextField()
foo_city = models.TextField()
foo_actions = models.ManyToManyField(Action, through="FooActions")
@property
def ba... | Django - display value of an @property field in a filter | Good evening guys, I have the following model structure in my project:
`
class Foo(models.Model):
foo_name = models.TextField()
foo_city = models.TextField()
foo_actions = models.ManyToManyField(Action, through="FooActions")
@property
def bar(self):
response = True if FooAction.objects.filter(
... | [
"No, it's not possible directly because @property method interacts with a model's objects it is not a field of model\nthe model field is a column of the data table but, @property method interacts with a model column I mean it's not part of the SQL query\nbut you can achieve those things using a third-party library.... | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"python",
"python_3.x"
] | stackoverflow_0074381973_django_django_models_django_rest_framework_python_python_3.x.txt |
Q:
How to extract List items from website into DataFrame? (Clear example given)
I feel at the outset I should mention that this is a purely personal project.
I am looking to scrape car data from a well known car website. Their website for each car "product card" is structured as follows:
<section class="product-card-... | How to extract List items from website into DataFrame? (Clear example given) | I feel at the outset I should mention that this is a purely personal project.
I am looking to scrape car data from a well known car website. Their website for each car "product card" is structured as follows:
<section class="product-card-details">
<h3 class="product-card-details__title">
Mercedes-Benz A-Class
<... | [
"I created an html page with the code you pasted:\n<html>\n<body>\n<section class=\"product-card-details\">\n <h3 class=\"product-card-details__title\">\nMercedes-Benz A-Class\n </h3>\n\n <p class=\"product-card-details__subtitle\">\n1.3 A 200 AMG LINE 5d 161 BHP | 14-DAYS MONEY BACK GUARANTEE*\n </p>\n... | [
1,
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074377138_python_selenium.txt |
Q:
iterate over select columns and check if a specfic value is in these select columns and use that column name that has that value to create a new table
If I have below table
+-----+-----+---+-----+-----+-----+-----+-----+-----+-----+
| a| b| id|m2000|m2001|m2002|m2003|m2004|m2005
+-----+-----+---+-----+--... | iterate over select columns and check if a specfic value is in these select columns and use that column name that has that value to create a new table | If I have below table
+-----+-----+---+-----+-----+-----+-----+-----+-----+-----+
| a| b| id|m2000|m2001|m2002|m2003|m2004|m2005
+-----+-----+---+-----+-----+-----+-----+-----+-----+-----+
|a |world| 1| 0| 0| 1| 0| 0| 1|
+-----+-----+---+-----+-----+-----+-----+-----+-----+-----+
... | [
"Assuming a dataframe with a more complete scenario, where there are rows without years to '1' and rows with more '1's:\nfrom pyspark.shell import spark\nfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType\n\ndata2 = [(\"a\", \"world\", \"1\", 0, 0, 1,0,0,1),\n (\"b\", \"world\", ... | [
0,
0
] | [] | [] | [
"apache_spark",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074376972_apache_spark_dataframe_pyspark_python.txt |
Q:
How to train Custom Tensorflow Models in Azure ML Studio Designer
I am currently trying out different architectures with Azure ML Ecosystem. Currently, I am testing out Azure ML Studio Designer.
When I created a custom Tensorflow model using the "Create Python Model" Component. When I run the designer pipeline I g... | How to train Custom Tensorflow Models in Azure ML Studio Designer | I am currently trying out different architectures with Azure ML Ecosystem. Currently, I am testing out Azure ML Studio Designer.
When I created a custom Tensorflow model using the "Create Python Model" Component. When I run the designer pipeline I get an error saying that Tensorlfow is not found.
Error:
---------- Star... | [
"Directly we cannot install TensorFlow in designer. Instead, we can call the node of the algorithm which includes TensorFlow internally. For example, I am performing Image classification using DenseNet. Checkout the following flow.\n\n\n\n\nThis below screen is the complete picture of the flow in the designer.\n\n"... | [
0
] | [] | [] | [
"azure",
"azure_machine_learning_service",
"azure_ml_pipelines",
"python",
"tensorflow"
] | stackoverflow_0074342053_azure_azure_machine_learning_service_azure_ml_pipelines_python_tensorflow.txt |
Q:
python split dataframe based on multiple criteria in 2 columns
I need to filter the df based on 2 criteria: where Name != jack and ignore all dates for jack where Date <= 2020-04-01
# List of Tuples
df = [ ('jack', 'Apples' , '2020-01-01') ,
('Riti', 'Mangos' , '2020-02-01') ,
('Aa... | python split dataframe based on multiple criteria in 2 columns | I need to filter the df based on 2 criteria: where Name != jack and ignore all dates for jack where Date <= 2020-04-01
# List of Tuples
df = [ ('jack', 'Apples' , '2020-01-01') ,
('Riti', 'Mangos' , '2020-02-01') ,
('Aadi', 'Grapes' , '2020-03-01') ,
('jack', 'Oranges', '20... | [
"boolean indexing of multi condition\ncond1 = df1['Name'] != 'jack'\ncond2 = pd.to_datetime(df1['Date']) > pd.Timestamp('2020-04-01')\ndf1[cond1 | cond2].reset_index(drop=True)\n\noutput:\n Name Product Date\n0 Riti Mangos 2020-02-01\n1 Aadi Grapes 2020-03-01\n2 Lucy Mangos 2020-05-01\n3 j... | [
2,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074384114_numpy_pandas_python.txt |
Q:
PermissionError Multiprocessing argument pyppeteer.Page
PermissionError Multiprocessing argument pyppeteer.Page
successful but inefficient
import asyncio
from pyppeteer import launch
from multiprocessing import Process
async def f(x):
print("async def f(x,page):",x)
browser = a... | PermissionError Multiprocessing argument pyppeteer.Page | PermissionError Multiprocessing argument pyppeteer.Page
successful but inefficient
import asyncio
from pyppeteer import launch
from multiprocessing import Process
async def f(x):
print("async def f(x,page):",x)
browser = await launch(headless=False, autoClose=False)
page = (... | [
"I got the desired result with this code.\n queue = asyncio.Queue()\n browser = await launch(headless=False, autoClose=False)\n \n for i in range(MAX_TASK_COUNT-1): \n await browser.newPage() \n \n pages = await browser.pages()\n\n for page in pages:\n asyncio.create_task(cr... | [
1
] | [] | [] | [
"multiprocessing",
"permissionerror",
"pyppeteer",
"python"
] | stackoverflow_0074370230_multiprocessing_permissionerror_pyppeteer_python.txt |
Q:
my input function is giving traceback and valueError-python
I have asked the user for input and set out while true,try and expect blocks. I keep getting valueError even though I have set out that integer required should be displayed if I enter a letter.
pass_credit=int(input("please enter your credits at pass:"))
... | my input function is giving traceback and valueError-python | I have asked the user for input and set out while true,try and expect blocks. I keep getting valueError even though I have set out that integer required should be displayed if I enter a letter.
pass_credit=int(input("please enter your credits at pass:"))
defer_credit=int(input("Please enter your credits at defer:"))
fa... | [
"You are not including all your code as you describe it. Input section should look like this:\nwhile True:\n try: \n pass_credit=int(input(\"please enter your credits at pass:\"))\n break\n except ValueError as e:\n print (\"Bad integer value entered, try again.\")\n\nwhile True:\n ... | [
1,
0
] | [] | [] | [
"function",
"input",
"python"
] | stackoverflow_0074384135_function_input_python.txt |
Q:
Discord.py - message.content is empty for every message
I'm trying to make a discord bot and when I run it locally, it works fine; However when I push it to heroku, it doesn't work because message.content is empty for some reason for every message. It was working fine just a few days ago, but it broke now.
main.py... | Discord.py - message.content is empty for every message | I'm trying to make a discord bot and when I run it locally, it works fine; However when I push it to heroku, it doesn't work because message.content is empty for some reason for every message. It was working fine just a few days ago, but it broke now.
main.py code:
@client.event
async def on_message(message):
msg =... | [
"Go to the dev portal and turn on intents\nThen when creating the bot add\nimport discord\nfrom discord.ext import commands\n\nclient = commands.Bot(command_prefix=\">\", intents=discord.Intents.all())]\n\n@client.event\nasync def on_message(message):\n if message.author.bot:\n pass\n else:\n pr... | [
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0071750709_discord.py_python.txt |
Q:
Pip Install stuck on "Preparing Wheel metadata..." when trying to install PyQT5
I'm trying to install PyQT5 on my Raspberry Pi and used the command sudo pip3 install pyqt5.
But it has been stuck on that for over an hour nowand I'm starting to get frustrated, since it still moves, so it didn't crash or anything. Is... | Pip Install stuck on "Preparing Wheel metadata..." when trying to install PyQT5 | I'm trying to install PyQT5 on my Raspberry Pi and used the command sudo pip3 install pyqt5.
But it has been stuck on that for over an hour nowand I'm starting to get frustrated, since it still moves, so it didn't crash or anything. Is there a workaround for that or am I missing something?
Thanks in advance
| [
"I had the same problem and got impatient after a few dozen minutes...\nThen tried running the command with:\npip3 install --verbose PyQt5\nso this way I could always be sure that it didn't crash in the background.\nIt completed after almost 2 hours. The compilation takes some time...\n",
"This is a little hacky,... | [
11,
8,
2,
1,
0,
0
] | [] | [] | [
"pip",
"pyqt",
"pyqt5",
"python",
"raspberry_pi"
] | stackoverflow_0066546886_pip_pyqt_pyqt5_python_raspberry_pi.txt |
Q:
Updating environmental variables in Django while running
I have an app that makes some API calls, I store my API secret in an .env file which is loaded into the Django settings file which works fine.
Once a month I have to update the API secret, I have the code to check for expiry and get the new key, my question ... | Updating environmental variables in Django while running | I have an app that makes some API calls, I store my API secret in an .env file which is loaded into the Django settings file which works fine.
Once a month I have to update the API secret, I have the code to check for expiry and get the new key, my question is how to handle that within my running Django app. As it stan... | [
"You can store your settings dynamically in your database. There are a bunch of libraries which provide such opportunity, but the one I personally use in production is django-constance\n"
] | [
0
] | [] | [] | [
"django",
"environment_variables",
"python"
] | stackoverflow_0074382368_django_environment_variables_python.txt |
Q:
Python loop to execute multiple sql files in a directory
I have multiple .sql files that have DROP IF EXISTS and CREATE TABLE statements that I want to execute automatically without having to click on them through python.
I'm getting errors using this script:
import os
import fnmatch
for root, dirnames, filenames... | Python loop to execute multiple sql files in a directory | I have multiple .sql files that have DROP IF EXISTS and CREATE TABLE statements that I want to execute automatically without having to click on them through python.
I'm getting errors using this script:
import os
import fnmatch
for root, dirnames, filenames in os.walk("C:/Users/user/Desktop/Generated"):
for filename... | [
"Check out this answer. You'll have to use a library to actually execute the file.\n\nRead the .sql file\nExecute the text read from the file.\n\nsql = filename.read() % params # Don't do that with untrusted inputs\n cursor.execute(sql)\n cursor.commit()\n cursor.close()\n\n\n",
"... | [
0,
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0064884256_python_sql.txt |
Q:
Jira API : when using PUT call getting "no single-String constructor/factory method"
I was trying to update a custom field on a Jira ticket using Jira API, following this Jira Documentation. however, I am getting the below error.
{'errorMessages': ['Can not instantiate value of type [simple type, class com.atlass... | Jira API : when using PUT call getting "no single-String constructor/factory method" | I was trying to update a custom field on a Jira ticket using Jira API, following this Jira Documentation. however, I am getting the below error.
{'errorMessages': ['Can not instantiate value of type [simple type, class com.atlassian.jira.rest.v2.issue.IssueUpdateBean] from JSON String; no single-String constructor/fac... | [
"I think is a matter of single quotes.\nAs far as I remember, for valid JSON it should be double quotes.\n{\n \"update\": {\n \"customfield_25305\": [{\n \"set\": [{\n \"value\": \"1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9\"\n }, {\n \"value\": \"c6f1e31c... | [
0,
0
] | [] | [] | [
"jira_rest_api",
"python"
] | stackoverflow_0074374799_jira_rest_api_python.txt |
Q:
Check if string in a column, then return value from another column at the same index
Contact
Old Contact
234255
987778
343556
987877
Missing
984567
Missing
Missing
845665
343556
789998
Given the table above, I wish to go through each row under "Contact" and check if Missing. If the row has Missing, use corr... | Check if string in a column, then return value from another column at the same index |
Contact
Old Contact
234255
987778
343556
987877
Missing
984567
Missing
Missing
845665
343556
789998
Given the table above, I wish to go through each row under "Contact" and check if Missing. If the row has Missing, use corresponding "Old Contact" values inplace of the text 'Missing'. If old conta... | [
"use mask\ndf['Contact'].mask(df['Contact'].eq('Missing'), df['Old Contact'].fillna('Missing'))\n\noutput:\n0 234255\n1 343556\n2 984567\n3 Missing\n4 845665\n5 343556\nName: Contact, dtype: object\n\nmake reult to Contact column\n",
"You have two conditions you are checking. You can ... | [
1,
0,
0,
0
] | [] | [] | [
"apply",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074384043_apply_dataframe_pandas_python.txt |
Q:
Filtering dataframe columns with unsupported data type
I am trying to select columns by data type 'datetime.date'.
I am aware of the filtering method select_dtypes, but the problem is that the column containing dates have object dtype.
Suppose I have dataframes defined as below.
num
??
0
2013-04-26
1
2007-04-25... | Filtering dataframe columns with unsupported data type | I am trying to select columns by data type 'datetime.date'.
I am aware of the filtering method select_dtypes, but the problem is that the column containing dates have object dtype.
Suppose I have dataframes defined as below.
num
??
0
2013-04-26
1
2007-04-25
2
2020-09-21
I want to extract only date colum... | [
"After several hours of trying, I finally got the answer. Still, I will leave this post for those who are facing similar problems.\nFirst, convert the dataframe into the boolean dataframe that indicates whether the data type in each cell match desired data type.\ndf_boolean_by_date = df.applymap(lambda x: isinstanc... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074383555_dataframe_pandas_python.txt |
Q:
How do I ignore an iteration that has a bad user input?
I have a function, findnums(v) that is intended to append 5 numbers taken from user input to list v, which starts in main as an empty list. I have a nested try-except loop in my for loop for the function findnums(v) to try and reject non float user input.
I w... | How do I ignore an iteration that has a bad user input? | I have a function, findnums(v) that is intended to append 5 numbers taken from user input to list v, which starts in main as an empty list. I have a nested try-except loop in my for loop for the function findnums(v) to try and reject non float user input.
I want my except condition to ignore the iteration that had the ... | [
"I would use a while loop for this.\ndef main():\n v=[]\n findnums(v)\n printlist(v)\n\ndef findnums(v):\n # Reapeat the following until there is a break\n while(True):\n # If the list has a length of 5, break\n if len(v) == 5:\n break\n try:\n val = float(i... | [
0,
0,
0
] | [] | [] | [
"for_loop",
"iteration",
"loops",
"python",
"validation"
] | stackoverflow_0074383033_for_loop_iteration_loops_python_validation.txt |
Q:
KeyError in Pandas Series
I am trying to convert a Pandas item to a list in Python, and I have run across this error. Here is an example.
import pandas
data = pandas.read_csv("random_data.csv")
item_list = data['item'].to_list()
print(item_list)
This is the csv file
Item,Item2
1,2
3,4
5,6
It produces a very lo... | KeyError in Pandas Series | I am trying to convert a Pandas item to a list in Python, and I have run across this error. Here is an example.
import pandas
data = pandas.read_csv("random_data.csv")
item_list = data['item'].to_list()
print(item_list)
This is the csv file
Item,Item2
1,2
3,4
5,6
It produces a very long error, and it ends with KeyE... | [
"Because the column item is not present in your csv file. Instead, it should be Item in your Python code.\n\nimport pandas as pd\n\ndata = pd.read_csv(\"random_data.csv\", index_col=[0])\nitem_list = data['Item'].to_list()\nprint(item_list)\n\n[1, 2, 3]\n\n"
] | [
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074382365_csv_pandas_python.txt |
Q:
How to update SQLite?
Using local Jupyter Notebook, SQLite, Pandas and Plotly I want to move that notebook to the Colab website but it is reporting SQLite version 3.22 instead of 3.30. I am using window functions available since SQLite 3.28 so have to upgrade. I tried :
!apt-get update
!apt-get upgrade sqlite3
Th... | How to update SQLite? | Using local Jupyter Notebook, SQLite, Pandas and Plotly I want to move that notebook to the Colab website but it is reporting SQLite version 3.22 instead of 3.30. I am using window functions available since SQLite 3.28 so have to upgrade. I tried :
!apt-get update
!apt-get upgrade sqlite3
This tells me I have SQLite 3... | [
"Here's how to upgrade to the latest version\n!curl https://www.sqlite.org/src/tarball/sqlite.tar.gz?r=release | tar xz\n%cd sqlite/\n!./configure\n!make sqlite3.c\n%cd /content\n!npx degit coleifer/pysqlite3 -f\n!cp sqlite/sqlite3.[ch] .\n!python setup.py build_static build\n!cp build/lib.linux-x86_64-3.7/pysqlite... | [
8,
1,
0
] | [] | [] | [
"google_colaboratory",
"python",
"sqlite"
] | stackoverflow_0059427642_google_colaboratory_python_sqlite.txt |
Q:
How can i set my image as background on my tkinter digital clock?
I want to have my digital clock on top of the background. Currently the time is displaying above the image that im using
How should i set up this code? This is what i have come up with so far
from tkinter import *
from PIL import ImageTk,Image
impor... | How can i set my image as background on my tkinter digital clock? | I want to have my digital clock on top of the background. Currently the time is displaying above the image that im using
How should i set up this code? This is what i have come up with so far
from tkinter import *
from PIL import ImageTk,Image
import time
root=Tk()
root.title("Klocka")
root.attributes("-topmost", 1)
r... | [
"You can use place() instead of pack() to place the clock on top of the center of the canvas:\ndigi_clock.place(x=150, y=70, anchor=\"c\")\n\n\nHowever the background of the clock label is not transparent.\nYou can use canvas.create_text() instead to show the clock and use canvas.itemconfigure() to update the clock... | [
0
] | [] | [] | [
"image",
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0074383404_image_python_python_imaging_library_tkinter.txt |
Q:
Setting a python script default when creating a new file
I would like to set a default custom script whenever creating a new .py file or .ipynb file in Pycharm or VS Code.
I would like the default script to load looking as such:
import time
import datetime
start = time.time()
# Code here.
end = time.time()
print... | Setting a python script default when creating a new file | I would like to set a default custom script whenever creating a new .py file or .ipynb file in Pycharm or VS Code.
I would like the default script to load looking as such:
import time
import datetime
start = time.time()
# Code here.
end = time.time()
print(str(datetime.timedelta(seconds=end - start)))
Is it possible... | [
"It is currently not possible to set a new file template. Maybe the code snippet will help you.\n\nYou can easily define your own snippets without any extension. To create or edit your own snippets, select User Snippets under File > Preferences (Code > Preferences on macOS), and then select the language (by languag... | [
1
] | [] | [] | [
"jupyter_notebook",
"pycharm",
"python",
"visual_studio_code"
] | stackoverflow_0074374257_jupyter_notebook_pycharm_python_visual_studio_code.txt |
Q:
Pygame: Reset the Angle after Rotation
The helicopter flies from right to left. When a key is pressed it crashes. In the code excerpt, it flies to the bottom right corner.
Then another helicopter should come from the left and fly straight ahead to the right. That doesn't happen. He comes from the left and immediat... | Pygame: Reset the Angle after Rotation | The helicopter flies from right to left. When a key is pressed it crashes. In the code excerpt, it flies to the bottom right corner.
Then another helicopter should come from the left and fly straight ahead to the right. That doesn't happen. He comes from the left and immediately falls again, although the angle has been... | [
"There are 2 problems:\n\nself.absturz == False is a comparison, but not an assignement\n\nself.absturz needs to be set True when self.rect hits the ground (self.absturz == True)\n\n\nclass Helikopter(pygame.sprite.Sprite):\n # [...]\n\n def update(self):\n self.rect.x += 2 \n self.rect.y += ... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074384445_pygame_python.txt |
Q:
Filter by specific values in Pyspark DataFrame
I have a crimes dataset and need to plot a monthly time series line chart of all crimes for the last 3 years (2019,2020,2021). My approach is to create a new dataframe where the count per month is the total count of incidents from 2019-202 and then plot that dataframe... | Filter by specific values in Pyspark DataFrame | I have a crimes dataset and need to plot a monthly time series line chart of all crimes for the last 3 years (2019,2020,2021). My approach is to create a new dataframe where the count per month is the total count of incidents from 2019-202 and then plot that dataframe.
An example would be
enter image description here
T... | [
"Due to the distributed architecture of spark, the dataset rows are split across different worker nodes and partitions. Operations where computation of next row depends on output of previous row are trickier in spark.\nFirst, partition the data by group. In your case, there is no such group, so introduce a dummy ke... | [
0
] | [] | [] | [
"dataframe",
"filter",
"pyspark",
"python"
] | stackoverflow_0074384398_dataframe_filter_pyspark_python.txt |
Q:
Replacing line contains NULL byte with '0' value
Columns with Null ByteHow can I replace the NULL byte with '0' value after opening up csv file?
My code is as follow but it doesn't work:
try:
# open source file
with open (dataFile,'r')as csvfile:
... | Replacing line contains NULL byte with '0' value | Columns with Null ByteHow can I replace the NULL byte with '0' value after opening up csv file?
My code is as follow but it doesn't work:
try:
# open source file
with open (dataFile,'r')as csvfile:
sourceDF = csv.reader(csvfile)
... | [
"There are multiple problems in these two lines:\nsourceDF = csv.reader(csvfile)\nreplaced = [sourceDF.replace(b'\\0',b'0') for sourceDF in replaced]\n\nThe first line reads data from the CSV file. replaced is None at this time.\nThe second line now tries to iterate over replaced, which is None - which doesn't work... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074384594_python.txt |
Q:
How to use each element in the list to check and locate the matching value from a data set?
I want to retrieve values from a data set that matches a certain value. The ".loc" method is working fine if I give one value at a time. But when trying to get the value from a list nothing is happening.
The below script wo... | How to use each element in the list to check and locate the matching value from a data set? | I want to retrieve values from a data set that matches a certain value. The ".loc" method is working fine if I give one value at a time. But when trying to get the value from a list nothing is happening.
The below script work fine.
df.loc[df.domains=="IN"]
The below script is not. I want to use each item from the lis... | [
"Instead of a=f'\"{i}\"' try a = list[i]\nYou need to access the list in position i in order to get the location you desire.\nAlso I noticed that in list you have extra \" in the beginning. It might give you a syntax error\n"
] | [
0
] | [] | [] | [
"data_science",
"pandas",
"python"
] | stackoverflow_0074384561_data_science_pandas_python.txt |
Q:
using yahoo! finance to get prior earnings dates for last 5 years for a given stock
Trying to get 1) earnings dates for the last 5 years for a given stock
(TGT) along with 2) the accompanying price percentage change on those days. Then put data in a dataframe
This is the code I have found to use so far but it seem... | using yahoo! finance to get prior earnings dates for last 5 years for a given stock | Trying to get 1) earnings dates for the last 5 years for a given stock
(TGT) along with 2) the accompanying price percentage change on those days. Then put data in a dataframe
This is the code I have found to use so far but it seems that the error comes from the date range. It seems that in this instance, yahoo! financ... | [
"The YahooEarningsCalendar is no longer actively maintained with the latest commit dating back to 2020.\nLooking at the code an error is thrown whenever the scraped result does not match an expected site structure. Several open issues exist regarding the missing User-Agents in the request, which are now required fo... | [
1,
0
] | [] | [] | [
"python",
"yahoo_finance"
] | stackoverflow_0071914472_python_yahoo_finance.txt |
Q:
WAP to remove duplicates in a list. Why is this wrong?
I expected every element to go through the for loop, then the duplicate ones to be removed through the if loop.
num = [5, 7, 21, 7, 5, 7, 7, 5, 7 , 7]
for i in num:
if num.count(i)!=1:
num.remove(i)
print(num)
What I get:
[21, 7, 5, 7, 7]
What I... | WAP to remove duplicates in a list. Why is this wrong? | I expected every element to go through the for loop, then the duplicate ones to be removed through the if loop.
num = [5, 7, 21, 7, 5, 7, 7, 5, 7 , 7]
for i in num:
if num.count(i)!=1:
num.remove(i)
print(num)
What I get:
[21, 7, 5, 7, 7]
What I expect:
[21, 5, 7]
| [
"Since you are reducing the size of array while iterating on it.\nfor i in num will check for the length of num. After 5 iterations (i=5), the length of num will become 5 and the loop will break.\nIt's better to always avoid mutating the list you're looping on.\nSame result can also be achieved simply by:\nnum = li... | [
3,
1
] | [
"Why not use np.unique?\nimport numpy as np\nunique_num = np.unique(num)\n\nhttps://numpy.org/doc/stable/reference/generated/numpy.unique.html\n"
] | [
-1
] | [
"list",
"python"
] | stackoverflow_0074384584_list_python.txt |
Q:
Prefill a list of field with value in a form
I'm developing a School Management System for my thesis and I've been stuck at implementing a grading module for 3 weeks now, I have gotten close to achieving my wanted result. I can now list all the students on a page depending on a selected subject and a field where t... | Prefill a list of field with value in a form | I'm developing a School Management System for my thesis and I've been stuck at implementing a grading module for 3 weeks now, I have gotten close to achieving my wanted result. I can now list all the students on a page depending on a selected subject and a field where the faculty can input a grade beside the student's ... | [
"Regarding the issue where the record is getting created rather than being updated if the student already has a grade in the subject, i fixed it by using django's update_or_create function\ndef add_gradebook_for(request, id):\n global student, s\n current_year = AcademicYear.objects.get(active=True)\n curr... | [
1,
0
] | [] | [] | [
"django_forms",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074371328_django_forms_django_models_django_templates_django_views_python.txt |
Q:
How get string between expression with Pandas?
I would like to get only codes between # and concat it to a new column.
What I have
id
code
0
(#M05Q01900R00100# = 1) AND (#M05Q01950R00200# = 0)
1
(#M05Q01900R00100# = 1) AND ((#M05Q01950R00100# = 0) OR (#M05Q01950R00200# = 0))
2
(#M05Q01600R00100# = 1)
3
(#M05Q... | How get string between expression with Pandas? | I would like to get only codes between # and concat it to a new column.
What I have
id
code
0
(#M05Q01900R00100# = 1) AND (#M05Q01950R00200# = 0)
1
(#M05Q01900R00100# = 1) AND ((#M05Q01950R00100# = 0) OR (#M05Q01950R00200# = 0))
2
(#M05Q01600R00100# = 1)
3
(#M05Q01125R00200# = 1)
4
(#M05Q01129R00100# = ... | [
"Use Series.str.findall with regex for values between # and then Series.str.join:\ndf['concat'] = df['code'].str.findall(r'#(.*?)#').str.join(', ')\nprint (df)\n id code \\\n0 0 (#M05Q01900R00100# = 1) AND (#M05Q01950R00200#... \n1 1 (#M05Q01900R00100# = 1... | [
1
] | [] | [] | [
"pandas",
"python",
"string_concatenation"
] | stackoverflow_0074384682_pandas_python_string_concatenation.txt |
Q:
Plotting Kernel Ridge Regression results in weird lines
I'm trying to run kernel Ridge regression on a simple artificial dataset. When I run the code, I get two plots. The first is for Linear Regression fit, which looks normal. however, the kernel one is very erratic. Is this expected behavior, or am I not calling... | Plotting Kernel Ridge Regression results in weird lines | I'm trying to run kernel Ridge regression on a simple artificial dataset. When I run the code, I get two plots. The first is for Linear Regression fit, which looks normal. however, the kernel one is very erratic. Is this expected behavior, or am I not calling the functions properly?
The first plt.show():
The second pl... | [
"The line plot appears jumbled because matplotlib draws a connecting line between each pair of points in the order they appear in the input array.\nThe solution is to sort the array of randomly generated x-values for which to generate and draw predictions:\nx_to_draw_line = np.random.randn(1000, 1).sort()\n\n"
] | [
1
] | [] | [] | [
"numpy",
"python",
"scikit_learn"
] | stackoverflow_0074384512_numpy_python_scikit_learn.txt |
Q:
Check if value in list except for number between {}
I have a list
list = ["Hat({})A", "Tie({})B", "Disk({})C"]
And another list:
inventory = ["Hat(1)A", "Hat(43)A", "Shirt(23)E", "Tie(2)B"]
In python, I want to iterate inventory for each item, if it contains the value except for the number, return true. If not, ... | Check if value in list except for number between {} | I have a list
list = ["Hat({})A", "Tie({})B", "Disk({})C"]
And another list:
inventory = ["Hat(1)A", "Hat(43)A", "Shirt(23)E", "Tie(2)B"]
In python, I want to iterate inventory for each item, if it contains the value except for the number, return true. If not, return false.
"Hat(1)A", "Hat(43)A", "Tie(2)B" = TRUE
"Sh... | [
"First you remove the curly braces from the list.\nl = [\"Hat({})A\", \"Tie({})B\", \"Disk({})C\"]\n\nnew_list = [''.join(x.split('{}')) for x in l]\n\n# ['Hat()A', 'Tie()B', 'Disk()C']\n\nYour inventory is:\ninventory = [\"Hat(1)A\", \"Hat(43)A\", \"Shirt(23)E\", \"Tie(2)B\"]\n\nTo find the numbers in inventory us... | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074384389_list_python.txt |
Q:
Create column names based on existing columns and fill values
I have a dataframe as such:
Year Col1 Col2 Col3 Col4 ......Col64 Reach
2019 12 17 11 11 10
2020 10 20 21 33 10
2021 19 15 22 32 10
2022 26 9 ... | Create column names based on existing columns and fill values | I have a dataframe as such:
Year Col1 Col2 Col3 Col4 ......Col64 Reach
2019 12 17 11 11 10
2020 10 20 21 33 10
2021 19 15 22 32 10
2022 26 9 16 12 10
I want to append existing columns to t... | [
"Use Index.difference for all columns names without 'Year','Reach', create subset and multiple by column Reach, then DataFrame.add_suffix and append to original by DataFrame.join:\ncols = df.columns.difference(['Year','Reach'], sort=False)\n\ndf = df.join(df[cols].mul(df['Reach'], axis=0).add_suffix(' Value'))\npri... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074384785_pandas_python.txt |
Q:
ImportError: Could not find 'cudart64_100.dll
I'm trying to install tensorflow-gpu==2.0.0-beta1 on my Windows 10 machine and got this error:
ImportError: Could not find 'cudart64_100.dll'. TensorFlow requires
that this DLL be installed in a directory that is named in your %PATH%
environment variable. Download... | ImportError: Could not find 'cudart64_100.dll | I'm trying to install tensorflow-gpu==2.0.0-beta1 on my Windows 10 machine and got this error:
ImportError: Could not find 'cudart64_100.dll'. TensorFlow requires
that this DLL be installed in a directory that is named in your %PATH%
environment variable. Download and install CUDA 10.0 from this URL:
https://dev... | [
"The simplest way to fix is to install the latest ‘NVIDIA GPU Computing Toolkit’, because if it's not there, you'll be missing the 'cudart64_100.dll' library.\nThe only issue is that the latest copy of CUDA has this particular library upgraded to 'cudart64_101.dll', while the latest TensorFlow still requires the ol... | [
14,
12,
6,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0057528027_python_tensorflow.txt |
Q:
How do we visualize csv point cloud data?
I am having an xyz file I want to preprocess and save it as a df, how do I visualize the csv file or convert it into xyz or las format in python
A:
save each xyz to a line, separate by a space, and add a column represent the color, and save these lines to a txt file, the... | How do we visualize csv point cloud data? | I am having an xyz file I want to preprocess and save it as a df, how do I visualize the csv file or convert it into xyz or las format in python
| [
"save each xyz to a line, separate by a space, and add a column represent the color, and save these lines to a txt file, then open the file with cloud-compare.\nthe txt file will looks like:\n1.23 0.12 3.45 1\n2.23 1.12 4.45 1\n3.23 2.12 5.45 0\n\n"
] | [
0
] | [] | [] | [
"point_cloud_library",
"point_clouds",
"python"
] | stackoverflow_0074358202_point_cloud_library_point_clouds_python.txt |
Q:
How to use elements in list by order
My goal is to change multiple csv files in a folder into JSON.
First, I needed to list my csv files
for file in os.listdir("C:/Users/folder_to_csv"):
filename = os.fsdecode(file)
if filename.endswith(".csv"):
#check if csv files are listed correctly
print(os.pat... | How to use elements in list by order | My goal is to change multiple csv files in a folder into JSON.
First, I needed to list my csv files
for file in os.listdir("C:/Users/folder_to_csv"):
filename = os.fsdecode(file)
if filename.endswith(".csv"):
#check if csv files are listed correctly
print(os.path.join("C:/Users/folder_to_csv", filename)... | [
"In the initial loop, you keep redefining the csvlist variable. I suppose you want it to be a list? Then just create an initial empty list and append to it instead of redefining\ncsvlist = []\n...\ncsvlist.append(os.path.join(\"C:/Users/folder_to_csv\", filename))\n\n"
] | [
0
] | [] | [] | [
"csv",
"json",
"python"
] | stackoverflow_0074384787_csv_json_python.txt |
Q:
Structlog and logging module not logging with pytest
So I have a testing folder structure (that tests a module src not shown here) like this:
├── tests
│ ├── __init__.py
│ ├── conftest.py
│ ├── test_main.py
And have the __init__.py configure my logging as shown:
import structlog, logging, sys
from structlog... | Structlog and logging module not logging with pytest | So I have a testing folder structure (that tests a module src not shown here) like this:
├── tests
│ ├── __init__.py
│ ├── conftest.py
│ ├── test_main.py
And have the __init__.py configure my logging as shown:
import structlog, logging, sys
from structlog.testing import LogCapture
logging.basicConfig(filename="... | [
"If you configure structlog to use LogCapture, it captures the log entries instead of printing them – that's the whole purpose of it. See also https://www.structlog.org/en/latest/testing.html\n"
] | [
1
] | [] | [] | [
"python",
"python_logging",
"structlog"
] | stackoverflow_0074373394_python_python_logging_structlog.txt |
Q:
Using OpenWeatherMap API gives 401 error
I'm trying to get the weather data for London in JSON but I am getting HTTPError: HTTP Error 401: Unauthorized. How do I get the API working?
import urllib2
url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&cnt=10&mode=json&units=metric"
response = urll... | Using OpenWeatherMap API gives 401 error | I'm trying to get the weather data for London in JSON but I am getting HTTPError: HTTP Error 401: Unauthorized. How do I get the API working?
import urllib2
url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&cnt=10&mode=json&units=metric"
response = urllib2.urlopen(url).read()
| [
"The docs open by telling you that you need to register for an API key first.\n\nTo access the API you need to sign up for an API key\n\nSince your url doesn't contain a key, the site tells you you're not authorized. Follow the instructions to get a key, then add it to the query parameters.\nhttp://api.openweather... | [
16,
7,
0,
0,
0,
0
] | [] | [] | [
"openweathermap",
"python",
"weather_api"
] | stackoverflow_0033091948_openweathermap_python_weather_api.txt |
Q:
Append data in New Column in excel using python
I have to Run this code everyday and store dataframe in new columns
How to Store the data frame to next column automatically without specifying the column number in excel file using Python Here dx stores the day of month i.e "09-11-2022" dx=9 so the data gets stored ... | Append data in New Column in excel using python | I have to Run this code everyday and store dataframe in new columns
How to Store the data frame to next column automatically without specifying the column number in excel file using Python Here dx stores the day of month i.e "09-11-2022" dx=9 so the data gets stored in column 9 but there will be gaps if i run it after ... | [
"Try this answer to get the max populated column in the excel file.\nThen use startcol = max_column + 1 to write to the next empty column\n"
] | [
0
] | [] | [] | [
"append",
"excel",
"pandas",
"python"
] | stackoverflow_0074384642_append_excel_pandas_python.txt |
Q:
I can't insert sql result from a connection to another
I retrieved sql result from a query.
coding: cp1252 -*-
import pyodbc
import mariadb
.
.
cnxn=pyodbc.connect(...
cursor=cnxn.cursor()
cursor.execute("select cli, lib from ficcli")
result=cursor.fetchmany(3)
then
cnxn2=mariadb.connect(...
.
.
mySql_insert_qu... | I can't insert sql result from a connection to another | I retrieved sql result from a query.
coding: cp1252 -*-
import pyodbc
import mariadb
.
.
cnxn=pyodbc.connect(...
cursor=cnxn.cursor()
cursor.execute("select cli, lib from ficcli")
result=cursor.fetchmany(3)
then
cnxn2=mariadb.connect(...
.
.
mySql_insert_query = "INSERT INTO sxfcli (cli,lib) values(?,?);"
cursor2=cn... | [
"execute_many() requires as second parameter a sequence of parameters which is usally an array (list) of tuples.\nContrary to what you described, the exception says that you are passing a tuple to executemany() instead of a sequence of tuples:\nFile \"<pyshell#42>\", line 1, in <module> cursor2.executemany(mySql_in... | [
0
] | [] | [] | [
"insert",
"mariadb",
"mysql",
"python",
"sql"
] | stackoverflow_0074380804_insert_mariadb_mysql_python_sql.txt |
Q:
Error installing snowflake connector for python
When I try to download snowflake connector as following https://docs.snowflake.com/en/user-guide/python-connector.html I get an error for metadata-generation-failed.
Specifically I get an error saying NotADirectoryError: [Errno 20] Not a directory: 'pkg-config'.
I've... | Error installing snowflake connector for python | When I try to download snowflake connector as following https://docs.snowflake.com/en/user-guide/python-connector.html I get an error for metadata-generation-failed.
Specifically I get an error saying NotADirectoryError: [Errno 20] Not a directory: 'pkg-config'.
I've never seen this error, nor have I found anything onl... | [
"Yes this is an issue with M1 chips on MAC.\nMore discussion here.\nCan you try installing python connector with this\npip install --no-binary snowflake-connector-python\n\nThere are other work-around mentioned in the above article, so please test those as well.\n",
"I just upgraded pip and re-tried and it worked... | [
0,
0
] | [] | [] | [
"python",
"snowflake_connector"
] | stackoverflow_0072233939_python_snowflake_connector.txt |
Q:
how to navigate a nested loop
I am new to python and I've been trying to wrap my head around this code:
stop = int(input())
result = 0
for a in range(4):
print(a, end=': ')
for b in range(2):
result += a + b
if result > stop:
print('-', end=' ')
continue
prin... | how to navigate a nested loop | I am new to python and I've been trying to wrap my head around this code:
stop = int(input())
result = 0
for a in range(4):
print(a, end=': ')
for b in range(2):
result += a + b
if result > stop:
print('-', end=' ')
continue
print(result, end=' ')
print()
Whe... | [
"Value of b will never be 2.\nEach iteration of loop will initialise the scope variables. i.e. while looping first loop, value of b will range between 0 & 1.\nWhereas, Value of result (a global variable) will be cumulative (value obtained from prev iteration).\n\n\n\n\niteration\na\nb\nresult\noutput\n\n\n\n\n1\n0\... | [
3,
0
] | [] | [] | [
"for_loop",
"nested_loops",
"python"
] | stackoverflow_0074384416_for_loop_nested_loops_python.txt |
Q:
Is there any code for showing a different modes(charging,parking,driving) of a vehicle on map?
I have a location data set for a vehicle including LONGITUDE,LATITUDE and MODE (charging,driving and parking) as follows:
longitude
latitude
mode
x
y
charging
x
y1
charging
x1
y3
parking
x2
y2
driving
x2
y
parking
... | Is there any code for showing a different modes(charging,parking,driving) of a vehicle on map? | I have a location data set for a vehicle including LONGITUDE,LATITUDE and MODE (charging,driving and parking) as follows:
longitude
latitude
mode
x
y
charging
x
y1
charging
x1
y3
parking
x2
y2
driving
x2
y
parking
x1
y4
driving
x
y1
driving
I want to plot these modes (charging,driving and parkin... | [
"Check out this code:\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\n\n\ndata = [['x', 'y', 'charging'], ['x', 'y1', 'charging'], ['x1', 'y3', 'parking'], ['x2', 'y2', 'driving'], ['x2', 'y', 'parking'], ['x1', 'y4', 'driving'], ['x', 'y1',... | [
0
] | [] | [] | [
"geospatial",
"leaflet",
"matplotlib_basemap",
"pandas",
"python"
] | stackoverflow_0074384753_geospatial_leaflet_matplotlib_basemap_pandas_python.txt |
Q:
Understanding xreadgroup command
I have written redis stream consumer in python and the minimal code looks as below:
key = 'order_completed'
group = 'inventory_group'
redis.xgroup_create(key, group) #statement1
result = redis.xreadgroup(group, key, {key: '>'}, None) #statement2
I need help to understand the la... | Understanding xreadgroup command | I have written redis stream consumer in python and the minimal code looks as below:
key = 'order_completed'
group = 'inventory_group'
redis.xgroup_create(key, group) #statement1
result = redis.xreadgroup(group, key, {key: '>'}, None) #statement2
I need help to understand the last two statements.
My limited understa... | [
"The > special stream entry ID makes XREADGROUP to return only the stream entries which were never delivered to any consumer in the group - basically, it will return new entries only.\nApart from >, the command accepts any other regular stream entry ID: in that case, XREADGROUP returns the stream entries already de... | [
1
] | [] | [] | [
"kafka_consumer_api",
"producer_consumer",
"python",
"python_3.x",
"redis"
] | stackoverflow_0074383615_kafka_consumer_api_producer_consumer_python_python_3.x_redis.txt |
Q:
Trying to render text on matplotlib plots with LaTex font and getting the error "[Errno 13] Permission denied: 'latex'"
Problem
I am trying to follow the Text rendering with LaTeX matplotlib documentation in order to have the font of my plots (including axis) in Jupyter Notebook be in LaTex. I am hoping to run thi... | Trying to render text on matplotlib plots with LaTex font and getting the error "[Errno 13] Permission denied: 'latex'" | Problem
I am trying to follow the Text rendering with LaTeX matplotlib documentation in order to have the font of my plots (including axis) in Jupyter Notebook be in LaTex. I am hoping to run this example code provided in the documentation:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['text.usetex']... | [
"I also had a similar problem before, although not specifically with latex in matplotlib. What I found was that sometimes packages get installed only for the administrator of the PC, and then permissions get denied. I found two solutions:\n\nRun your jupyter notebook via Anaconda Prompt by right clicking on the pro... | [
0
] | [] | [] | [
"jupyter_notebook",
"latex",
"matplotlib",
"python",
"visual_studio"
] | stackoverflow_0074384213_jupyter_notebook_latex_matplotlib_python_visual_studio.txt |
Q:
There are two hover message when my cursor over the python code
What I have tried:
Reboot the system. Done but nothing happens.
Uninstall the pylance and python extension. Done but nothing happens.
Install vscode insider and open the same jupyter notebook file. Done but the same issue still occurs.
Switch diff... | There are two hover message when my cursor over the python code |
What I have tried:
Reboot the system. Done but nothing happens.
Uninstall the pylance and python extension. Done but nothing happens.
Install vscode insider and open the same jupyter notebook file. Done but the same issue still occurs.
Switch different conda virtual environments. Done but the same issue still occu... | [
"UPDATE\nAdd a GitHub link: https://github.com/microsoft/vscode-jupyter/issues/11938\nUpgrading the jupyter extension to the pre-release version (2022.11.1003131031) solved the problem.\n\nIt may be an exception brought by the version update, resulting in repeated code prompts.\nRolling back the Python extension ve... | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074384520_python_visual_studio_code.txt |
Q:
local variable 'sampled_df' referenced before assignment
There is no return value because there is something wrong with the loop.
If the data type of the data frame column is categorized, I want to do stratififed sampling , and if there is no categorical type and the length of the value_counts is less than 5, I w... | local variable 'sampled_df' referenced before assignment | There is no return value because there is something wrong with the loop.
If the data type of the data frame column is categorized, I want to do stratififed sampling , and if there is no categorical type and the length of the value_counts is less than 5, I want to do stratified sampling. and if it is neither, I want to... | [
"All your iterations are continued due to\nelif len(df[col].value_counts()[df[col].value_counts() == 1]) /len(df) > 0.05:\n\nbeing True for each col. That's why sampled_df is not set at the end, and that's why you get referencing before assignment\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074384826_python.txt |
Q:
How to get attention weights from attention neural network?
I have a model that uses an attention mechanism as below:
def create_model(feature_size, max_features, num_class):
feature_input = Input((max_features,feature_size), dtype=tf.float32)
feature_vectors = TimeDistributed(Dense(feature_size, u... | How to get attention weights from attention neural network? | I have a model that uses an attention mechanism as below:
def create_model(feature_size, max_features, num_class):
feature_input = Input((max_features,feature_size), dtype=tf.float32)
feature_vectors = TimeDistributed(Dense(feature_size, use_bias=False, activation='tanh'))(feature_input)
# Atten... | [
"Create a subset of the model which just outputs the attention scores:\nattention = keras.Model(inputs=model.input, \n outputs=model.get_layer(\"softmax\").output)\n\nand run,\n attention.predict(X_test)\n\nAlso make sure the layer name is proper in model.get_layer(\"softmax'). You c... | [
2
] | [
"it is possible but you don't need to create complex classes or functions for understanding it is just the multiplication of inputs and learning weights.\n\nSample: INT is significant !!!\n\nimport os\nfrom os.path import exists\n\nimport tensorflow as tf\nimport tensorflow_text as tft\n\nimport matplotlib.pyplot a... | [
-5
] | [
"attention_model",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074384354_attention_model_keras_python_tensorflow.txt |
Q:
Pyspark, looping through DataFrame in a more efficient way?
can someone maybe tell me a better way to loop through a df in Pyspark in my specific case. I am new to spark, so sorry for the question.
What I am doing is selecting the value of the id column of the df where the song_name is null. I append these to a li... | Pyspark, looping through DataFrame in a more efficient way? | can someone maybe tell me a better way to loop through a df in Pyspark in my specific case. I am new to spark, so sorry for the question.
What I am doing is selecting the value of the id column of the df where the song_name is null. I append these to a list and get the track_ids for these values. With these track_ids I... | [
"In my opinion, you are thinking about this in kind of a standard programming way, but instead you should be thinking about how to solve this using operations that apply across the entire dataframe. For example, there is no reason to collect list, then iterate over list to make api call, etc. This all happens mostl... | [
0,
0
] | [] | [] | [
"pyspark",
"python"
] | stackoverflow_0074349761_pyspark_python.txt |
Q:
How to add an extra field in auth user model in django admin?
I want to customize my existing auth user model.
I need the command or code for executing the solution?
A:
from datetime import datetime
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
... | How to add an extra field in auth user model in django admin? | I want to customize my existing auth user model.
I need the command or code for executing the solution?
| [
"from datetime import datetime\nfrom django.contrib.auth.base_user import BaseUserManager\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.models import AbstractUser\nimport uuid\nfrom django.db import models\n\n\nclass CustomUserManager(BaseUserManager):\n \"\"\"\n Custom us... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074384626_django_django_models_python.txt |
Q:
pandas Series to Dataframe using Series indexes as columns
I have a Series, like this:
series = pd.Series({'a': 1, 'b': 2, 'c': 3})
I want to convert it to a dataframe like this:
a b c
0 1 2 3
pd.Series.to_frame() doesn't work, it got result like,
0
a 1
b 2
c 3
How can I construct a Data... | pandas Series to Dataframe using Series indexes as columns | I have a Series, like this:
series = pd.Series({'a': 1, 'b': 2, 'c': 3})
I want to convert it to a dataframe like this:
a b c
0 1 2 3
pd.Series.to_frame() doesn't work, it got result like,
0
a 1
b 2
c 3
How can I construct a DataFrame from Series, with index of Series as columns?
| [
"You can also try this :\ndf = DataFrame(series).transpose()\n\nUsing the transpose() function you can interchange the indices and the columns.\nThe output looks like this : \n a b c\n0 1 2 3\n\n",
"You don't need the transposition step, just wrap your Series inside a list and pass it to the DataFram... | [
79,
29,
8,
7,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0040224319_pandas_python.txt |
Q:
Histogram plotting in Pandas for a dataframe with single and 58000 columns
import numpy as np
import pandas as pd
from PIL import Image
hlack_img = Image.open("Henrietta_Lacks.jpg")
hlack_arr = np.array(hlack_img)
print(hlack_arr.shape) # (290,200)
features = np.reshape(hlack_img, (290*200))
hlack_df = pd.DataFra... | Histogram plotting in Pandas for a dataframe with single and 58000 columns | import numpy as np
import pandas as pd
from PIL import Image
hlack_img = Image.open("Henrietta_Lacks.jpg")
hlack_arr = np.array(hlack_img)
print(hlack_arr.shape) # (290,200)
features = np.reshape(hlack_img, (290*200))
hlack_df = pd.DataFrame(np.array([features]), index=['hlack'])
print(hlack_df)
hlack_df.hist()
I am ... | [
"For this plot alone you actually don't really need pandas.\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nhlack_img = Image.open(\"images/color_wheel.jpg\")\nhlack_arr = np.array(hlack_img)\nprint(hlack_arr.shape) # (290,200)\nplt.hist(hlack_arr.reshape(-1))\n\nreshape(-1) flatten y... | [
0
] | [] | [] | [
"histogram",
"image_processing",
"numpy",
"pandas",
"python"
] | stackoverflow_0074384886_histogram_image_processing_numpy_pandas_python.txt |
Q:
ValueError: check_hostname requires server_hostname
I was going to install pandas and epanettools on my computer using the code shown below with python 3.8.5 and I received one Error exception.
Code:
pip install epanettools
pip install pandas
Actually, I could install epanettools on my old computer and I bought a... | ValueError: check_hostname requires server_hostname | I was going to install pandas and epanettools on my computer using the code shown below with python 3.8.5 and I received one Error exception.
Code:
pip install epanettools
pip install pandas
Actually, I could install epanettools on my old computer and I bought a new computer and I wanted to do the same thing on my new... | [
"Are you using proxy software, like V2ray, SSR...?\nIf so, close the software, and try again.\n",
"On Linux, the problem can be resolved by replacing https with http in the proxy settings environment variable export https_proxy=http://123.123.123.123:8888. Note, it is proxy settings for https, but an http address... | [
39,
9,
5,
0,
0,
0,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0067297278_pip_python.txt |
Q:
ImportError: cannot import name 'soft_unicode' from 'markupsafe'
I am trying to build a docker container with Airflow and Postgres nevertheless getting many errors during build as shown below. I've tried to downgrade markupsafe in my requirements.txt as shown below, but it didn't help. What can I do to solve the i... | ImportError: cannot import name 'soft_unicode' from 'markupsafe' | I am trying to build a docker container with Airflow and Postgres nevertheless getting many errors during build as shown below. I've tried to downgrade markupsafe in my requirements.txt as shown below, but it didn't help. What can I do to solve the issue?
# I tried this version:
markupsafe==2.1.1
# and then also this o... | [
"Downgrade markupsafe to 2.0.1\npip install markupsafe==2.0.1\n",
"It turns out markupsafe removed `soft_unicode' which is causing this error! https://github.com/pallets/markupsafe/issues/304\nAdd MarkupSafe==2.0.1 to your PYTHON_DEPS like so:\n webserver:\n image: puckel/docker-airflow:1.10.4\n build:\n ... | [
85,
18,
5,
4,
2,
1,
0,
0,
0
] | [] | [] | [
"dependencies",
"docker",
"docker_compose",
"importerror",
"python"
] | stackoverflow_0072191560_dependencies_docker_docker_compose_importerror_python.txt |
Q:
How to split my data into train, validation and test datasets?
I'm using a flowers dataset which has this structure:
I have already split this data into training and validation sets and my network is running based on these 2 sets. I split the data into a 80:20 split, 80 for training and 20 for validation. I want ... | How to split my data into train, validation and test datasets? | I'm using a flowers dataset which has this structure:
I have already split this data into training and validation sets and my network is running based on these 2 sets. I split the data into a 80:20 split, 80 for training and 20 for validation. I want to have a data split so it is 80 training, 10 validation and 10 test... | [
"You can use the tf.keras.utils.split_dataset API available in Tensorflow 2.10 to split the dataset to train and test sets like below\ntrain_ds,test_ds=tf.keras.utils.split_dataset(\n train_ds, left_size=None, right_size=.2,\n)\n\nKindly refer to this gist for working code. Thank you!\n"
] | [
0
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074257284_conv_neural_network_deep_learning_keras_python_tensorflow.txt |
Q:
Indexing flaw, changing color of Vertices
Keep making same mistake.
Horizontal lines is always result. Trying to display random points.
import cv2 as cv, numpy as np, random
blank = np.ones((300,300), np.uint8) * 255
X, Y = [], []
for i in np.arange(1,300,1):
X.append(random.randrange(1,300))
for i in np.ar... | Indexing flaw, changing color of Vertices | Keep making same mistake.
Horizontal lines is always result. Trying to display random points.
import cv2 as cv, numpy as np, random
blank = np.ones((300,300), np.uint8) * 255
X, Y = [], []
for i in np.arange(1,300,1):
X.append(random.randrange(1,300))
for i in np.arange(1,300,1):
Y.append(random.randrange(1,... | [
"Everything is okay in your code, just require some change which is that we have to pass X, Y instead of XY.\nblank[X, Y] = 1\n\nSo basically index operater [] requires a tuple so we can create our own using XY.\n# tuple(XY.transpose())\nblank[tuple(XY.transpose())] = 1\n\n\nimport cv2 as cv, numpy as np, random\nb... | [
2
] | [] | [] | [
"numpy",
"opencv",
"python"
] | stackoverflow_0074384948_numpy_opencv_python.txt |
Q:
How do I change this for loop into a function?
I am trying to find the largest and then second- largest number in a list, then calculate the sum and difference of the two, then print the two solutions in a list.
numbers = [1,2,3,4,5]
largest_integer = -1e10
second_largest_integer = -1e11
for item in numbers:
... | How do I change this for loop into a function? | I am trying to find the largest and then second- largest number in a list, then calculate the sum and difference of the two, then print the two solutions in a list.
numbers = [1,2,3,4,5]
largest_integer = -1e10
second_largest_integer = -1e11
for item in numbers:
if item > largest_integer:
second_largest_i... | [
"This function will take 1 argument, which is list of numbers.\ndef get_first_and_second_largest(numbers):\n\n largest_integer = -1e10\n second_largest_integer = -1e11\n\n for item in numbers:\n if item > largest_integer:\n second_largest_integer = largest_integer\n largest_int... | [
1
] | [] | [] | [
"for_loop",
"function",
"python"
] | stackoverflow_0074385056_for_loop_function_python.txt |
Q:
Python Pandas Dataframe: conditional counters of one and zeros values
I want to add two columns in my dataframe with the following function using python:
"counter1": it counts the number of the ones in the column "case1-0". (cumulative sum of the ones)
"counter2": it counts the number of the zeros in the column "... | Python Pandas Dataframe: conditional counters of one and zeros values | I want to add two columns in my dataframe with the following function using python:
"counter1": it counts the number of the ones in the column "case1-0". (cumulative sum of the ones)
"counter2": it counts the number of the zeros in the column "case1-0" but only if the last previous value in "counter1" is greater than ... | [
"Use this solution with a mask for compare by 1 for counter11 and for counter22 is replaced not 1 values of column counter11 to missing values and forward filling them, so possible compare for greater values like 3 and pass to numpy.where values of s helper Series:\na = df['case1-0'].eq(1)\nb = a.cumsum()\ndf['coun... | [
1
] | [] | [] | [
"conditional_statements",
"counter",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074385195_conditional_statements_counter_dataframe_pandas_python.txt |
Q:
Regex for opening and closing tag String
I have a file from which I want to grab all the StringABCD between "estimate" opening and closing tag eg.
<estimate>StringABCD</estimate>
('GTIServiceResult', '<report>\n <estimate>StringABCD</estimate>\n</report>"}}}}
Can someone please give me a REGEX code for this
| Regex for opening and closing tag String | I have a file from which I want to grab all the StringABCD between "estimate" opening and closing tag eg.
<estimate>StringABCD</estimate>
('GTIServiceResult', '<report>\n <estimate>StringABCD</estimate>\n</report>"}}}}
Can someone please give me a REGEX code for this
| [] | [] | [
"You can try this:\n(?<=<estimate>).*(?=<\\/estimate>)\n"
] | [
-1
] | [
"python",
"xml"
] | stackoverflow_0074385118_python_xml.txt |
Q:
Serverless With Scrapy [ERROR] Runtime.ImportModuleError:
I am trying to use aws lambda feature for deploying my serverless project as I wanted the scrapy cronjob to run every minute but I encountered following error.
ERROR] Runtime.ImportModuleError: Unable to import module 'liveshare/spiders/livemarket': /lib64/... | Serverless With Scrapy [ERROR] Runtime.ImportModuleError: | I am trying to use aws lambda feature for deploying my serverless project as I wanted the scrapy cronjob to run every minute but I encountered following error.
ERROR] Runtime.ImportModuleError: Unable to import module 'liveshare/spiders/livemarket': /lib64/libc.so.6: version `GLIBC_2.25' not found (required by /var/tas... | [
"The issue is due to the wrong download of cryptography manylinux package. Try to change python runtime in lambda to python3.8 or python3.9.\nIf the issue still persists you can use older versions of cryptography.\n"
] | [
0
] | [] | [] | [
"amazon_web_services",
"python",
"scrapy",
"serverless",
"web_scraping"
] | stackoverflow_0074385144_amazon_web_services_python_scrapy_serverless_web_scraping.txt |
Q:
Scrapy - Get 2 values split between span tag
I'm using Scrapy to scrapy a table on a page:
import scrapy
from ..items import TestItem
from scrapy.loader import ItemLoader
class TestSpider(scrapy.Spider):
name = 'test'
def parse(self, response):
items = response.xpath('//*[@id="12"]/div/div/div[2]... | Scrapy - Get 2 values split between span tag | I'm using Scrapy to scrapy a table on a page:
import scrapy
from ..items import TestItem
from scrapy.loader import ItemLoader
class TestSpider(scrapy.Spider):
name = 'test'
def parse(self, response):
items = response.xpath('//*[@id="12"]/div/div/div[2]/table/tbody/tr')
for l in items:
... | [
"Try\nitems = response.xpath('//*[@id=\"12\"]/div/div/div[2]/table/tbody/tr')\nfor l in items:\n tf = l.xpath('./td[@class=\"test2\"]//text()').getall()\n il = ItemLoader(item=TestItem(), selector=l)\n # From should be text before <span></span> and To should be after\n il.add_value('from', tf[0])\n i... | [
1
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0074383003_python_scrapy.txt |
Q:
How to split data into two graphs with mat plot lib
I would be so thankful if someone would be able to help me with this. I am creating a graph in matplotib however I would to love to split up the 14 lines created from the while loop into the x and y values of P, so instead of plt.plot(t,P) it would be plt.plot(t,... | How to split data into two graphs with mat plot lib | I would be so thankful if someone would be able to help me with this. I am creating a graph in matplotib however I would to love to split up the 14 lines created from the while loop into the x and y values of P, so instead of plt.plot(t,P) it would be plt.plot(t,((P[1])[0]))) and
plt.plot(t,((P[1])[1]))). I would lov... | [
"You can use subplots() to create two subplots and then plot the individual line into the plot you need. To do this, firstly add the subplots at the start (before the while loop) by adding this line...\nfig, ax = plt.subplots(2,1) ## Plot will 2 rows, 1 column... change if required\n\nThen... within the while loop,... | [
0
] | [] | [] | [
"arrays",
"graph",
"matplotlib",
"ode",
"python"
] | stackoverflow_0074378950_arrays_graph_matplotlib_ode_python.txt |
Q:
How to split a string separating multiple names with a separator python
How to split columns song feat artist and join to title song
column name Artist, Title, Artist_followers
Ed Sheeran - Cardi B - Camila Cabello - Cheat south of the 71783101
Ed Sheeran - Chris Stapleton - Bruno Mars blow 71783... | How to split a string separating multiple names with a separator python |
How to split columns song feat artist and join to title song
column name Artist, Title, Artist_followers
Ed Sheeran - Cardi B - Camila Cabello - Cheat south of the 71783101
Ed Sheeran - Chris Stapleton - Bruno Mars blow 71783101
output
Ed Sheeran What do i do feat Cardi B & Camila Cabello & Cheat 71... | [
"df['artist'] = df['artist'].str.split('-')\ndf = df.explode('artist').reset_index(drop=True)\n\nThen You can just use the +.\ndf['artist'] + '_' + df['title']\n\nI don't know the exact names for the columns since there are no present in the question\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"split",
"string",
"title"
] | stackoverflow_0074385383_pandas_python_split_string_title.txt |
Q:
calculating expanding mean in pandas with date multiindex
I have a dataframe with a multi-index the first level is a stock ticker the second is a date such as this:
import pandas as pd
import numpy as np
arrays = [
np.array(["MSFT", "MSFT", "MSFT", "MSFT", "GOOG", "GOOG", "GOOG", "GOOG"]),
np.array([pd.to... | calculating expanding mean in pandas with date multiindex | I have a dataframe with a multi-index the first level is a stock ticker the second is a date such as this:
import pandas as pd
import numpy as np
arrays = [
np.array(["MSFT", "MSFT", "MSFT", "MSFT", "GOOG", "GOOG", "GOOG", "GOOG"]),
np.array([pd.to_datetime("2022-04-05"), pd.to_datetime("2022-04-06"), pd.to_da... | [
"Use GroupBy.transform with lambda function with Expanding.mean and Series.shift:\nfor ticker in df.reset_index()['Ticker'].unique(): \n for date in df.loc[ticker].index:\n filtered_df = df.loc[ticker].loc[(df.loc[ticker].index < date)]\n print (filtered_df)\n mean = np.mean(np.asarray(filtere... | [
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python",
"time_series"
] | stackoverflow_0074385365_dataframe_numpy_pandas_python_time_series.txt |
Q:
Python client for elasticsearch 8.5
I used to connect elasticsearch 7 self managed cluster using following code.
from elasticsearch import Elasticsearch,RequestsHttpConnection
es = Elasticsearch(['hostname'], timeout=1000,http_auth=('user_name', 'password'),use_ssl=True,verify_certs=True,connection_class=Requests... | Python client for elasticsearch 8.5 | I used to connect elasticsearch 7 self managed cluster using following code.
from elasticsearch import Elasticsearch,RequestsHttpConnection
es = Elasticsearch(['hostname'], timeout=1000,http_auth=('user_name', 'password'),use_ssl=True,verify_certs=True,connection_class=RequestsHttpConnection,scheme="https",port=9200)
... | [
"In Elasticsearch 8.X, there have been significant changes in the Elasticsearch API.\nNow, in the Elasticsearch 8.X, the scheme and port need to be included explicitly as part of the hostname, scheme://hostname:port e.g.(https://localhost:9200)\nThe http_auth should be updated to basic_auth instead. You can have a ... | [
1
] | [] | [] | [
"authentication",
"deprecated",
"elasticsearch",
"permissions",
"python"
] | stackoverflow_0074384522_authentication_deprecated_elasticsearch_permissions_python.txt |
Q:
Extend a class in Python which is later created
I know that it usually recommended to extend classes like this example where the Volvo class is extends the class Car:
import Car
class Volvo(Car):
do stuff...
In my situation I would like to define the class Volvo before I create the instance of Car. So I would... | Extend a class in Python which is later created | I know that it usually recommended to extend classes like this example where the Volvo class is extends the class Car:
import Car
class Volvo(Car):
do stuff...
In my situation I would like to define the class Volvo before I create the instance of Car. So I would like to do something like this:
class Car:
def _... | [
"do you need something like this?\nclass Car:\n def __init__(self, speed_limit):\n self.speed_limit = speed_limit\n \n def print_current_speed_limit(self):\n print(self.speed_limit)\n\nclass Volvo(Car):\n def __init__(self, c, modified_speed_limit):\n super(Volvo, self).__init__((c.... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074385413_python.txt |
Q:
n_jobs got an unexpected keyword argument
I have a parameter in k-Means clustering. how do i resolve this error to solve the problem in clustering? I tried all methods but cant find the solution.
A:
There is no argument such as njobs in Kmeans.
If you want to decrease processing time, try
initialization of clus... | n_jobs got an unexpected keyword argument | I have a parameter in k-Means clustering. how do i resolve this error to solve the problem in clustering? I tried all methods but cant find the solution.
| [
"There is no argument such as njobs in Kmeans.\nIf you want to decrease processing time, try\n\ninitialization of clusters . USE INIT as kmeans++\nreduce threshold for convergence in tol\n\nRead more about sklearn kmeans https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html\n"
] | [
0
] | [] | [] | [
"cluster_analysis",
"clustering_key",
"image",
"k_means",
"python"
] | stackoverflow_0074359326_cluster_analysis_clustering_key_image_k_means_python.txt |
Q:
How do I scrape Google Search results (on a big scale kinda)?
From what I've heard, google doesn't like being crawled/scraped. Found a similar question month ago on stackoverflow when I was about to start this project (Can't find it now.). Someone said that using proxy is a way to go, so I got proxymesh. And I'm g... | How do I scrape Google Search results (on a big scale kinda)? | From what I've heard, google doesn't like being crawled/scraped. Found a similar question month ago on stackoverflow when I was about to start this project (Can't find it now.). Someone said that using proxy is a way to go, so I got proxymesh. And I'm guessing that I need to send requests at a "random rate" to have hum... | [
"Try using Node.js with puppeteer and running this code as a starting point. It will get you the links for a given google search. Using different IP addresses is good, but also try turning off your location services, clearing your cache constantly, and clearing anything else google might use to uniquely identify yo... | [
0,
0
] | [] | [] | [
"google_search",
"python",
"web_crawler",
"web_scraping"
] | stackoverflow_0067179806_google_search_python_web_crawler_web_scraping.txt |
Q:
Python argparse print version and exit
Here is my code.
import argparse
parser = argparse.ArgumentParser(prog="prog")
parser.add_argument("-v", "--version", action="store_true")
parser.add_argument("filename")
args = parser.parse_args()
if args.version:
print_version_and_exit()
If I run prog --version it sh... | Python argparse print version and exit | Here is my code.
import argparse
parser = argparse.ArgumentParser(prog="prog")
parser.add_argument("-v", "--version", action="store_true")
parser.add_argument("filename")
args = parser.parse_args()
if args.version:
print_version_and_exit()
If I run prog --version it should print the version and exit, But current... | [
"Answering my own question based on @hpaulj's comment.\nimport argparse\n\nparser = argparse.ArgumentParser(prog=\"prog\")\n\nparser.add_argument(\"-v\", \"--version\", action=\"version\", version=\"v0.1.0\")\nparser.add_argument(\"filename\")\n\nargs = parser.parse_args()\n\nAdding version action would do the tric... | [
0
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0074385341_argparse_python.txt |
Q:
Can i append a value to my flask request object in the @app.before_request and pass it forward to the endpoint view function?
I am developing some basic REST APIs in python. I am expecting an authorization token in the header of all requests except some unsecured requests like login and register. I am validating t... | Can i append a value to my flask request object in the @app.before_request and pass it forward to the endpoint view function? | I am developing some basic REST APIs in python. I am expecting an authorization token in the header of all requests except some unsecured requests like login and register. I am validating the token in @app.before_request and then I want to pass the decoded payload to the corresponding endpoint view function. But, I am ... | [
"I have a similar usecase (surprisingly similar, actually). I got around it by setting a custom property in the request object, much like your approach, although instead of using direct assignment (i.e. request[\"token\"]=token), I used setattr(request, \"token\", token).\nI got the tip from a bottle plugin which d... | [
2,
0
] | [] | [] | [
"flask",
"python",
"rest"
] | stackoverflow_0053108394_flask_python_rest.txt |
Q:
How can i convert this log data into JSON using a python script
I have log file from a Vivado simulator, which i want to convert into simple JSON to visualize it ultimately.
Please suggest me a python code to format the logs into JSON.
I have tried to search for converting the logs into JSON, but most of them conv... | How can i convert this log data into JSON using a python script | I have log file from a Vivado simulator, which i want to convert into simple JSON to visualize it ultimately.
Please suggest me a python code to format the logs into JSON.
I have tried to search for converting the logs into JSON, but most of them convert .csv (comma separated values) into JSON, while my log file contai... | [
"You can do something like this:\nfileDesc = open('YourFileName', 'r')\nfileData = fileDesc.read()\nfileDesc.close()\n\nlog = []\n\nfor line in fileData.splitlines():\n words = [word.strip() for word in line.split(':')]\n log.append({\n 'Error': words[0],\n 'Assertion': words[1],\n 'Messa... | [
0,
0,
0
] | [] | [] | [
"formatting",
"json",
"python"
] | stackoverflow_0074385156_formatting_json_python.txt |
Q:
Extracting only a number and letter F from the column of a pandas dataframe
I have some data as below,
AST_NAME
2F
3F
4F
5F
2-F-C
3-F-A
4-F-C
4-F-D
5-F-E
5-F-F
SwB
6-F-G
SwB
7-F-A
I want to extract the number and letter F only from those values like 2-F-C or 3-F-D.
My desired output is as below.
A... | Extracting only a number and letter F from the column of a pandas dataframe | I have some data as below,
AST_NAME
2F
3F
4F
5F
2-F-C
3-F-A
4-F-C
4-F-D
5-F-E
5-F-F
SwB
6-F-G
SwB
7-F-A
I want to extract the number and letter F only from those values like 2-F-C or 3-F-D.
My desired output is as below.
AST_NAME
2F
3F
4F
5F
2F
3F
4F
4F
5F
... | [
"You can use a regex and str.replace:\ndf['AST_NAME_clean'] = df['AST_NAME'].str.replace(r'^(\\d+)-?(F).*',\n r'\\1\\2', regex=True)\n\nOutput:\n AST_NAME AST_NAME_clean\n0 2F 2F\n1 3F 3F\n2 4F 4F\n3 5... | [
2,
1
] | [] | [] | [
"extract",
"pandas",
"python",
"strip"
] | stackoverflow_0074385336_extract_pandas_python_strip.txt |
Q:
SQL Alchemy How to query Join and Sum Distinct
How do I query join two tables and sum distinct values in a column?
Given Parent:
Given Child:
Expected Result:
from app import db_con
from sqlalchemy import ForeignKey
from sqlalchemy.dialects import mssql
class Parent(db_con.Model):
__tablename__ = "parent"
... | SQL Alchemy How to query Join and Sum Distinct | How do I query join two tables and sum distinct values in a column?
Given Parent:
Given Child:
Expected Result:
from app import db_con
from sqlalchemy import ForeignKey
from sqlalchemy.dialects import mssql
class Parent(db_con.Model):
__tablename__ = "parent"
ID = db_con.Column(
"id", mssql.INTEGER,... | [
"#...\nfrom sqlalchemy.sql import func\n\nclass CategoryCost(Base):\n __tablename__ = \"category_costs\"\n id = Column(\n Integer, nullable=False, primary_key=True\n )\n cost = Column(Numeric)\n category_id = Column(Integer, ForeignKey(\"categories.id\"))\n category = relationship(\"Categor... | [
0,
0
] | [] | [] | [
"flask",
"python",
"sqlalchemy"
] | stackoverflow_0074368267_flask_python_sqlalchemy.txt |
Q:
Pandas: Identify Date ranges that contain date 'x' in list
The code maybe explains the question better, but I have a list of date ranges (month start, month end for example) in a dataframe, and then a list of birthdays.
I'm simply trying to create a dataframe column that contains the birthdate days (or a list of t... | Pandas: Identify Date ranges that contain date 'x' in list | The code maybe explains the question better, but I have a list of date ranges (month start, month end for example) in a dataframe, and then a list of birthdays.
I'm simply trying to create a dataframe column that contains the birthdate days (or a list of them) if its in between a StartDate and EndDate.
Sample code:
imp... | [
"You can use a merge_asof:\ndf['Solution'] = (df['StartDate'].map(\n pd.merge_asof(pd.to_datetime(pd.Series(birthdays, name='Solution')),\n df,\n left_on='Solution', right_on='StartDate'\n )\n .groupby('StartDate')['Solution'].agg(list)\n))\n\noutput:\n StartDate En... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074380744_pandas_python.txt |
Q:
When I attempt to execute my recursive function with odd numbers ,i have a kern problem
There is a problem with odd numbers.
When I run the function on even numbers, the code works.
#recursive demo function1
#Even nums
def evenNum(num):
if num % 2 != 0:
print("enter a even number")
... | When I attempt to execute my recursive function with odd numbers ,i have a kern problem | There is a problem with odd numbers.
When I run the function on even numbers, the code works.
#recursive demo function1
#Even nums
def evenNum(num):
if num % 2 != 0:
print("enter a even number")
if num == 2:
return num
else:
return evenNum(num-2) ... | [
"The second if should be changed to elif. When number is odd it prints \"Enter a even number\" and then compares it to 2. As it is different, it calls the function again.\nHere is fixed code\n def evenNum(num):\n if num % 2 != 0:\n print(\"enter a even number\")\n elif num == 2:\n ... | [
3,
0
] | [] | [] | [
"function",
"python",
"recursion"
] | stackoverflow_0074375182_function_python_recursion.txt |
Q:
raise KeyError(key) in pandas while using apply function and trying get 2 input
I want in .apply function get 2 entities and check it but I got pandas.errors.IndexingError: Too many indexers error.
import pandas as pd
dict2 = {
"name": ["kambiz", "ali", "mmd", "sara"],
"age": [19, 19, 14, 12],
}
df = pd.... | raise KeyError(key) in pandas while using apply function and trying get 2 input | I want in .apply function get 2 entities and check it but I got pandas.errors.IndexingError: Too many indexers error.
import pandas as pd
dict2 = {
"name": ["kambiz", "ali", "mmd", "sara"],
"age": [19, 19, 14, 12],
}
df = pd.DataFrame(dict2)
def show_if(age, name):
if age == 19:
if name == "kamb... | [
"Don't use apply but rather a vectorial approach:\nimport numpy as np\n\ndf[\"19 ages\"] = np.where(df['age'].eq(19),\n '19 in this group is '+df['name'],\n 'not available')\n\nOutput:\n name age 19 ages\n0 kambiz 19 19 in this group is ka... | [
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074385613_dataframe_numpy_pandas_python_python_3.x.txt |
Q:
Problem simultaneously indexing several dimensions of a multidimensional numpy array
Consider a 4-dimensional numpy array (variable a). We have a.shape = (16, 5, 66, 717).
From the second dimension containing 4 elements, I want to select the second and the fifth:
b = a[:, [1,4],:,:]
b.shape returns (16, 2, 66, 71... | Problem simultaneously indexing several dimensions of a multidimensional numpy array | Consider a 4-dimensional numpy array (variable a). We have a.shape = (16, 5, 66, 717).
From the second dimension containing 4 elements, I want to select the second and the fifth:
b = a[:, [1,4],:,:]
b.shape returns (16, 2, 66, 717), so I guess what I did is correct. Now I want to extract 4 elements from the first dime... | [
"Make a smaller 3d array:\nIn [155]: a = np.arange(24).reshape(2,3,4)\nIn [158]: a\nOut[158]: \narray([[[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]],\n\n [[12, 13, 14, 15],\n [16, 17, 18, 19],\n [20, 21, 22, 23]]])\n\nSelecting two \"rows\" (on the middle dimension):\n... | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074376729_arrays_numpy_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.