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 use inline if statement
am fairly new to programming and i don't get how the inline if statement works.
i wanna do something like this:
tries = 0
Numbers = "Hello world"
for x in Numbers: (print(( f"found{x}" if x == "o" else None)), tries += 1 if x != "o" else 0)
so if it does find x which is "o" it print... | How to use inline if statement | am fairly new to programming and i don't get how the inline if statement works.
i wanna do something like this:
tries = 0
Numbers = "Hello world"
for x in Numbers: (print(( f"found{x}" if x == "o" else None)), tries += 1 if x != "o" else 0)
so if it does find x which is "o" it prints it else it adds 1 to tries, i trie... | [
"As others have already commented, this is not a good idea.\nIt's hard to read and doesn't make anything better.\n\nJust to provide an actual answer to your question:\ntries = 0\nNumbers = \"Hello world\"\nfor x in Numbers: tries += 0 if x == \"o\" and not print(f\"found{x}\") else 1\n\nWhen x is \"o\", then the se... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074574312_python.txt |
Q:
How to configure line length for VS Code python Sort Imports in user settings?
I'm using the Sort Imports function of the Python extension for VS Code. I'd like to configure the line length for this to 100; however, I've been unable to properly set this in my settings.json file. From the documentation, it seems li... | How to configure line length for VS Code python Sort Imports in user settings? | I'm using the Sort Imports function of the Python extension for VS Code. I'd like to configure the line length for this to 100; however, I've been unable to properly set this in my settings.json file. From the documentation, it seems like "python.sortImports.args": ["-l", "100"] should work, but it's giving me an error... | [
"There is a known bug with using Sort Imports on __init__.py files. Here is the full solution to put in vscode's .vscode/settings.json:\n\"python.sortImports.args\": [\"-ns\", \"__init__.py\", \"-l\", \"100\"],\n\n",
"Nowdays, it's adding:\n \"isort.args\": [\"-l\", \"100\"],\n\nto your settings file.\n"
] | [
6,
0
] | [] | [] | [
"python",
"visual_studio_code",
"vscode_settings"
] | stackoverflow_0052046251_python_visual_studio_code_vscode_settings.txt |
Q:
Doesn't remove duplicate strings in the list in one instance
How do I make a for loop in elif choice == 2?
let's say I have the list ["egg, "eGG", "radish", "pork", "meat"] from user input, if the user decides to remove egg, both egg and eGG should be removed.
Here's my code:
print(" MY GROCERY LIST ")
#functio... | Doesn't remove duplicate strings in the list in one instance | How do I make a for loop in elif choice == 2?
let's say I have the list ["egg, "eGG", "radish", "pork", "meat"] from user input, if the user decides to remove egg, both egg and eGG should be removed.
Here's my code:
print(" MY GROCERY LIST ")
#function that adds items, removes items, prints the list of items, exits ... | [
"You can use a while loop to loop over all the items in the array, and then use call the lower() function on each element in the array list. This will make all the characters in an element lowercase and then you can compare. You would also have to lowercase the user input to compare correctly.\nelif choice == \"2\"... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074574364_python.txt |
Q:
How can you download all non-obvious images with Beautifulsoup/Selenium?
I'm making next little project to learn - it's what I'm trying to do past few days, without success. I want to make list of opals, their prices...and download their images from website. At end (probably) here are two ways: assign opals to ima... | How can you download all non-obvious images with Beautifulsoup/Selenium? | I'm making next little project to learn - it's what I'm trying to do past few days, without success. I want to make list of opals, their prices...and download their images from website. At end (probably) here are two ways: assign opals to images (in word or excel) or just save images with name of opal+price. I succeed ... | [
"you can use the API and all downloaded images ll be next to the executable file:\nimport requests\n\n\ndef get_info(page: int):\n url = f\"https://www.koroit-opal-company.com/api/v2/products?sort=position-asc&resultsPerPage=12&page={page}&categoryId=551DDBD9-8AD4-229C-164A-C0A82AB9D825&locale=en_GB&shop=8030002... | [
2
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074574105_beautifulsoup_html_python_selenium_web_scraping.txt |
Q:
how do I make the independent variables columns and targets into variables X and y
how do I make the independent variables columns and targets into variables X and y
#independent columns --> SepalLengthCm, SepalWidthCm, PetalLengthCm, PetalWidthCm
X = df1.<...>
#target columns --> species
y = df1.<...>
A:
you c... | how do I make the independent variables columns and targets into variables X and y | how do I make the independent variables columns and targets into variables X and y
#independent columns --> SepalLengthCm, SepalWidthCm, PetalLengthCm, PetalWidthCm
X = df1.<...>
#target columns --> species
y = df1.<...>
| [
"you can do the following.\nx = df.iloc[:, [0, 1, 2, 3]].values\n\nHere you use iloc Docs, so you take all elements (:) from columns with index [0,1,2,3] then you take the values because iloc returns pandas object.\nFor target, you can do the following.\ny = df.iloc[:, [4]].values\n\nThis dataset is really popular,... | [
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074574291_jupyter_notebook_python.txt |
Q:
OSError: port/proto not found in for loop
I wrote a python script using the socket module, which provides getservbyport for retrieving a service name based on a port number argument.
I used the following code:
import socket
socket.getservbyport(443) # 'https'
But with certain port numbers i'm getting the followi... | OSError: port/proto not found in for loop | I wrote a python script using the socket module, which provides getservbyport for retrieving a service name based on a port number argument.
I used the following code:
import socket
socket.getservbyport(443) # 'https'
But with certain port numbers i'm getting the following error:
socket.getservbyport(675)
Traceback (... | [
"The error OSError: port/proto not found is thrown when no service is found on that port. So if you're iterating through all possible ports, odds are you will almost certainly get that error. Catching the error is the right way to go.\nTo achieve what you need, use a separate counter to keep track of the number of ... | [
3,
0
] | [] | [] | [
"for_loop",
"network_programming",
"python",
"sockets"
] | stackoverflow_0037644773_for_loop_network_programming_python_sockets.txt |
Q:
Keras model predict iteration getting slower.
Hi I have some problem about Keras with python 3.6
My enviroment is keras with Python and Only CPU.
but the problem is when I iterate same Keras model for predict some diferrent input, its getting slower and slower..
my code is so simple just like that
for i in rang... | Keras model predict iteration getting slower. | Hi I have some problem about Keras with python 3.6
My enviroment is keras with Python and Only CPU.
but the problem is when I iterate same Keras model for predict some diferrent input, its getting slower and slower..
my code is so simple just like that
for i in range(100):
model.predict(x)
the First run is fast.... | [
"Try using the __call__ method directly. The documentation of the predict method states the following:\n\nFor small numbers of inputs that fit in one batch, directly use __call__() for faster execution, e.g., model(x).\n\nI see the performance is critical in this case. So, if it doesn't help, you could use OpenVINO... | [
0
] | [
"If your model calls the fit function in batches, there are different samples in the same batch with slightly different times over the course of the iteration, and then you try again and again to get more and more groups of predictive model performance time will be longer and longer.\n"
] | [
-1
] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0049777263_keras_python_tensorflow.txt |
Q:
Using pytest with a dockerized Postgres database
I'm currently creating a separate database for the sake of my tests. Is there any better solution to run the test suite when the database is running in Docker and I don't want my tests to mess up my production database?
A:
You are already using a dockerized databa... | Using pytest with a dockerized Postgres database | I'm currently creating a separate database for the sake of my tests. Is there any better solution to run the test suite when the database is running in Docker and I don't want my tests to mess up my production database?
| [
"You are already using a dockerized database as your \"production database\". You could add a second dockerized database as a \"develop database\". This second instance should replicate the production database, and be spun up / torn down as part of the test suite.\nAdvantages of using dockerized database instances ... | [
1
] | [] | [] | [
"docker",
"postgresql",
"pytest",
"python",
"testing"
] | stackoverflow_0074361237_docker_postgresql_pytest_python_testing.txt |
Q:
How can I perform multiple random.choices tests
I have a list called marbles of 10.000 items (5000 blue and 5000 red)
I want to do a test. To pick 4 random items from the list I do this
import random
marbles = ["RED" for _ in range(5000)] + ["BLUE" for _ in range(5000)]
A = random.choices(marbles, k=4)
print(A) ... | How can I perform multiple random.choices tests | I have a list called marbles of 10.000 items (5000 blue and 5000 red)
I want to do a test. To pick 4 random items from the list I do this
import random
marbles = ["RED" for _ in range(5000)] + ["BLUE" for _ in range(5000)]
A = random.choices(marbles, k=4)
print(A) # this will print a list of 4 random Items from the l... | [
"Use a for loop.\nfor x in range(4):\n print(random.choice(marbles))\n\n",
"Sampling with and without replacement\nIt's important to understand the difference between sampling with replacement and without replacement. Say we have a bag of 1 blue and 2 red marbles, and you select 2 marbles. If you put the marbl... | [
0,
0
] | [] | [] | [
"loops",
"python",
"random"
] | stackoverflow_0074574168_loops_python_random.txt |
Q:
How to scale data with a center that doesn't change with scikit-learn and python
I am attempting to scale a dateset to train a machine learning model on using python and scikit-learn. I want to scale a dataset but maintain that all the raw values that are negative remain negative post scaling and all the raw valu... | How to scale data with a center that doesn't change with scikit-learn and python | I am attempting to scale a dateset to train a machine learning model on using python and scikit-learn. I want to scale a dataset but maintain that all the raw values that are negative remain negative post scaling and all the raw values that are positive remain positive after scaling.
Something like this pseudo code fo... | [
"\nFirstly, if you want an array of 1 feature, 4 values you need to reshape your array.\n\nimport numpy as np\nprint('This is an array of 1-value for 4-features', np.array([[-5.0, 0.0, 1.25, 2.5]]).shape)\nprint('This is an array of 4-values for 1-feature', np.array([-5.0, 0.0, 1.25, 2.5]).shape)\n#[output] This is... | [
1
] | [] | [] | [
"data_preprocessing",
"machine_learning",
"normalization",
"python",
"scikit_learn"
] | stackoverflow_0074574548_data_preprocessing_machine_learning_normalization_python_scikit_learn.txt |
Q:
Replace value text in Tkinter Treeview
Is there way to replace the value that is displayed (in this case a very long hyperlink) in a Tkinter treeview column with something shorter (but it still open the hyperlink)? The example I have is similar to the screenshot below, except the Google link is actually a very lon... | Replace value text in Tkinter Treeview | Is there way to replace the value that is displayed (in this case a very long hyperlink) in a Tkinter treeview column with something shorter (but it still open the hyperlink)? The example I have is similar to the screenshot below, except the Google link is actually a very long OneNote link. I would like to be able to r... | [
"You can store the links in a dictionary, with the key being whatever you want to display to the user. Then it’s just a matter of looking up the link when the user clicks.\nAnother alternative is to put the actual link in a hidden column.\n"
] | [
1
] | [] | [] | [
"hyperlink",
"python",
"tkinter",
"treeview"
] | stackoverflow_0074573939_hyperlink_python_tkinter_treeview.txt |
Q:
What Python Libraries I can use to produce such markers on a map. The marker should also have a popup functionality
I tried to inspect element the website I got this image from but did not quite find anything useful. Here is the link
| What Python Libraries I can use to produce such markers on a map. The marker should also have a popup functionality |
I tried to inspect element the website I got this image from but did not quite find anything useful. Here is the link
| [] | [] | [
"Hi Hope you are doing well!\nI can highly recommend plotly for this task, I was using it in my previous to create a dashboard with a map and different labels/markers etc. It has a lot of benefits (e.g., different kinds of map styles) and really easy to use!\n\nExample of the plotly usage for maps visualization: h... | [
-1
] | [
"maps",
"python",
"visualization"
] | stackoverflow_0074568686_maps_python_visualization.txt |
Q:
Tkinter treeview selection of mutiple rows and retrieve the selected rows
I am using the sample Treeview widget for the user to select the multiple rows. I used the tree.selection method for this in the code.
However, I am unable to figure out a better approach to retrieve the selected rows in an appropriate way. ... | Tkinter treeview selection of mutiple rows and retrieve the selected rows | I am using the sample Treeview widget for the user to select the multiple rows. I used the tree.selection method for this in the code.
However, I am unable to figure out a better approach to retrieve the selected rows in an appropriate way. For example, If the user selects the IDs with 1 and 2. Then I would like to use... | [
"You can simply get the values tuple of the selected rows and append them to a list:\ndef Tree_Focus_Area():\n selections = tree.selection()\n rows = [tree.item(i, 'values') for i in selections]\n for i, row in enumerate(rows, 1):\n print(f\"The selected items for ID #{i}:\", ', '.join(row))\n\n"
] | [
1
] | [] | [] | [
"python",
"tkinter",
"treeview"
] | stackoverflow_0074574078_python_tkinter_treeview.txt |
Q:
Django ValueError: Cannot assign ">": "Booking.user" must be a "Customer" instance
The objective is simple: I'm building a car rental platform where customers can place an order for a car. The simple 'order' contains the car, start, and end-dates. The form should automatically save the authenticated user as the cr... | Django ValueError: Cannot assign ">": "Booking.user" must be a "Customer" instance | The objective is simple: I'm building a car rental platform where customers can place an order for a car. The simple 'order' contains the car, start, and end-dates. The form should automatically save the authenticated user as the creator.
It uses a CreateView with this code:
class BookingCreate(CreateView):
model =... | [
"Your self.request.user (or the user you're logged in as) seems to be the CustomUser instance, but you're trying to assign the User instance to the Booking. Though it has the same fields (as it inherits from CustomUser class), it is a different object.\nI think you want to make the CustomUser an abstract model?\nYo... | [
1,
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0074574723_django_django_forms_django_models_django_queryset_python.txt |
Q:
How to read and break down complex lambda equations in python
This question below is from a past year NUS exam paper, and im not sure how to go about solving this; how do you break down the lambda parts and figure out which bracket is for which lambda variable? I'm unable to trace the code to get 120
def combinato... | How to read and break down complex lambda equations in python | This question below is from a past year NUS exam paper, and im not sure how to go about solving this; how do you break down the lambda parts and figure out which bracket is for which lambda variable? I'm unable to trace the code to get 120
def combinator(y):
return (lambda x: lambda y: x(y))(lambda x:y)
combinator(... | [
"The function is\ndef combinator(y):\n return (lambda x: lambda y: x(y))(lambda x:y)\ncombinator(lambda x:x*10)(11)(12)\n\nLet's try to simplify the function. First, take note that you can change the symbol for a function. For example, lambda x: x can be changed to lambda z: z.\nAs there are a lot of x and y, we... | [
0
] | [] | [] | [
"function",
"higher_order_functions",
"lambda",
"python"
] | stackoverflow_0074573856_function_higher_order_functions_lambda_python.txt |
Q:
Can some one tell me how i can mask only front part of a car image in pygame?
I am making a car racing game, i want to mask front part of the car image (not the whole car image) for collision detection.
code
front = pygame.mask.from_surface(self.car.car_image)
offset = (int(self.car.x-x), int(self.car.y-y))
p = t... | Can some one tell me how i can mask only front part of a car image in pygame? | I am making a car racing game, i want to mask front part of the car image (not the whole car image) for collision detection.
code
front = pygame.mask.from_surface(self.car.car_image)
offset = (int(self.car.x-x), int(self.car.y-y))
p = track.overlap(front, offset)
| [
"You can create a subsurface of the image and then a mask from the subsurface:\nfront_surf = self.car.car_image.subsurface((0, 0, width, front_height))\nfront = pygame.mask.from_surface(front_surf)\n\n"
] | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074574963_pygame_python.txt |
Q:
Iterate over inner axes of an array
I want to iterate over some inner dimensions of an array without knowing in advance how many dimensions to iterate over. Furthermore I only know that the last two dimensions should not be iterated over.
For example assume the array has dimension 5 and shape (i,j,k,l,m) and I wan... | Iterate over inner axes of an array | I want to iterate over some inner dimensions of an array without knowing in advance how many dimensions to iterate over. Furthermore I only know that the last two dimensions should not be iterated over.
For example assume the array has dimension 5 and shape (i,j,k,l,m) and I want to iterate over the second and third di... | [
"With the caveat that I don't fully understand how you want to use this, I reckon the following should do what you are asking for:\nfrom itertools import product\n\ndef iterover(x, axes):\n x = np.moveaxis(x, axes, np.arange(len(axes)))\n subshape = x.shape[:len(axes)]\n ixi = product(*[range(k) for k in s... | [
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"numpy_slicing",
"python"
] | stackoverflow_0074574094_numpy_numpy_ndarray_numpy_slicing_python.txt |
Q:
Addition and multiplication recursion
I've been trying to write a recursive function that adds the following number to an odd number, and multiplies by the following number if the number is even. Essentially:
add_mult_rec(5) does 1+2*3+4*5 and should return 27
But by writing:
def add_mult_rec(num):
if num... | Addition and multiplication recursion | I've been trying to write a recursive function that adds the following number to an odd number, and multiplies by the following number if the number is even. Essentially:
add_mult_rec(5) does 1+2*3+4*5 and should return 27
But by writing:
def add_mult_rec(num):
if num == 1:
return num
elif ... | [
"The order of operation should be respected, what you wants is actually: 1 + (2 x 3) + (4 x 5) +...\ndef add_mult_rec(num):\n if num <= 1:\n return num\n \n if num % 2 == 1:\n return num * (num - 1) + add_mult_rec(num - 2)\n else:\n return num + add_mult_... | [
3
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074574806_python_recursion.txt |
Q:
Thread wont start within __init__ method of my class
Within the __init__ of my class I want to trigger a thread that handles a function.
For some reason the thread isnt triggered though, nothing just happens:
class OrderBook:
# Create two sorted lists for bids and asks
def __init__(self, bids=None, asks=N... | Thread wont start within __init__ method of my class | Within the __init__ of my class I want to trigger a thread that handles a function.
For some reason the thread isnt triggered though, nothing just happens:
class OrderBook:
# Create two sorted lists for bids and asks
def __init__(self, bids=None, asks=None):
if asks is None:
asks = []
... | [
"You are calling the target function eagerly, on the main thread.\nYou have to pass the function as an argument to the Thread constructor, and the arguments in separate, so that the function will be called inside the running thread:\n threading.Thread(target=populate_orderbook, args=(self, 10)).start()\n\n"
... | [
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0074574979_multithreading_python.txt |
Q:
Speeding up TF/Keras LSTM text generation on GPU?
The tensorflow official example for text generation (https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/text_generation.ipynb) runs in a loop as defined below. The text generation feels slow, and according to NVTOP only uses a fraction of the ava... | Speeding up TF/Keras LSTM text generation on GPU? | The tensorflow official example for text generation (https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/text_generation.ipynb) runs in a loop as defined below. The text generation feels slow, and according to NVTOP only uses a fraction of the available GPU resources (15-20%).
Any suggestions on how... | [
"To speed up the processing, I have two suggestions,\n\nAs you have GPU support, you may want to set unroll=True of the GRU layer. As per the Keras GRU documentation, setting unroll=True reduces some computation by using some extra memory. As your GPU consumption is quite less, you may want to use unroll=True. Usin... | [
1,
0,
0
] | [] | [] | [
"keras",
"performance",
"python",
"tensorflow"
] | stackoverflow_0061875324_keras_performance_python_tensorflow.txt |
Q:
Querying a dataframe to return rows based on a list/ndarray of conditions
Say I have a dataframe 'df':
And an array of numbers, called 'profiles':
[310, 47, 161, 51, 78, 162, 303, 314, 176, 54]
I'm trying to query 'df' on column 'dayNo' to only returns rows which match the array above (profiles), but not sure ho... | Querying a dataframe to return rows based on a list/ndarray of conditions | Say I have a dataframe 'df':
And an array of numbers, called 'profiles':
[310, 47, 161, 51, 78, 162, 303, 314, 176, 54]
I'm trying to query 'df' on column 'dayNo' to only returns rows which match the array above (profiles), but not sure how. I attempted the below, but to no avail:
df2 = df.loc[df['dayNo'] == [np.arra... | [
"You can use boolean indexing with pandas.Series.isin :\ndf2 = df.loc[df['dayNo'].isin(profiles)]\n\nAnother method is pandas.DataFrame.query :\ndf2 = df.query('dayNo in @profiles')\n\n"
] | [
2
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074574903_numpy_pandas_python.txt |
Q:
How to get all the likes of a twitter user using tweepy
I'm using tweepy with 1.1 API and Elevated access.
I have been trying to request all the likes of a user but there seems to be a limit of about 1430 returned tweets. I've tried with a couple of test accounts and it seems to get 1430-1440 then a "Too Many Requ... | How to get all the likes of a twitter user using tweepy | I'm using tweepy with 1.1 API and Elevated access.
I have been trying to request all the likes of a user but there seems to be a limit of about 1430 returned tweets. I've tried with a couple of test accounts and it seems to get 1430-1440 then a "Too Many Requests - Rate limit exceeded" error is returned.
This is the ca... | [
"Pay careful attention to the word \"rate\" in that diagnostic.\nIt refers to \"records per hour\",\nrather than \"total number of records\".\nTwitter offer extensive documentation on this topic:\nhttps://developer.twitter.com/en/docs/twitter-api/rate-limits#recovering\nYou obtained a 429 status because you ignored... | [
1
] | [] | [] | [
"api",
"python",
"tweepy",
"twitter"
] | stackoverflow_0074574920_api_python_tweepy_twitter.txt |
Q:
Create a counter of date values for a given max-min interval
Be the following python pandas DataFrame:
| date | column_1 | column_2 |
| ---------- | -------- | -------- |
| 2022-02-01 | val | val2 |
| 2022-02-03 | val1 | val |
| 2022-02-01 | val | val3 |
| 2022-02-04 | val2 | v... | Create a counter of date values for a given max-min interval | Be the following python pandas DataFrame:
| date | column_1 | column_2 |
| ---------- | -------- | -------- |
| 2022-02-01 | val | val2 |
| 2022-02-03 | val1 | val |
| 2022-02-01 | val | val3 |
| 2022-02-04 | val2 | val |
| 2022-02-27 | val2 | val4 |
I want to create a... | [
"Count dates first & remove duplicates using Drop duplicates. Fill intermidiate dates with Pandas has asfreq function for datetimeIndex, this is basically just a thin, but convenient wrapper around reindex() which generates a date_range and calls reindex.\ndf['counts'] = df['date'].map(df['date'].value_counts())\nd... | [
2,
1
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074574705_dataframe_datetime_pandas_python.txt |
Q:
How to change syntax highlighting in Jupyter Notebook?
a = np.array([1,4,3])
b = np.array([2,-1,5])
a@b
df['A'].fillna(value=df['A'].mean())
df.fillna(value=df.mean())
For teaching purposes: I need to apply a special color in Jupyter Notebook for coding to differentiate them from variables:
a, b: black by de... | How to change syntax highlighting in Jupyter Notebook? | a = np.array([1,4,3])
b = np.array([2,-1,5])
a@b
df['A'].fillna(value=df['A'].mean())
df.fillna(value=df.mean())
For teaching purposes: I need to apply a special color in Jupyter Notebook for coding to differentiate them from variables:
a, b: black by default, ok
1,4,3: Green by default, ok
@: Purple by defaul... | [
"As far as I can tell, the Jupyter rendering of python code formatting within a python code cell relies on specific CSS styles.\nso:\npd.DataFrame(...)\n\npd has a CSS style cm.variable (cmstands for codemirror)\nDataFrame has a CSS style cm.property\nSo the Jupyter notebook sees pd.DataFrame, it only sees variable... | [
1
] | [] | [] | [
"jupyter_notebook",
"python",
"syntax_highlighting"
] | stackoverflow_0052877167_jupyter_notebook_python_syntax_highlighting.txt |
Q:
Tensorflow lite model inference is very slow compared to keras h5 model (VGG16 pretrained)
Tensorflow lite predictions are extremely slow compared to keras (h5) model. The behavior is similar between Colab and also on Windows 10 system. I converted the standard VGG16 model to tflite both with and without optimizat... | Tensorflow lite model inference is very slow compared to keras h5 model (VGG16 pretrained) | Tensorflow lite predictions are extremely slow compared to keras (h5) model. The behavior is similar between Colab and also on Windows 10 system. I converted the standard VGG16 model to tflite both with and without optimization (converter.optimizations = [tf.lite.Optimize.DEFAULT])
Here are the results I got:
Keras mo... | [
"TensorFlow Lite isn't optimized for desktop/server, so its not surprising that it performs badly for most models in those environments. TFLite's optimized kernels (including lot of their GEMM operations) are especially geared for mobile CPUs (which don't have the same instruction set as desktop CPUs IIUC).\nStanda... | [
0,
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0066912736_keras_python_tensorflow.txt |
Q:
Logging in with Selenium then submitting requests with Python Requests gives error 401
I have the following code to log in to a website with Selenium, then submit a request with Requests. I can't easily stick to just requests or just Selenium for this project. I need both. Selenium successfully logs in, but Reques... | Logging in with Selenium then submitting requests with Python Requests gives error 401 | I have the following code to log in to a website with Selenium, then submit a request with Requests. I can't easily stick to just requests or just Selenium for this project. I need both. Selenium successfully logs in, but Requests gives an error 401 with any requests I submit. The Requests code was generated by Insomni... | [
"My solution to this problem has been to use the selenium requests package rather than selenium. This allows you to authenticate using selenium and then use that same webdriver object to send requests to specific APIs.\nI never found the root cause for trying to re-use the cookies from selenium with a different ses... | [
0
] | [] | [] | [
"python",
"python_requests",
"selenium",
"selenium_webdriver"
] | stackoverflow_0073930512_python_python_requests_selenium_selenium_webdriver.txt |
Q:
Dealing with Nested For Loops
Hello I was wondering if there is an easier and cleaner way of dealing with nested for loops.
lst = [['a','b','c','d','e','f','g'],['h','i','j','k','l','m','n','o','p'],
['q','r','s','t','u','v']]
path = ['c:\Data_1','c:\Data_2','c:\Data_3']
channel = ['Wholesale','Retail']
category =... | Dealing with Nested For Loops | Hello I was wondering if there is an easier and cleaner way of dealing with nested for loops.
lst = [['a','b','c','d','e','f','g'],['h','i','j','k','l','m','n','o','p'],
['q','r','s','t','u','v']]
path = ['c:\Data_1','c:\Data_2','c:\Data_3']
channel = ['Wholesale','Retail']
category = ['ALL','APPAREL','FOOTWEAR','ACCES... | [
"You can use list comprehension instead of multiple for loop:\nHere is the example:\nfor l,p in zip(lst,path): \n result_list = [(b, c, a, m) for b in l for c in channel for a in category for m in metric]\n print(result_list)\n\nHope it will be helpful :)\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074559522_pandas_python.txt |
Q:
How to integrate Twilio's Voice API service with AWS S3 Storage?
I'm trying to create a short program that calls a user's number and records the conversation using Twilio and send the recording to an S3 bucket
Here's a link that does it to a dropbox instead of an S3:
https://www.twilio.com/blog/recording-saving-ou... | How to integrate Twilio's Voice API service with AWS S3 Storage? | I'm trying to create a short program that calls a user's number and records the conversation using Twilio and send the recording to an S3 bucket
Here's a link that does it to a dropbox instead of an S3:
https://www.twilio.com/blog/recording-saving-outbound-voice-calls-python-twilio-dropbox
Here's the code I have so far... | [
"Twillio has inbuilt mechanism to do it, any specific use case you want to do it. https://www.twilio.com/blog/announcing-external-aws-s3-storage-support-for-voice-recordings\n",
"When you create the call you can also create a webhook that tells you when the recording is ready. When you then receive the webhook yo... | [
1,
1
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"flask",
"python",
"twilio"
] | stackoverflow_0074553752_amazon_s3_amazon_web_services_flask_python_twilio.txt |
Q:
Function to remove a part of a string before a capital letter in Pandas Series
I have a dataframe that includes a column ['locality_name'] with names of villages, towns, cities. Some names are written like "town of Hamilton", some like "Hamilton", some like "city of Hamilton" etc. As such, it's hard to count uniqu... | Function to remove a part of a string before a capital letter in Pandas Series | I have a dataframe that includes a column ['locality_name'] with names of villages, towns, cities. Some names are written like "town of Hamilton", some like "Hamilton", some like "city of Hamilton" etc. As such, it's hard to count unique values etc. My goal is to leave the names only.
I want to write a function that re... | [
"You can use pandas.Series.str.extract. For the example :\nser = pd.Series([\"town of Hamilton\", \"Hamilton\", \"city of Hamilton\"])\nser_2= ser.str.extract(\"([A-Z][a-z]+-?\\w+)\")\n\nIn your case, use :\nraw_data['locality_name_only'] = raw_data['locality_name'].str.extract(\"([A-Z][a-z]+-?\\w+)\")\n\n# Output ... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"python_re"
] | stackoverflow_0074575151_pandas_python_python_re.txt |
Q:
Trying to add a sentinel that is not a number (Python)
(I am new to Python so forgive me in advance) I have to write a program that calculates the total of integers from 1 to the user input. So if I input 4, it would add 1+2+3+4. I also added an argument that makes a number that is less than 1 print "invalid numbe... | Trying to add a sentinel that is not a number (Python) | (I am new to Python so forgive me in advance) I have to write a program that calculates the total of integers from 1 to the user input. So if I input 4, it would add 1+2+3+4. I also added an argument that makes a number that is less than 1 print "invalid number". I am stuck on adding a sentinel that is a letter. Thank ... | [
"Beginning of an answer.\nvalue = input(\"Enter a number or J to finish: \")\nwhile value ! = \"J\":\n i = float(value)\n# a placeholder for future code\nprint(value)\n# There is a lot of possible code to achieve the goal.\n\n",
"the function input() always stores the input as string data-type\nso if you give ... | [
0,
0
] | [] | [] | [
"if_statement",
"python",
"sentinel",
"while_loop"
] | stackoverflow_0074575127_if_statement_python_sentinel_while_loop.txt |
Q:
seperate string number ranges in pandas df
I have a df which looks like this
Type range
Mike 10..13|7|8|
Ni 3..4
NANA 2|1|6
and desired output should look like this
Type range
Mike 10
Mike 11
Mike 12
Mike 13
Mike 7
Mike 8
Nico 3
Nico 4
NANA 2
NANA 1
NANA 6
so, To... | seperate string number ranges in pandas df | I have a df which looks like this
Type range
Mike 10..13|7|8|
Ni 3..4
NANA 2|1|6
and desired output should look like this
Type range
Mike 10
Mike 11
Mike 12
Mike 13
Mike 7
Mike 8
Nico 3
Nico 4
NANA 2
NANA 1
NANA 6
so, Totaling column presenet the multiple values per T... | [
"Assuming that your ranges are inclusive, which I assume because your '3..4' translates to a row with 3 and a row with 4, and assuming that you forgot to put Mike 14 and Mike 15 in your example output, I found the following solution:\nimport pandas as pd\n\ndef parse_str(s):\n numbers = []\n for v in s.rstrip... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074575084_pandas_python.txt |
Q:
Doing math with numbers in a list
i want to be able to add, subtract, divide, multiply etc with integers in a list and in order.
I know you can use sum() to add, but i also want to be able to subtract, etc in order... so i tried making a for loop idk if thats the right thing to do, but it doesn't give me the right... | Doing math with numbers in a list | i want to be able to add, subtract, divide, multiply etc with integers in a list and in order.
I know you can use sum() to add, but i also want to be able to subtract, etc in order... so i tried making a for loop idk if thats the right thing to do, but it doesn't give me the right output and it really confuses me becau... | [
"There are two main issues with your code:\n\ni can't be your loop variable and the sum, because it will be overwritten all the time. So make two variables.\nYour first task is different from the second. The sum is easy: take all the values of the list and add them, so the order is irrelevant. For your subtraction ... | [
0,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074574492_for_loop_python.txt |
Q:
Why Python format function is not working?
In python I wrote:
list_of_assets = []
list_of_assets.append(('A', 'B', 'C'))
for asset in list_of_assets:
print('{:15} {:30} {:30}'.format([asset[0], asset[1], asset[2]]))
But I get:
print('{:15} {:30} {:30}'.format([asset[0], asset[1], asset[2]]))
TypeError... | Why Python format function is not working? | In python I wrote:
list_of_assets = []
list_of_assets.append(('A', 'B', 'C'))
for asset in list_of_assets:
print('{:15} {:30} {:30}'.format([asset[0], asset[1], asset[2]]))
But I get:
print('{:15} {:30} {:30}'.format([asset[0], asset[1], asset[2]]))
TypeError: non-empty format string passed to object.__for... | [
"Don't wrap the format parameters in a list:\nlist_of_assets = []\nlist_of_assets.append(('A', 'B', 'C'))\nfor asset in list_of_assets:\n # here ↓ and here ↓\n print('{:15} {:30} {:30}'.format(asset[0], asset[1], asset[2]))\n\noutput:\nA B ... | [
2,
1,
0
] | [] | [] | [
"format",
"python",
"python_3.x"
] | stackoverflow_0070582950_format_python_python_3.x.txt |
Q:
How to modify html title separator in Sphinx doc generator
By default it seems to what to use a long dash '--' as the separator between page title and overall site html_title that's set in the config.py file.
We'd like to change this to a '|' character instead.
I can add a block to the layout.html template to modi... | How to modify html title separator in Sphinx doc generator | By default it seems to what to use a long dash '--' as the separator between page title and overall site html_title that's set in the config.py file.
We'd like to change this to a '|' character instead.
I can add a block to the layout.html template to modify the title I'm just unsure of what to actually write for that.... | [
"The em dash (—) comes from the layout.html template:\n{%- if not embedded and docstitle %}\n{%- set titlesuffix = \" — \"|safe + docstitle|e %}\n{%- else %}\n{%- set titlesuffix = \"\" %}\n{%- endif %}\n\nThe value of titlesuffix is used a bit further down in the template:\n{%- block htmltitle %}\n<tit... | [
1
] | [] | [] | [
"documentation",
"html",
"python",
"python_sphinx"
] | stackoverflow_0074564451_documentation_html_python_python_sphinx.txt |
Q:
Count the frequency that a value occurs in a dataframe (multiple column)
I want to count the frequency of a value that are same in 2 column, also adding a column at the end that display the counting number & delete the first cloumn.
The dataframe I have
| Column A | Column B | Column C |
| -------- | -------- | --... | Count the frequency that a value occurs in a dataframe (multiple column) | I want to count the frequency of a value that are same in 2 column, also adding a column at the end that display the counting number & delete the first cloumn.
The dataframe I have
| Column A | Column B | Column C |
| -------- | -------- | -------- |
| Column A | Cat | Fish |
| Column A | Cat | Apple |... | [
"You can use GroupBy.count :\nout = (\n df.groupby([\"Column B\", \"Column C\"],\n as_index=False, sort=False)\n [\"Column A\"].count()\n )\n\n# Output :\nprint(out)\n Column B Column C Column A\n0 Cat Fish 1\n1 Cat Apple 2\n... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074575361_pandas_python.txt |
Q:
Python - Search a list of a group strings in text file
I want to search a list of group of strings inside a text file (.txt or .log).
it must include group A or B (or CDE..).
group A OR B each words need in the same line but not near by. (eg. ["123456", "Login"] or ["123457", "Login"] if in the same line then sav... | Python - Search a list of a group strings in text file | I want to search a list of group of strings inside a text file (.txt or .log).
it must include group A or B (or CDE..).
group A OR B each words need in the same line but not near by. (eg. ["123456", "Login"] or ["123457", "Login"] if in the same line then save it to a new txt file.
Some of example output line:
202211... | [
"import os, re\npath = \"Log\\\\\"\nfile_list = [path + f for f in os.listdir(path) if f.endswith('.log')]\n\nAll keep_phrases in a container, I choose a dictionary but since they are identified by order, it could have been a list:\nkeep_phrases = {'keep_phrases1': [\"123456\", \"Login\"], 'keep_phrases2':[\"123457... | [
0,
0,
0
] | [] | [] | [
"python",
"python_re",
"txt"
] | stackoverflow_0074568196_python_python_re_txt.txt |
Q:
When should I use pandas' Categorical dtype?
My question concerns optimizing memory usage for pandas Series. The docs note,
The memory usage of a Categorical is proportional to the number of categories plus the length of the data. In contrast, an object dtype is a constant times the length of the data.
My under... | When should I use pandas' Categorical dtype? | My question concerns optimizing memory usage for pandas Series. The docs note,
The memory usage of a Categorical is proportional to the number of categories plus the length of the data. In contrast, an object dtype is a constant times the length of the data.
My understanding is that pandas Categorical data is effect... | [
"categorical astype uses less memory. However one hot encoding allows you to maintain categorical ranking of the level. you can analyze the classifier coefficients to understand behavior and predictions on the categorical data.\n",
"\nis there any rule-of-thumb for when using pd.Categorical will not save memory... | [
0,
0
] | [] | [] | [
"categorical_data",
"memory",
"pandas",
"python"
] | stackoverflow_0048256395_categorical_data_memory_pandas_python.txt |
Q:
How do Assignment Operators and Lists Work? - Python
The assignment operator appears to work differently for lists than it does for integers:
>>> list1 = [1,2,3,4,5]
>>> newlist1 = list1
>>> print(id(list1))
140282759536448
>>> print(id(newlist1))
140282759536448
>>> newlist1.append(6)
>>> print(id(newlist1))
1402... | How do Assignment Operators and Lists Work? - Python | The assignment operator appears to work differently for lists than it does for integers:
>>> list1 = [1,2,3,4,5]
>>> newlist1 = list1
>>> print(id(list1))
140282759536448
>>> print(id(newlist1))
140282759536448
>>> newlist1.append(6)
>>> print(id(newlist1))
140282759536448
>>> print(list1)
[1, 2, 3, 4, 5, 6]
>>> print(... | [
"You should use newlist1 = list1.copy() because when you do newlist1 = list1 you are not creating new list you are referencing the same list\n",
"In Python, when you assign a list to a new variable, you will only pass the address of the list to it.\nThat is why the id()function return the same value.\nIf you want... | [
0,
0
] | [] | [] | [
"assignment_operator",
"integer",
"list",
"python",
"python_3.x"
] | stackoverflow_0074575436_assignment_operator_integer_list_python_python_3.x.txt |
Q:
Displaying better error than TypeException when doing JSON.dump on Python
When Python json.dump fails to serialise value, it does not tell what was the invalid key or where it was located. This makes json.dump useless when trying to locate data errors in large JSON objects.
Is it possible to improve json.dump Type... | Displaying better error than TypeException when doing JSON.dump on Python | When Python json.dump fails to serialise value, it does not tell what was the invalid key or where it was located. This makes json.dump useless when trying to locate data errors in large JSON objects.
Is it possible to improve json.dump TypeError error messages?
| [
"One can pre-validate the data before passing it to json.dump. json.dump encoder itself does not pass data locatin information around, making it hard to use it for the task.\nHere is a Python code that\n\nRaises nested custom exceptions to locate any keys with bad values\n\nContains some useful checks and patterns ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074575566_python.txt |
Q:
Python SciPy is 'RuntimeWarning: invalid value encountered in sqrt' bad?
I wanted to fit some astronomical data (made up data mostly), using a gaussian function on a line. I took the residual of the gaussian+line function on x-axis so I only had to fit the gaussian. Here's how I defined it:
def gaussian_only(x, am... | Python SciPy is 'RuntimeWarning: invalid value encountered in sqrt' bad? | I wanted to fit some astronomical data (made up data mostly), using a gaussian function on a line. I took the residual of the gaussian+line function on x-axis so I only had to fit the gaussian. Here's how I defined it:
def gaussian_only(x, amp, mean, std):
curve = amp*np.exp(-(x-mean)**2 /( 2*std**2 ) ) * np.sqrt(... | [
"curve_fit() probably attempted to evaluate your function with a negative value of std.\nYou can use the bounds argument of curve_fit() to avoid this. You should probably also avoid fitting with 0 standard deviation, so set a very small positive value as the lower bound:\nfit = scipy.optimize.curve_fit(gaussian_onl... | [
1
] | [] | [] | [
"curve_fitting",
"python",
"scipy"
] | stackoverflow_0074575480_curve_fitting_python_scipy.txt |
Q:
Need to find and replace/correct list from another df column
I have a list let suppose F = [Jonii, Max, anna, xyz, etc..] and df which contains 2 column- Name and Corrected_Name.
df
I need to search each string from list into df[Name] and replace it with df[Corrected_Name]. For eg. in above, code will search list ... | Need to find and replace/correct list from another df column | I have a list let suppose F = [Jonii, Max, anna, xyz, etc..] and df which contains 2 column- Name and Corrected_Name.
df
I need to search each string from list into df[Name] and replace it with df[Corrected_Name]. For eg. in above, code will search list in df[Name] and if found which is "Jonii" then replace it with "Jo... | [
"You can use a simple dict to do that:\nd = {k: v for k, v in zip(df['Name'], df['Corrected_Name'])}\nf = [d.get(k, k) for k in F]\n\nReproducible example\ndf = pd.DataFrame([['a', 'b'], ['b', 'c'], ['foo', 'bar']], columns=['Name', 'Corrected_Name'])\nF = ['a', 'aa', 'b', 'hello', 'foo']\n\n# code above\n\n>>> f\n... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074575299_pandas_python.txt |
Q:
How to do a kernel with horizontal stripes fast
I wanna do a kernel of zeros and ones. I have a list with pairs of heights (e.g. [[191.0, 243.0], [578.0, 632.0]]. What I want to do is set ones in the kernel on those rows with height between the values of a pair of heights.
Example image about what I want to do (in... | How to do a kernel with horizontal stripes fast | I wanna do a kernel of zeros and ones. I have a list with pairs of heights (e.g. [[191.0, 243.0], [578.0, 632.0]]. What I want to do is set ones in the kernel on those rows with height between the values of a pair of heights.
Example image about what I want to do (in this case 2 pairs, the values above):
enter image de... | [
"IIUC, it is quite simple:\nfor h0, h1 in hpairs:\n mask[h0:h1, :] = 1\n\nReproducible example\nw, h = 8, 4\nmask = np.zeros((w, h), dtype=np.uint8)\n\nhpairs = [\n [1,3],\n [5,6],\n]\n\nfor h0, h1 in hpairs:\n mask[h0:h1, :] = 1\n\n>>> mask\narray([[0, 0, 0, 0],\n [1, 1, 1, 1],\n [1, 1, 1, ... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074573234_numpy_python.txt |
Q:
Level-field validation in django rest framework 3.1 - access to the old value
Before updating object the title field is validated. How to access data of serialized object in order to compare value with older value of this object?
from rest_framework import serializers
class BlogPostSerializer(serializers.Serializ... | Level-field validation in django rest framework 3.1 - access to the old value | Before updating object the title field is validated. How to access data of serialized object in order to compare value with older value of this object?
from rest_framework import serializers
class BlogPostSerializer(serializers.Serializer):
title = serializers.CharField(max_length=100)
content = serializers.Ch... | [
"You can do this:\ndef validate_title(self, value):\n \"\"\"\n Check that the title has not changed.\n \"\"\"\n if self.instance and value != self.instance.title\n raise serializers.ValidationError(\"Title of a blog post cannot be edited \")\n return value\n\nIn case of... | [
2,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"serialization"
] | stackoverflow_0031089407_django_django_rest_framework_python_serialization.txt |
Q:
Refined manipulation of sympy expressions
I am trying to work with sympy and work with manipulation of expressions.
import sympy as sym
from sympy.abc import t
x0,v0 = sym.symbols("x0 v0 ", real=True)
wn = sym.symbols("omega_n", positive = True, real=True)
z = sym.symbols("zeta", positive = True, real=True)
... | Refined manipulation of sympy expressions | I am trying to work with sympy and work with manipulation of expressions.
import sympy as sym
from sympy.abc import t
x0,v0 = sym.symbols("x0 v0 ", real=True)
wn = sym.symbols("omega_n", positive = True, real=True)
z = sym.symbols("zeta", positive = True, real=True)
x = sym.Function('x')
Dx = sym.Derivative(x(t),... | [
"One way is to use pattern matching. Note that your circled term is a multiplication, containing z**2 (a power operation).\n# search the expression tree and select all multiplications\n# containing a power with exponent 2\nw = sym.Wild(\"w\", properties=[\n lambda e: e.is_Mul and any(t.is_Pow and t.exp == 2 for ... | [
3,
1
] | [] | [] | [
"expression",
"python",
"sympy"
] | stackoverflow_0074574539_expression_python_sympy.txt |
Q:
Deleting multiple elements in a list - with a list of item locations
I have two lists.
List1 is the list of items I am trying to format
List2 is a list of item locations in List1 that I need to remove (condensing duplicates)
The issue seems to be that it first removes the first location (9) and then removes the se... | Deleting multiple elements in a list - with a list of item locations | I have two lists.
List1 is the list of items I am trying to format
List2 is a list of item locations in List1 that I need to remove (condensing duplicates)
The issue seems to be that it first removes the first location (9) and then removes the second (16) after...instead of doing them simultaneously. After it removes ... | [
"You can sort List2 and reverse it afterward (sorted(List2, key=List2.index, reverse=True)). Then python will remove these elements from back to the front:\nList1 = [\"HST\", \"BA\", \"CRM\", \"QQQ\", \"IYR\", \"TDG\", \"HD\", \"TDY\", \"UAL\", \"CRM\", \"XOM\", \"CCL\", \"LLY\", \"QCOM\", \"UPS\", \"MPW\", \"CCL\"... | [
1,
0,
0,
0
] | [] | [] | [
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074575522_numpy_python_python_3.x.txt |
Q:
How to print multiple words in my program?
I have this program that reads a file and prints the desired amount of most common words. I don't know how to print the words that appear the same amount of times.
Here's my code:
number_of_words = int(input('Enter how many top words you want to see: '))
uniques = []
stop... | How to print multiple words in my program? | I have this program that reads a file and prints the desired amount of most common words. I don't know how to print the words that appear the same amount of times.
Here's my code:
number_of_words = int(input('Enter how many top words you want to see: '))
uniques = []
stop_words = ["a", "an", "and", "in", "is"]
for word... | [
"We can achieve by using this.\ncount_with_word = {}\nfor i in range(min(number_of_words, len(counts))):\n count, word = counts[i]\n if count in count_with_word:\n count_with_word[count].append(word)\n else:\n count_with_word[count] = [word]\n\nfor count, words in count_with_word.items():\n ... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074575523_python_python_3.x.txt |
Q:
Python Sqlite3 insert operation with a list of column names
Normally, if i want to insert values into a table, i will do something like this (assuming that i know which columns that the values i want to insert belong to):
conn = sqlite3.connect('mydatabase.db')
conn.execute("INSERT INTO MYTABLE (ID,COLUMN1,COLUMN2... | Python Sqlite3 insert operation with a list of column names | Normally, if i want to insert values into a table, i will do something like this (assuming that i know which columns that the values i want to insert belong to):
conn = sqlite3.connect('mydatabase.db')
conn.execute("INSERT INTO MYTABLE (ID,COLUMN1,COLUMN2)\
VALUES(?,?,?)",[myid,value1,value2])
But now i have a list of... | [
"As far as I know the parameter list in conn.execute works only for values, so we have to use string formatting like this:\nimport sqlite3\nconn = sqlite3.connect(':memory:')\nconn.execute('CREATE TABLE t (a integer, b integer, c integer)')\ncol_names = ['a', 'b', 'c']\nvalues = [0, 1, 2]\nconn.execute('INSERT INTO... | [
4,
3,
1,
0
] | [] | [] | [
"python",
"python_2.7",
"sqlite"
] | stackoverflow_0020044178_python_python_2.7_sqlite.txt |
Q:
I have a problem with my "Game of life" on python
I don't know why but my "def" that checks 3 rules of "Game of live" doesn't work correctly. I have 2 lists that contains 0 and some 1 to check the program. 3 points that should give this image but instead it gives this
def upd(mass,screen,WHITE,mass1):
BLACK =... | I have a problem with my "Game of life" on python | I don't know why but my "def" that checks 3 rules of "Game of live" doesn't work correctly. I have 2 lists that contains 0 and some 1 to check the program. 3 points that should give this image but instead it gives this
def upd(mass,screen,WHITE,mass1):
BLACK = (0,0,0)
for i in range(len(mass)-1):
for j... | [
"mass = mass1 does not copy the contents of the grid, it just puts a reference to mass1 in mass (actually only in the local variable mass in scope of upd). You must deep copy the grid:\nfor i in range(len(mass1)):\n for j in range(len(mass1[i])):\n mass[i][j] == mass1[i][j]\n\n"
] | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074575332_pygame_python.txt |
Q:
Airflow Subdag started but tasks within it not starting
I have a situation and problem in my production airflow. Here it goes :
There’s a dag with multiple subdags. when I trigger the dag, sub-dag got triggered and shows as in progress but the tasks inside it are not getting started. shows as blank for long time.... | Airflow Subdag started but tasks within it not starting | I have a situation and problem in my production airflow. Here it goes :
There’s a dag with multiple subdags. when I trigger the dag, sub-dag got triggered and shows as in progress but the tasks inside it are not getting started. shows as blank for long time.
When I try to render the pod spec, this error shows :
Error ... | [
"Yeah, sometimes this happens to me too. Maybe it is an Airflow bug, I don't know.\nWhat I do instead is force the Subdag to trigger manually:\n\nAfter I do this once, the next DAG execution will run as expected.\nEdit:\nAfter some research, I found out this DAG parameter might be related is_paused_upon_creation, o... | [
0
] | [] | [] | [
"airflow",
"python"
] | stackoverflow_0073354932_airflow_python.txt |
Q:
protocol buffers in python: no classes generated
My proto file is as follows:
syntax = "proto3";
option csharp_namespace = "Proto";
message FileListRequest {
repeated File Files = 1;
}
message File {
string Path = 1;
}
message ImageFile {
File File = 1;
Size Size = 2;
bytes Content = 3;
}
m... | protocol buffers in python: no classes generated | My proto file is as follows:
syntax = "proto3";
option csharp_namespace = "Proto";
message FileListRequest {
repeated File Files = 1;
}
message File {
string Path = 1;
}
message ImageFile {
File File = 1;
Size Size = 2;
bytes Content = 3;
}
message Size {
int32 Width = 1;
int32 Height = ... | [
"Documentation says:\n\nUnlike when you generate Java and C++ protocol buffer code, the Python\nprotocol buffer compiler doesn't generate your data access code for\nyou directly.\n\nIt means, that your .proto files won't be converted into some familiar accessors (no classes, no methods and no properties defined)\nT... | [
1,
0
] | [] | [] | [
"protocol_buffers",
"python"
] | stackoverflow_0071960226_protocol_buffers_python.txt |
Q:
Why is my count variable not calculating correct number of True values from the list?
I have a list values_count which contains boolean values True and False. I am trying to calculate number of True values present in the list. For example , for the list ltr=[False,True,True,True] I expect my answer to be 3 but my ... | Why is my count variable not calculating correct number of True values from the list? | I have a list values_count which contains boolean values True and False. I am trying to calculate number of True values present in the list. For example , for the list ltr=[False,True,True,True] I expect my answer to be 3 but my answer comes 0, the initial value of the count variable that I have declared. Below is my c... | [
"Actually, am + 1 should be am =+ 1 and return am should be at the last line.\nHowever, you can use my code below:\ndef count_true(self, values_count=[]):\n count = 0\n for value in values_count:\n if value:\n count += 1\n return count\n\nOutput:\n> 3\n\n",
"why not just\nltr = [False, ... | [
0,
0
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0074575802_for_loop_list_python.txt |
Q:
How to incorporate options?
I am new to web scraping but fortunately I am taking a class that gives us much of the framework needed for scraping certian API's. I want to change the options of which youtube videos I am extracting Info from but I am not sure how.
ydl_opts = {'dump_single_json': True, 'writeautomatic... | How to incorporate options? | I am new to web scraping but fortunately I am taking a class that gives us much of the framework needed for scraping certian API's. I want to change the options of which youtube videos I am extracting Info from but I am not sure how.
ydl_opts = {'dump_single_json': True, 'writeautomaticsub': True, 'subtitleslangs': ['e... | [
"I believe I have figured it out, but I am not 100% that the videos extracted are, in fact, within the specified date:\nydl_opts = {'dump_single_json': True, 'writeautomaticsub': True, 'subtitleslangs': ['en'], 'datebefore': 2012}\n\n"
] | [
0
] | [] | [] | [
"python",
"youtube_dl"
] | stackoverflow_0074575883_python_youtube_dl.txt |
Q:
why is the return of the program not good?
I'm new to python and there's a video on Youtube that I watched. I do the exact same code as he but mine doesn't work and I don' understand why.
Here's the code:
MAX_LINES = 3
def deposit():
while True:
amount = input("What would you like to deposit? $")
... | why is the return of the program not good? | I'm new to python and there's a video on Youtube that I watched. I do the exact same code as he but mine doesn't work and I don' understand why.
Here's the code:
MAX_LINES = 3
def deposit():
while True:
amount = input("What would you like to deposit? $")
if amount.isdigit():
amount = in... | [
"\nYou have one space too much in front of while True in function get_number_of_lines().\nYes used in functions to return value\nBecause function don't get inside while loop (because of indent problem), lines is never defined, probably this was the problem.\n\nSo try fix indent and run again\n"
] | [
0
] | [] | [] | [
"python",
"return"
] | stackoverflow_0074575758_python_return.txt |
Q:
How to load Pickle file in chunks?
Is there any option to load a pickle file in chunks?
I know we can save the data in CSV and load it in chunks.
But other than CSV, is there any option to load a pickle file or any python native file in chunks?
A:
Based on the documentation for Python pickle, there is not curren... | How to load Pickle file in chunks? | Is there any option to load a pickle file in chunks?
I know we can save the data in CSV and load it in chunks.
But other than CSV, is there any option to load a pickle file or any python native file in chunks?
| [
"Based on the documentation for Python pickle, there is not currently support for chunking.\nHowever, it is possible to split data into chunks and then read in chunks. For example, suppose the original structure is\nimport pickle\n\nfilename = \"myfile.pkl\"\nstr_to_save = \"myname\"\n\nwith open(filename,'wb') as ... | [
0,
0,
0
] | [] | [] | [
"chunks",
"csv",
"file",
"pickle",
"python"
] | stackoverflow_0059983073_chunks_csv_file_pickle_python.txt |
Q:
Passing a string to pandas.loc
There is a pandas data frame for which it is required make a subset using multiple conditions. This works when the conditions are hard-coded:
subset_frame = data_frame.loc[(data_frame['Quantity'] >5) & (data_frame['Discount'] >0)]
The conditions vary and a function is being created ... | Passing a string to pandas.loc | There is a pandas data frame for which it is required make a subset using multiple conditions. This works when the conditions are hard-coded:
subset_frame = data_frame.loc[(data_frame['Quantity'] >5) & (data_frame['Discount'] >0)]
The conditions vary and a function is being created for whatever list of conditions is s... | [
"You need to use eval :\nmystring = \"(data_frame['Quantity'] >5) & (data_frame['Discount'] >0)\"\n\nsubset_frame= data_frame.loc[eval(mystring)]\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python",
"string"
] | stackoverflow_0074575882_pandas_python_string.txt |
Q:
Graphs overlap each other when showing them in a Flask application
I would like to show multiple graphs on a webpage, build with flask. The graphs work fine when I run them separately, but when I try to show them on the same page, they overlap.
main.py
@main.route('/filetypebarchart', methods=["GET"])
def filetype... | Graphs overlap each other when showing them in a Flask application | I would like to show multiple graphs on a webpage, build with flask. The graphs work fine when I run them separately, but when I try to show them on the same page, they overlap.
main.py
@main.route('/filetypebarchart', methods=["GET"])
def filetypebarchart():
fig1 =plt.figure("1")
df = pd.read_csv('./export_da... | [
"Ooh meanwhile, I found out myself.\nI needed to add the following line to close the plot.\nplt.close(fig1)\n\nSo now it looks like this.\n@main.route('/filetypebarchart', methods=[\"GET\"])\ndef filetypebarchart():\n fig1 =plt.figure(\"1\")\n\n df = pd.read_csv('./export_dataframe.csv') \n \n df.value_cou... | [
0
] | [] | [] | [
"flask",
"matplotlib",
"python"
] | stackoverflow_0074575666_flask_matplotlib_python.txt |
Q:
Print every two pairs in a new line from array of elements in Python
How can I print from an array of elements in Python every second pair of elements one below another, without commas and brackets?
My array looks like this:
m=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
And, I want to print in one of the cases:
1 2
5... | Print every two pairs in a new line from array of elements in Python | How can I print from an array of elements in Python every second pair of elements one below another, without commas and brackets?
My array looks like this:
m=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
And, I want to print in one of the cases:
1 2
5 6
9 10
or in another case:
3 4
7 8
11 12
I didn't know how to do that, ... | [
"You could use a while loop\nm = [1,2,3,4,5,6,7,8,9] \nidx = 0\ntry:\n while idx < len:\n print(m[idx], m[idx+1]) \n idx += 3\nexcept IndexError:\n print(\"Index out of bounds\") \n\nJust change the start Index (idx) for the other print\n",
"Another way to do it like this-\nm=[1, 2, 3, 4, 5, 6... | [
0,
0,
0,
0
] | [] | [] | [
"arrays",
"printing",
"python",
"python_3.x"
] | stackoverflow_0074575687_arrays_printing_python_python_3.x.txt |
Q:
Keys and Values as two columns?
I have a data frame with several columns. Each of the column headers is a unique category and the rows below it contain a list of items in that category. I would like to transform it into two columns. Ideally, the first column would have all of the items listed and the second column... | Keys and Values as two columns? | I have a data frame with several columns. Each of the column headers is a unique category and the rows below it contain a list of items in that category. I would like to transform it into two columns. Ideally, the first column would have all of the items listed and the second column would have the corresponding categor... | [
"You can use pandas.melt function for that :\nimport pandas as pd\n\ndf = pd.DataFrame({\n \"Birds\": [\"Eagle\", \"Swan\", \"Robi\"],\n \"Fish\": [\"cod\", \"salmon\", \"Haddock\"],\n \"Farm animals\": [\"Pig\", \"horse\", \"hen\"]\n})\n\ndf\n\n\ndf = df.melt(value_vars=df.columns).rename(columns={\"varia... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074575564_dataframe_pandas_python.txt |
Q:
How to make a Tkinter window jump to the front?
How do I get a Tkinter application to jump to the front? Currently, the window appears behind all my other windows and doesn't get focus.
Is there some method I should be calling?
A:
Assuming you mean your application windows when you say "my other windows", you c... | How to make a Tkinter window jump to the front? | How do I get a Tkinter application to jump to the front? Currently, the window appears behind all my other windows and doesn't get focus.
Is there some method I should be calling?
| [
"Assuming you mean your application windows when you say \"my other windows\", you can use the lift() method on a Toplevel or Tk:\nroot.lift()\n\nIf you want the window to stay above all other windows, use: \nroot.attributes(\"-topmost\", True)\n\nWhere root is your Toplevel or Tk. Don't forget the - infront of \"... | [
111,
46,
31,
6,
4,
4,
4,
3,
2,
1,
0,
0
] | [] | [] | [
"focus",
"python",
"tkinter"
] | stackoverflow_0001892339_focus_python_tkinter.txt |
Q:
Pandas: replacing nan values conditionally within a group
I have a dataframe with missing values. for each index in a column group, i want to replace these values seperately. If all of the values in a group are missing, i want to replace the values with 1. If only some of the values are missing, i want to replace... | Pandas: replacing nan values conditionally within a group | I have a dataframe with missing values. for each index in a column group, i want to replace these values seperately. If all of the values in a group are missing, i want to replace the values with 1. If only some of the values are missing, i want to replace it with data from an imputed dataframe
dataframe 1
index
d... | [
"IIUC:\ndf = df1.mask(df1.groupby('group', axis=1).count() == 0, 1)\ndf = df.where(~df.isna(), df2)\n\n>>> df\nindex d0_1 d0_2 d1_1 d1_2\ngroup d0 d0 d1 d1\n1 3 3 1 1\n2 3 2 3 3\n\nThis is assuming the columns are indeed a MultiIndex as you describe, e.g.:\n>>> df1.columns\nM... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074574058_dataframe_pandas_python.txt |
Q:
python: simplify return statement (trigraph?)
Consider the following simple code:
import re
def my_match(s):
if re.match("^[a-zA-Z]+", s):
return True
else:
return False
Is there a way to collapse this in a single return statement? In C we could do for example:
return match("^[a-zA-Z]+"... | python: simplify return statement (trigraph?) | Consider the following simple code:
import re
def my_match(s):
if re.match("^[a-zA-Z]+", s):
return True
else:
return False
Is there a way to collapse this in a single return statement? In C we could do for example:
return match("^[a-zA-Z]+", s) ? true : false;
Is there something similar in... | [
"A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit.\nreturn re.match(\"^[a-zA-Z]+\", s) is not None\n\n",
"Python also supports this, although the synt... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074575794_python_python_3.x.txt |
Q:
Import into tables from Django import_export
I am struggling to populate models in Django by using ForeignKey. Let's say we have as in import_export documentation the following example:
class Author(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=100)
def _... | Import into tables from Django import_export | I am struggling to populate models in Django by using ForeignKey. Let's say we have as in import_export documentation the following example:
class Author(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Cat... | [
"There are a couple of ways of creating an FK relation during import if it does not already exist.\nOption 1 - override the before_import_row() method\nclass BookResource(resources.ModelResource):\n\n # note use of 'iexact' for case-insensitive lookup\n def before_import_row(self, row, **kwargs):\n aut... | [
1
] | [] | [] | [
"django",
"django_import_export",
"python"
] | stackoverflow_0074562802_django_django_import_export_python.txt |
Q:
Starting a Google Compute instance with Python
I am trying to start a Google Compute instance with the Google API Python Client Library. This is so that a cheap instance (running on a single core) can periodically start and stop a more expensive instance (with many cores) periodically, to keep costs down.
I have s... | Starting a Google Compute instance with Python | I am trying to start a Google Compute instance with the Google API Python Client Library. This is so that a cheap instance (running on a single core) can periodically start and stop a more expensive instance (with many cores) periodically, to keep costs down.
I have successfully installed the different components and r... | [
"Below is the code needed to start a compute engine instance\nfrom googleapiclient import discovery\n\nservice = discovery.build('compute', 'v1')\nprint('VM Instance starting')\n\n# Project ID for this request.\nproject = 'project_name' \n\n# The name of the zone for this request.\nzone = 'zone_value' \n\n# Name o... | [
5,
3,
0
] | [
"I used the code shared by @user570778, and for me it worked fine.\n`from googleapiclient import discovery\nservice = discovery.build('compute', 'v1')\nprint('VM Instance starting')\nProject ID for this request.\nproject = 'project_name'\nThe name of the zone for this request.\nzone = 'zone_value'\nName of the inst... | [
-2
] | [
"google_api_python_client",
"google_compute_engine",
"python"
] | stackoverflow_0045207202_google_api_python_client_google_compute_engine_python.txt |
Q:
Importing multiple excel files and combining into dataframe
I am trying to import many excel files (around 400) into one dataframe from a folder but I seem to be running into an error.
The files I want from my folder are names filename followed by a date - "filename_yyyy_mm_dd.xlsx".
I want to keep the header as t... | Importing multiple excel files and combining into dataframe | I am trying to import many excel files (around 400) into one dataframe from a folder but I seem to be running into an error.
The files I want from my folder are names filename followed by a date - "filename_yyyy_mm_dd.xlsx".
I want to keep the header as the files have all same columns for different dates.
My current co... | [
"Instead of using concat, you could try reading the files into a df and then append them to one combined csv using mode='a'. Then read the combined csv.\nfor filename in my_files:\n df = pd.read_excel(filename, index_col=None, header=1)\n df.to_csv('combined.csv', mode='a', header=False)\n\n\ndf = pd.re... | [
0,
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074574921_excel_pandas_python.txt |
Q:
Python loops, need some advice
i trying to create a small program usign python and i need some help about python loops.
this small program will automates a fairly boring repetitive task.
I use module : selenium, time and pyautogui
here is the piece of code that i want to repeat until it no longer finds a certain e... | Python loops, need some advice | i trying to create a small program usign python and i need some help about python loops.
this small program will automates a fairly boring repetitive task.
I use module : selenium, time and pyautogui
here is the piece of code that i want to repeat until it no longer finds a certain element on the web page :
btnOptions ... | [
"I've done a similar task. You may try this:\nwhile True:\n try:\n btnOptions = driver.find_element(By.XPATH, \"/html/body/div[1]/div/div[1]/div/div[5]/div/div/div[3]/div/div/div[1]/div[1]/div/div/div[4]/div[2]/div/div[2]/div[3]/div[1]/div/div/div/div/div/div/div/div/div/div/div[8]/div/div[2]/div/div[3]/d... | [
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074575175_loops_python.txt |
Q:
Is there a way to use another computer GPU in vscode notebook?
I have laptop A with Nvidia 2060 and desktop B with Nvidia 3080 in my room.
All settings, files, and notebooks are in laptop A.
Laptop A and Desktop B are on the same network (with a network hub).
Is it possible to run notebooks (that contains tensorfl... | Is there a way to use another computer GPU in vscode notebook? | I have laptop A with Nvidia 2060 and desktop B with Nvidia 3080 in my room.
All settings, files, and notebooks are in laptop A.
Laptop A and Desktop B are on the same network (with a network hub).
Is it possible to run notebooks (that contains tensorflow neural network parts) on desktop B GPU while working from laptop ... | [
"I am not sure, if you get it running but try this:\nhttps://code.visualstudio.com/docs/remote/vscode-server\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074576049_python.txt |
Q:
Python split by dot and question mark, and keep the character
I have a function:
with open(filename,'r') as text:
data=text.readlines()
split=str(data).split('([.|?])')
for line in split:
print(line)
This prints the sentences that we have after splitting a text by 2 different marks. I also want to ... | Python split by dot and question mark, and keep the character | I have a function:
with open(filename,'r') as text:
data=text.readlines()
split=str(data).split('([.|?])')
for line in split:
print(line)
This prints the sentences that we have after splitting a text by 2 different marks. I also want to show the split symbol in the output, this is why I use () but the s... | [
"Try escaping the marks, as both symbols have functional meanings in RegEx. Also I'm quite not sure if the str.split method takes regex. maybe try it with split from Python's \"re\" module.\n[\\.|\\?]\n\n",
"There are a few distinct problems, here.\n1. read vs readlines\n\n data = text.readlines()\n\n\nThis pr... | [
0,
0
] | [] | [] | [
"python",
"split"
] | stackoverflow_0074575458_python_split.txt |
Q:
With Python, I want to add the last two values of a string but I want to keep double digit numbers together and not include spaces in the string index
I need to create a fibonacci sequence (k = 5, until 5 elements are in the sequence) from an original string containing two starting values. While calling the last t... | With Python, I want to add the last two values of a string but I want to keep double digit numbers together and not include spaces in the string index | I need to create a fibonacci sequence (k = 5, until 5 elements are in the sequence) from an original string containing two starting values. While calling the last two elements in the string forward (newnumber= old[-1] + old[-2]) I pull the number "5" and what seems to be a "black space". Is there a way to lift the inte... | [
"Use split() to split the string on whitespace. When you write it back out you can use join() to turn the list of numbers back into a string.\nwith open('old.txt') as f:\n nums = [int(n) for n in f.read().strip().split()]\n\nwhile len(nums) < 5:\n nums.append(nums[-2] + nums[-1])\n\nwith open('new.txt', 'w')... | [
0
] | [] | [] | [
"fibonacci",
"python",
"rosalind"
] | stackoverflow_0074576106_fibonacci_python_rosalind.txt |
Q:
Python .exe keylogger file not sending email
I created a keylogger which captures keystrokes and sends the keystrokes file to an email address specified. The python script when run from VS code terminal works perfectly, but when I compiled the files into an executable(.exe) using nuitka and execute the .exe file b... | Python .exe keylogger file not sending email | I created a keylogger which captures keystrokes and sends the keystrokes file to an email address specified. The python script when run from VS code terminal works perfectly, but when I compiled the files into an executable(.exe) using nuitka and execute the .exe file by double-clicking on the .exe file, the keylogger ... | [
"So, nuitka doesn't compile python scripts effectively, thus not allowing the .exe file to send the email specified in your code. I suggest you try pyinstaller and see if that works.\n"
] | [
0
] | [] | [] | [
"executable",
"keylogger",
"nuitka",
"python",
"security"
] | stackoverflow_0074556880_executable_keylogger_nuitka_python_security.txt |
Q:
How can I drop nan(s)?
Unique values of the column as follows:
array(['..', '0', nan, ..., '30.0378539547197', '73.3261637778593',
'59.9402466154723'], dtype=object)
I use the following codes to drop NaNs and None.
df[df["Country Name"].isin([None]) == False]
and it still includes the NaNs.
A:
You can u... | How can I drop nan(s)? | Unique values of the column as follows:
array(['..', '0', nan, ..., '30.0378539547197', '73.3261637778593',
'59.9402466154723'], dtype=object)
I use the following codes to drop NaNs and None.
df[df["Country Name"].isin([None]) == False]
and it still includes the NaNs.
| [
"You can use .isna to check for nan.\ndf[~df[\"Country Name\"].isna()]\n\n",
"Did you try this df = df.dropna() ?\n",
"You can probably use \"dropna\" method if the NaN's are in a correct format.\nAnd if you want to do it for a particular column then, use\ndf[\"column_name\"].dropna()\nor\ndf.dropna(subset=['co... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074575387_pandas_python.txt |
Q:
how to enter the user's reply message on the bot and put it in a variable
so the problem here is I want to enter data into the database via a bot, and I'm trying to retrieve word for word with arrays or indexing, but what if the user wants to enter data into the name column and has a varied name which can consist ... | how to enter the user's reply message on the bot and put it in a variable | so the problem here is I want to enter data into the database via a bot, and I'm trying to retrieve word for word with arrays or indexing, but what if the user wants to enter data into the name column and has a varied name which can consist of 4-3 sentences, so do you guys have a solution My Code
I'm confused, I hope s... | [
"You can assume that class and status are always a single word so take texts[-1] as status, texts[-2] as class and texts[:-2] as the name. This way if it is a name with 3-4 words then all of it will be accounted for.\n"
] | [
0
] | [] | [] | [
"bots",
"py_telegram_bot_api",
"python",
"variables"
] | stackoverflow_0074576164_bots_py_telegram_bot_api_python_variables.txt |
Q:
Having an error message when trying to sort a dataset in customized list
I'm using python to organize an imported csv file. the dataset I have looks like this
Name Style ID
0 heels High end 1
1 sneaker Middle 0
2 top High end 3
3 skirt Low end 6
4 dress High end ... | Having an error message when trying to sort a dataset in customized list | I'm using python to organize an imported csv file. the dataset I have looks like this
Name Style ID
0 heels High end 1
1 sneaker Middle 0
2 top High end 3
3 skirt Low end 6
4 dress High end 4
5 sweater Low end 9
6 hat N/A. 2
..
I am trying to ... | [
"use pd.Categorical to specify the order.\nstyle_list = df['Style'].unique()\nsort_order = sorted(style_list, key=lambda x: (x == 'High end', x == 'Middle', x == 'Low end'), reverse=True)\ndf['Style'] = pd.Categorical(df['Style'], categories=sort_order, ordered=True)\ndf.sort_values('Style', inplace=True)\n\noutput... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"sorting"
] | stackoverflow_0074576076_dataframe_pandas_python_sorting.txt |
Q:
use of < var < in embedded if statements
I'm learning Python via Udemy and we did a coding project where you have to get a user's height and weight, calculate their BMI and print the result. In my code, for the embedded if (elif) statements, I did something like this (variable is bmi to hold the actual BMI calcula... | use of < var < in embedded if statements | I'm learning Python via Udemy and we did a coding project where you have to get a user's height and weight, calculate their BMI and print the result. In my code, for the embedded if (elif) statements, I did something like this (variable is bmi to hold the actual BMI calculation): elif 18.5 < bmi < 25
if bmi < 18.5:
p... | [
"\nnow, the instructor instead did this: elif bmi < 25\n\nThis is better for two reasons:\n\nYou already know bmi >= 18.5 because if it were lower you would have entered the first if clause and not reached this elif test. So it's a waste of effort to test again whether for bmi > 18.5\n\nIf bmi is exactly equal to 1... | [
4
] | [
"x < bmi < y is perfectly fine Python code. Python will interpret it as x < bmi and bmi < y:\nhttps://www.geeksforgeeks.org/chaining-comparison-operators-python/\nHowever, as @The Photon said, your code will have a bug if you input bmi = 18.5 or 25.\nSince if, elif, ... statements are evaluated in sequence, it's be... | [
-1
] | [
"python"
] | stackoverflow_0074576190_python.txt |
Q:
Kubectl logs does not return any output
I am trying to debug my application and I need to look the logs for my backend service. I run it with conda run and the configuration is the following:
# Partir de l’image officielle de Python 3.7
FROM continuumio/miniconda3
EXPOSE 50051
# Mettre le code de l’application d... | Kubectl logs does not return any output | I am trying to debug my application and I need to look the logs for my backend service. I run it with conda run and the configuration is the following:
# Partir de l’image officielle de Python 3.7
FROM continuumio/miniconda3
EXPOSE 50051
# Mettre le code de l’application dans le répertoire / de l’image
WORKDIR /
# C... | [
"I made it work by specifying to use stdout instead of stderr in the logging config. It is weird though since the doc specifies that both stderr and stdout should be logged.\n"
] | [
0
] | [] | [] | [
"kubernetes",
"logging",
"python"
] | stackoverflow_0074564853_kubernetes_logging_python.txt |
Q:
Turning keywords into lists in python dataframe columns
I've extracted key words from a different column to make a new column (hard skills) that looks like this:
(https://i.stack.imgur.com/XNOIK.png)
But I want to make each key word into a list format within the "hards skills" column.
For example, for the 1st row ... | Turning keywords into lists in python dataframe columns | I've extracted key words from a different column to make a new column (hard skills) that looks like this:
(https://i.stack.imgur.com/XNOIK.png)
But I want to make each key word into a list format within the "hards skills" column.
For example, for the 1st row of "hard skills" column, my desired outcome would be:
['Pytho... | [
"IIUC, there is no need for functions and/or loops here since you can use pandas.Series.str.join to get your expected column/output :\ncourse_name_skills[\"hard skills\"]= course_name_skills[\"skills\"].str.join(\",\")\n\nNB: The line above assumes that the column hard skills holds lists, otherwise (if strings) use... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074576129_dataframe_pandas_python.txt |
Q:
How to Plot Implicit Equation in Python
I want to Plot V(y axis) vs t(x axis) graph using the below equation at 5 different values of L(shown below)
L= [5,10,15,20,25]
b=0.0032
Equation, (b*V*0.277*t) - (b*L) = log(1+b*V*0.277*t)
code output will be as shown in figure
Expected Outcome
A:
While sympy exposes the ... | How to Plot Implicit Equation in Python | I want to Plot V(y axis) vs t(x axis) graph using the below equation at 5 different values of L(shown below)
L= [5,10,15,20,25]
b=0.0032
Equation, (b*V*0.277*t) - (b*L) = log(1+b*V*0.277*t)
code output will be as shown in figure
Expected Outcome
| [
"While sympy exposes the plot_implicit function, the results are far from good. We can use Numpy and Matplotlib to achieve our goal.\nThe basic idea is that your equation can be written as LHS - RHS = 0. So, we can create contour plots and select the level 0. But contour plots uses colormaps, so we will have to cre... | [
2
] | [] | [] | [
"equation",
"implicit",
"matplotlib",
"python",
"sympy"
] | stackoverflow_0074575607_equation_implicit_matplotlib_python_sympy.txt |
Q:
Acessing for loop varible in another python script
I have the file name as file1.py the code is following.
`
import os
global x
def a_function():
while True:
for x in range(12):
cmd=f'rosbag record -O /home/mubashir/catkin_ws/src/germany1_trush/rosbag/{x}.bag /web_cam --duration 5 '
... | Acessing for loop varible in another python script | I have the file name as file1.py the code is following.
`
import os
global x
def a_function():
while True:
for x in range(12):
cmd=f'rosbag record -O /home/mubashir/catkin_ws/src/germany1_trush/rosbag/{x}.bag /web_cam --duration 5 '
os.system(cmd)
a_function()
I want t... | [
"In order to correct this, add an if statement to check if the file1.py itself is being run. If it is, then __name__ should equal '__main__'.\nThe code that you want to be read by file2.py should be outside the if statement and all code that you want to execute only if file1.py is run should be inside the if statem... | [
0
] | [] | [] | [
"global",
"loops",
"module",
"python",
"scope"
] | stackoverflow_0074575586_global_loops_module_python_scope.txt |
Q:
Hiding axis text in matplotlib plots
I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of... | Hiding axis text in matplotlib plots | I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.
This may be vague, but the foll... | [
"Instead of hiding each element, you can hide the whole axis:\nframe1.axes.get_xaxis().set_visible(False)\nframe1.axes.get_yaxis().set_visible(False)\n\nOr, you can set the ticks to an empty list:\nframe1.axes.get_xaxis().set_ticks([])\nframe1.axes.get_yaxis().set_ticks([])\n\nIn this second option, you can still u... | [
625,
283,
211,
121,
85,
66,
18,
15,
3,
0
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0002176424_matplotlib_plot_python.txt |
Q:
How do I create and access variables algorithmically?
I'm trying to assign and reference variables algorithmically. See below:
varName = "a0"
value = 1
globals()[varName] = value
print(varName)
print(a0)
This returns:
a0
1
So, the variable varName is "a0", which is right. And the variable a0 is 1, which is a... | How do I create and access variables algorithmically? | I'm trying to assign and reference variables algorithmically. See below:
varName = "a0"
value = 1
globals()[varName] = value
print(varName)
print(a0)
This returns:
a0
1
So, the variable varName is "a0", which is right. And the variable a0 is 1, which is also right.
But I want varName to output 1 directly instead ... | [] | [] | [
"To get the value of varName you can use eval function.\nvarName = \"a0\"\nvalue = 1\n\nglobals()[varName] = value\n\n# eval function here\nprint(eval(varName))\nprint(a0)\n\nOutput:\n1\n1\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074576226_python.txt |
Q:
dask.distributed: handle serialization of exotic objects?
Context
I am trying to write a data pipeline using dask distributed and some legacy code from a previous project. get_data simply get url:str and session:ClientSession as arguments and return a pandas DataFrame.
from dask.distributed import Client
from aioh... | dask.distributed: handle serialization of exotic objects? | Context
I am trying to write a data pipeline using dask distributed and some legacy code from a previous project. get_data simply get url:str and session:ClientSession as arguments and return a pandas DataFrame.
from dask.distributed import Client
from aiohttp import ClientSession
client = Client()
session: ClientSessi... | [
"There is a far easier to get around this: create your sessions within the mapped function. You would have been recreating the sessions in each worker anyway, they cannot survive a transfer\nfrom dask.distributed import Client\nfrom aiohttp import ClientSession\nclient = Client()\n\ndef func(u):\n session: Clien... | [
1
] | [] | [] | [
"dask",
"dask_distributed",
"python",
"serialization"
] | stackoverflow_0074573626_dask_dask_distributed_python_serialization.txt |
Q:
How to normalise a date columnin pandas dataframe to the same format
I have a dataframe made from pulling in different excel sheets.
I am trying to normalise the date_time column to just a standard DD/MM/YYY format. Is that possible?
1
DATE
Column 3
Column 4
Column 5
Column 6
2
01/03/2021 00:00
3
01/03/2021 00:... | How to normalise a date columnin pandas dataframe to the same format | I have a dataframe made from pulling in different excel sheets.
I am trying to normalise the date_time column to just a standard DD/MM/YYY format. Is that possible?
1
DATE
Column 3
Column 4
Column 5
Column 6
2
01/03/2021 00:00
3
01/03/2021 00:00
4
01/03/2021 00:00
5
01/03/2021 00:00
6
01... | [
"# example df\ndf = pd.DataFrame({'DATE': ['01/03/2021 00:00', '01/03/2021 00:00', '01/03/2021 00:00', '01/03/2021 00:00', '01/03/2021 00:00', '11/24/2022', '11/24/2022', '11/24/2022', '11/24/2022', '11/24/2022']})\ndf['DATE'] = pd.to_datetime(df['DATE'])\ndf['DATE'] = df['DATE'].dt.strftime('%d/%m/%Y')\n\noutput:\... | [
1
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074576304_excel_pandas_python.txt |
Q:
Splitting arrays in Python
I have the following problem: I would like to find different "cuts" of the array into two different arrays by adding one element each time, for example:
If I have an array
a = [0,1,2,3]
The following splits are desired:
[0] [1,2,3]
[0,1] [2,3]
[0,1,2] [3]
In the past I had easier tas... | Splitting arrays in Python | I have the following problem: I would like to find different "cuts" of the array into two different arrays by adding one element each time, for example:
If I have an array
a = [0,1,2,3]
The following splits are desired:
[0] [1,2,3]
[0,1] [2,3]
[0,1,2] [3]
In the past I had easier tasks so np.split() function was qu... | [
"Use slicing, more details : Understanding slicing.\na = [0,1,2,3]\n\nfor i in range(len(a)-1):\n print(a[:i+1], a[i+1:])\n\nOutput:\n[0] [1, 2, 3]\n[0, 1] [2, 3]\n[0, 1, 2] [3]\n\n",
"Check this out:\na = [0,1,2,3]\n\nresult = [(a[:x], a[x:]) for x in range(1, len(a))]\n\nprint(result)\n# [([0], [1, 2, 3]), (... | [
2,
1
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074576364_arrays_python.txt |
Q:
the log in math library does not work for me
i have been trying to get log to work but it just doesnt get the same value as you would get with a calculator.
i tried these but none work; i want to calculate for example 600 log 600 but never has that actual value.
the only difference between the below codes is they ... | the log in math library does not work for me | i have been trying to get log to work but it just doesnt get the same value as you would get with a calculator.
i tried these but none work; i want to calculate for example 600 log 600 but never has that actual value.
the only difference between the below codes is they calulate worst_mergesort defferently:
rows * math.... | [
"I think the problem is simply that the base of the logarithm is different in math.log than in a calculator.\nmath.log computes the natural logarithm, so the base is e and the calculators usually use base 10 by default.\nIn math.log, you can specify the base as a second argument e.g. 600*math.log(600, 10) should g... | [
1
] | [] | [] | [
"logarithm",
"math",
"python"
] | stackoverflow_0074576392_logarithm_math_python.txt |
Q:
how to iterate through dictionary in a dictionary in django template?
My dictionary looks like this(Dictionary within a dictionary):
{'0': {
'chosen_unit': <Unit: Kg>,
'cost': Decimal('10.0000'),
'unit__name_abbrev': u'G',
'supplier__supplier': u"Steve's Meat Locker",
'price': Decimal('5.00'),
... | how to iterate through dictionary in a dictionary in django template? | My dictionary looks like this(Dictionary within a dictionary):
{'0': {
'chosen_unit': <Unit: Kg>,
'cost': Decimal('10.0000'),
'unit__name_abbrev': u'G',
'supplier__supplier': u"Steve's Meat Locker",
'price': Decimal('5.00'),
'supplier__address': u'No\r\naddress here',
'chosen_unit_amount': u... | [
"Lets say your data is -\ndata = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }\nYou can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.\n<table>\n <tr>\n ... | [
326,
4,
2,
0
] | [] | [] | [
"dictionary",
"django",
"django_templates",
"python"
] | stackoverflow_0008018973_dictionary_django_django_templates_python.txt |
Q:
Bound label to Image
From the mnist dataset example I know that the dataset look something like this (60000,28,28) and the labels are (60000,). When, I print the first three examples of Mnist dataset
and I print the first three labels of those which are:
The images and labels are bounded.
I want to know how can ... | Bound label to Image | From the mnist dataset example I know that the dataset look something like this (60000,28,28) and the labels are (60000,). When, I print the first three examples of Mnist dataset
and I print the first three labels of those which are:
The images and labels are bounded.
I want to know how can I bound a folder with (120... | [
"Here's a rough sketch of how you can approach this problem.\nLoading each image\nThe first step is how you pre-process each image. You can use Python Imaging Library for this.\nExample:\nfrom PIL import Image\n\ndef load_image(path):\n image = Image.open(path)\n # Images can be in one of several different mo... | [
0
] | [] | [] | [
"deep_learning",
"mnist",
"neural_network",
"python"
] | stackoverflow_0074572024_deep_learning_mnist_neural_network_python.txt |
Q:
Cannot import settings module in python
I'm trying to use settings module but is shows "ModuleNotFoundError: No module named 'settings'" and whien I try to install the module it shows "Requirement already satisfied: python-settings in c:\users\harsh\appdata\local\programs\python\python310\lib\site-packages (0.2.2)... | Cannot import settings module in python | I'm trying to use settings module but is shows "ModuleNotFoundError: No module named 'settings'" and whien I try to install the module it shows "Requirement already satisfied: python-settings in c:\users\harsh\appdata\local\programs\python\python310\lib\site-packages (0.2.2)"
import settings
import settings module
| [
"try\npip install python-settings\nto import\nfrom python_settings import settings\n",
"If you have Visual Studio, you can create a Python environment (just right-click on it, choose \"add environment\" and set your python version) in \"solution explorer\" and then right-click on your new Python environment and ... | [
1,
0
] | [] | [] | [
"python",
"python_module"
] | stackoverflow_0074576312_python_python_module.txt |
Q:
How to scrape multiple tables with same name?
I am trying to scrape a site where the table classes have the same name.
There are 3 types of tables and I want to get the headers just once then get all the information from all three tables into a xlsx file.
Website = https://wiki.warthunder.com/List_of_vehicle_battl... | How to scrape multiple tables with same name? | I am trying to scrape a site where the table classes have the same name.
There are 3 types of tables and I want to get the headers just once then get all the information from all three tables into a xlsx file.
Website = https://wiki.warthunder.com/List_of_vehicle_battle_ratings
running the code with vehical = soup.find... | [
"Make it more simple, since you already involve pandas - This wil pd.read_html() all tables in a list an pd.concat() them to a single one:\npd.concat(\n pd.read_html(\n 'https://wiki.warthunder.com/List_of_vehicle_battle_ratings',\n attrs={'class':'wikitable'}\n ),\n ignore_index=True\n).to_e... | [
1
] | [] | [] | [
"beautifulsoup",
"dataframe",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074576236_beautifulsoup_dataframe_pandas_python_web_scraping.txt |
Q:
Converting shellcode hex bytes to text based inputs in Python for an unknown byte value '\x87'? Not a UTF-8 string?
So I am currently doing a beginner CTF challengeon pwnable.tw, the "start" challenge specifically. After reversing the challenge binary I found out there was a buffer overflow exploit, and one thing ... | Converting shellcode hex bytes to text based inputs in Python for an unknown byte value '\x87'? Not a UTF-8 string? | So I am currently doing a beginner CTF challengeon pwnable.tw, the "start" challenge specifically. After reversing the challenge binary I found out there was a buffer overflow exploit, and one thing I would have to do to get an ideal starting point would be to leak the stack address by pointing it back to a specific ad... | [
"So I ended up finding the answer, it was to use sys.stdout.buffer.write(), rather than print or sys.stdout.write() since sys.stdout.buffer.write() uses a BufferedWriter which simply operates on raw bytes rather than the other two which operate on text/strings. Thank you to everyone in the comments who helped me!\n... | [
0
] | [] | [] | [
"buffer_overflow",
"exploit",
"python",
"shellcode",
"x86"
] | stackoverflow_0074554479_buffer_overflow_exploit_python_shellcode_x86.txt |
Q:
How to read names in file upto specific character using Python
Group Name: grp1
name1
name2
name3
===============
Group Name: grp2
NAME4
NAME5
NAME6
NAME7
===============
and so on....
mainfile.txt will have above content, here i need to create lists with group names and each list will have its content which ... | How to read names in file upto specific character using Python | Group Name: grp1
name1
name2
name3
===============
Group Name: grp2
NAME4
NAME5
NAME6
NAME7
===============
and so on....
mainfile.txt will have above content, here i need to create lists with group names and each list will have its content which is present up to "=========" symbol.
For Eg: as per above file conte... | [
"You can iterate on your file line by line like and check if the content is equal to the separator. This would give you something like this:\nfile = open(\"myfile.txt\", \"r+\")\nline = file.readline()\ngroups = []\n\nwhile line:\n group = []\n while line and line != \"===============\":\n group.append... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074576454_python_python_3.x.txt |
Q:
jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}' in html
i'm trying to make an if into my code html with flask:
{% if {{ role }} = 1 %}
<div id="cabecera">
<header class="py-3 mb-4 border-bottom">
<div class="container d-flex flex-wrap justify-c... | jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}' in html | i'm trying to make an if into my code html with flask:
{% if {{ role }} = 1 %}
<div id="cabecera">
<header class="py-3 mb-4 border-bottom">
<div class="container d-flex flex-wrap justify-content-center">
<a href="/home" class="d-flex align-items-ce... | [
"You don't need the {{ }} to refer to variables inside Jinja statements. See here.\nSo provided you have passed a variable role to the template the following will work:\n{% if role == 1 %}\n <div id=\"cabecera\">\n etc...\n{% endif %}\n\n",
"Try this:\n{% if role == 1 %}\n <div id=\"cabecera\">\n ... | [
1,
0
] | [] | [] | [
"css",
"flask",
"html",
"mysql",
"python"
] | stackoverflow_0074576569_css_flask_html_mysql_python.txt |
Q:
replacing a value from df1['colA'] with df2['ColB'] using a unique identifier?
Hi I am trying to replace values in a df1 column A with values from df2 column B, by matching them with df2 column A. Basically if the string of row x in df1['a'] is equal to a string of row y in df2['a'] I want to replace the value of... | replacing a value from df1['colA'] with df2['ColB'] using a unique identifier? | Hi I am trying to replace values in a df1 column A with values from df2 column B, by matching them with df2 column A. Basically if the string of row x in df1['a'] is equal to a string of row y in df2['a'] I want to replace the value of df1['a'] with df2['b']. I have tried a couple things but for some reason this isn't... | [
"I think the explanation is not quite correct. Based on your code attempt, I suspect that what you mean is:\n\nFor each row i of df1 that matches (for all fields (a, b, c)) a row j of df2, then replace df1.loc[i, 'a'] by df2.loc[j, 'c'].\n\nIf that is the correct interpretation of your question, then:\nFirst, it is... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074575994_dataframe_pandas_python.txt |
Q:
I have a data frame with Few columns and want sum of rows of a specific column with +1 row
Input DF:
Column A
Column B
AA
24
BB
37
CC
59
Desired Output Dataframe:
Column A
Column B
Result
AA
24
24
BB
37
61
CC
59
120
What I want is result column should have 24 in first row,
24+37 in 2nd row ,24+37+59 in 3... | I have a data frame with Few columns and want sum of rows of a specific column with +1 row | Input DF:
Column A
Column B
AA
24
BB
37
CC
59
Desired Output Dataframe:
Column A
Column B
Result
AA
24
24
BB
37
61
CC
59
120
What I want is result column should have 24 in first row,
24+37 in 2nd row ,24+37+59 in 3rd row and so on.
Kindly help
I am a beginner and was trying to solve this... | [
"You can use pandas.Series.cumsum :\ndf[\"Column C\"]= df[\"Column B\"].cumsum()\n\n# Output :\nprint(df)\n\n Column A Column B Column C\n0 AA 24 24\n1 BB 37 61\n2 CC 59 120\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"row"
] | stackoverflow_0074576611_dataframe_pandas_python_row.txt |
Q:
Compare elements in lists on 1 column rows and assign unique values in new column, Pandas
I would like to compare elements in lists in 1 column and assign unique values that are on no other row in new column in the same Pandas df:
Int.:
data = {'object_1':[1, 3, 4, 5, 77],
'object_2':[1, 5, 100, 3, 4],
"object_3":... | Compare elements in lists on 1 column rows and assign unique values in new column, Pandas | I would like to compare elements in lists in 1 column and assign unique values that are on no other row in new column in the same Pandas df:
Int.:
data = {'object_1':[1, 3, 4, 5, 77],
'object_2':[1, 5, 100, 3, 4],
"object_3": [1, 3, 4, 5, 5],
"object_4": [1, 3, 5, 47, 48]}
Out.:
data = {'object_1':[1, 3, 4, 5, 77],
'o... | [
"You can use isin and stack:\ndata['unique_values'] = ([df.loc[~df[col].isin(df.set_index(col).stack()), col].tolist()\n for col in df.columns])\n\ndata:\n{'object_1': [1, 3, 4, 5, 77],\n 'object_2': [1, 5, 100, 3, 4],\n 'object_3': [1, 3, 4, 5, 5],\n 'object_4': [1, 3, 5, 47, 48],\n 'unique_value... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074576366_pandas_python.txt |
Q:
How to create a new column with how many times a value in another variable repeats in python
I am trying to create a new column in a dataframe in which I can count how many times a value in another variables. I want my outcome to be like the column "count"
Product
Count
Apple
3
orange
2
Apple
3
orange
2
Appl... | How to create a new column with how many times a value in another variable repeats in python | I am trying to create a new column in a dataframe in which I can count how many times a value in another variables. I want my outcome to be like the column "count"
Product
Count
Apple
3
orange
2
Apple
3
orange
2
Apple
3
Pear
1
I have tried the following:
df['Prodct'].value_counts()
Hence, I have t... | [
"Is this what you're trying to achieve?\nimport pandas as pd\nimport numpy as np\nimport random\n\nfruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Mango']\n\n# bootstrap fruits\nsamples = np.random.choice(fruits, size=100, replace=True)\n\ndf = pd.DataFrame({'fruit': samples})\n\nprint(df.head())\n\ncount_dict = df... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074576265_dataframe_pandas_python.txt |
Q:
Avoid df.iterrow to drop dataframe rows within certain conditions
I have a dataframe similar to this:
import pandas as pd
colA = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c']
colB = [(21,1,2), (0,1,21), (2,1,21), (1,12,5), (21,1,0), (12,5,6), (18,7,14), (7,5,12), (14,7,18), (12,7,11), (11,7,12), (3... | Avoid df.iterrow to drop dataframe rows within certain conditions | I have a dataframe similar to this:
import pandas as pd
colA = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c']
colB = [(21,1,2), (0,1,21), (2,1,21), (1,12,5), (21,1,0), (12,5,6), (18,7,14), (7,5,12), (14,7,18), (12,7,11), (11,7,12), (3,5,7)]
df = pd.DataFrame(list(zip(colA, colB)), columns = ['colA', 'col... | [
"Try this:\ndf.groupby(['colA',df['colB'].map(lambda x: frozenset((x[0],x[-1])))],as_index=False).first()\n\nThis solution creates a frozenset, or an immutable set that can be used as a groupby key. This, along with colA is used to get the first value of each group. We are only using the first and last value in col... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074575790_dataframe_pandas_python.txt |
Q:
Github action to execute a Python script that create a file, then commit and push this file
My repo contains a main.py that generates a html map and save results in a csv. I want the action to:
execute the python script (-> this seems to be ok)
that the file generated would then be in the repo, hence having the f... | Github action to execute a Python script that create a file, then commit and push this file | My repo contains a main.py that generates a html map and save results in a csv. I want the action to:
execute the python script (-> this seems to be ok)
that the file generated would then be in the repo, hence having the file generated to be added, commited and pushed to the main branch to be available in the page ass... | [
"If you want to run a script, then you don't need an additional checkout step for that. There is a difference between steps that use workflows and those that execute shell scripts directly. You can read more about it here.\nIn your configuration file, you kind of mix the two in the last step. You don't need an addi... | [
3
] | [] | [] | [
"github_actions",
"python"
] | stackoverflow_0074575744_github_actions_python.txt |
Q:
Random Forest Classifier: Set feature importances?
On a RFC model, I am trying to figure out how the feature importances change my classification when i am perturbing my data, like
features(no perturbation)= features(perturbed data)-features(perturbation)
Then using the features(no perturbation) on my already fit ... | Random Forest Classifier: Set feature importances? | On a RFC model, I am trying to figure out how the feature importances change my classification when i am perturbing my data, like
features(no perturbation)= features(perturbed data)-features(perturbation)
Then using the features(no perturbation) on my already fit model.
Do you if it is possible to manually set or chang... | [
"The general convention in scikit-learn code is that attributes that are inferred from your data / training end with _. feature_importances_ attributes respects that convention as well. They represent impurity-based importances and they are computed / inferred from your training set statistics.\nYou have the option... | [
0
] | [] | [] | [
"machine_learning",
"python",
"random_forest",
"scikit_learn"
] | stackoverflow_0074575103_machine_learning_python_random_forest_scikit_learn.txt |
Q:
ERROR: Could not find a version that satisfies the requirement setuptools_scm<3,>=4.1.2
I'm trying to install djangular-serve in my project but I'm unsure what version of setuptools_Scm it's asking for.
Using cached djangular-serve-2.1.0.tar.gz (34 kB)
Installing build dependencies ... error
error: subproces... | ERROR: Could not find a version that satisfies the requirement setuptools_scm<3,>=4.1.2 | I'm trying to install djangular-serve in my project but I'm unsure what version of setuptools_Scm it's asking for.
Using cached djangular-serve-2.1.0.tar.gz (34 kB)
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfull... | [
"This is a bug in djangular-serve in pyproject.toml. Please report the bug. The fact that nobody reported the bug in two years suggests the package is not very popular among users.\n"
] | [
0
] | [] | [] | [
"django",
"djangular",
"pip",
"python"
] | stackoverflow_0074576627_django_djangular_pip_python.txt |
Q:
If loop in queue keeps repeating
# creating menu
def menu():
print("What do you want to do:")
print("1)Push")
print("2)Pop")
print("3)Display")
print("4)Quit")
choice = int(input("Make a selection: "))
return choice
# creating a queue with a list
def create_queue():
# creating a q... | If loop in queue keeps repeating | # creating menu
def menu():
print("What do you want to do:")
print("1)Push")
print("2)Pop")
print("3)Display")
print("4)Quit")
choice = int(input("Make a selection: "))
return choice
# creating a queue with a list
def create_queue():
# creating a queue
queue = []
while menu() ... | [
"In your code, you are calling the 'menu()' function multiple times.\nwhile menu() > 0 & menu() < 5:\n if menu() == 1:\n\nSave it in a variable:\nchoice = None\nwhile choice > 0 and choice < 5:\n choice = menu()\n if choice == 1:\n# Etc.\n\nHope this resolves your issue!\n"
] | [
0
] | [] | [] | [
"data_structures",
"loops",
"python",
"queue"
] | stackoverflow_0074576720_data_structures_loops_python_queue.txt |
Q:
Edit Discord message with the before content replaced
I'm currently developing a Discord bot with discord.py. I made a command named underscored and the goal is to edit each message the bot sends with just replacing the spaces by underscores. Here's an example:
User: /test
Bot: This is a test command.
User: /under... | Edit Discord message with the before content replaced | I'm currently developing a Discord bot with discord.py. I made a command named underscored and the goal is to edit each message the bot sends with just replacing the spaces by underscores. Here's an example:
User: /test
Bot: This is a test command.
User: /underscored
User: /test
Bot: This_is_a_test_command.
So here's ... | [
"You get that error because on_message event takes only one argument, which is the message (discord.Message class). You can refere the documentation here\nYou will have to implement it to every command manually, instead of using the on_message event\n# global variable that can be accessed by every command\nundersco... | [
1
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0074531641_bots_discord_discord.py_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.