question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
64,084,786
2020-9-27
https://stackoverflow.com/questions/64084786/read-data-from-a-pandas-dataframe-and-create-a-tree-using-anytree-in-python
Is there a way to read data from a pandas DataFrame and construct a tree using anytree? Parent Child A A1 A A2 A2 A21 I can do it with static values as follows. However, I want to automate this by reading the data from a pandas DataFrame with anytree. >>> from anytree import Node, RenderTree >>> A = Node("A") >>> A1 =...
Create nodes first if not exist, store their references in a dictionary nodes for further usage. Change parent when necessary for children. We can derive roots of the forest of trees by seeing what Parent values are not in Child values, since a parent is not a children of any node it won't appear in Child column. def a...
13
9
64,082,036
2020-9-26
https://stackoverflow.com/questions/64082036/arrays-into-pandas-dataframe-columns
I have a program that outputs arrays. For example: [[0, 1, 0], [0, 0, 0], [1, 3, 3], [2, 4, 4]] I would like to turn these arrays into a dataframe using pandas. However, when I do the values become row values like this: As you can see each array within the overall array becomes its own row. I would like each array wi...
A possible solution could be transposing and renaming the columns after transforming the numpy array into a dataframe. Here is the code: import numpy as np import pandas as pd frame = [[0, 1, 0], [0, 0, 0], [1, 3, 3], [2, 4, 4]] numpy_data= np.array(frame) #transposing later df = pd.DataFrame(data=numpy_data).T #creati...
8
5
64,076,149
2020-9-26
https://stackoverflow.com/questions/64076149/plotly-how-to-create-an-odd-number-of-subplots
I want the 5th subplot to be in the centre of the two columns in the third row. (I have tried doing that by adding the domain argument). Here is the code to reproduce it- import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots continent_df = pd.read_csv('https://raw.githubusercon...
You can achieve this through a correct setup of domain. Here's an example that will have a figure in each of the four corners and one figure in the middle. Plot Complete code: import plotly import plotly.offline as py import plotly.graph_objs as go labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen'] values = [4...
7
6
64,079,000
2020-9-26
https://stackoverflow.com/questions/64079000/groupby-in-reverse
I have a pandas dataframe with name of variables, the values for each and the count (which shows the frequency of that row): df = pd.DataFrame({'var':['A', 'B', 'C'], 'value':[10, 20, 30], 'count':[1,2,3]}) var value count A 10 1 B 20 2 C 30 3 I want to use count to get an output like this: var value A 10 B 20 B 20 C ...
You can use index.repeat: i = df.index.repeat(df['count']) d = df.loc[i, :'value'].reset_index(drop=True) var value 0 A 10 1 B 20 2 B 20 3 C 30 4 C 30 5 C 30
8
7
64,074,217
2020-9-26
https://stackoverflow.com/questions/64074217/finplot-as-a-widget-in-layout
I am trying to add finplot, https://pypi.org/project/finplot/, as a widget to one of the layouts in my UI. I created a widget for finplot and added it to the widgets in the layout but I get the following error: self.tab1.layout.addWidget(self.tab1.fplt_widget) TypeError: addWidget(self, QWidget, stretch: int = 0, align...
The create_plot_widget() function creates a PlotItem that cannot be added to a layout, the solution is to use some QWidget that can display the content of the PlotItem as the PlotWidget: import pyqtgraph as pg # ... self.tab1.df = yfinance.download("AAPL") self.tab1.fplt_widget = pg.PlotWidget( plotItem=fplt.create_plo...
9
6
64,067,519
2020-9-25
https://stackoverflow.com/questions/64067519/how-to-create-a-min-max-lineplot-by-month
I have retail beef ad counts time series data, and I intend to make stacked line chart aim to show On a three-week average basis, quantity of average ads that grocers posted per store last week. To do so, I managed to aggregate data for plotting and tried to make line chart that I want. The main motivation is based on ...
Also see How to create a min-max plot by month with fill_between? See in-line comments for details import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import calendar ################################################################# # setup from question url = 'https://gist.githubusercontent.com...
6
6
64,070,651
2020-9-25
https://stackoverflow.com/questions/64070651/argparse-optional-argument-between-positional-arguments
I want to emulate the behavior of most command-line utilities, where optional arguments can be put anywhere in the command line, including between positional arguments, such as in this mkdir example: mkdir before --mode 077 after In this case, we know that --mode takes exactly 1 argument, so before and after are both ...
Starting from Python 3.7, it seems argparse now supports this kind of Unix-style parsing: Intermixed parsing ArgumentParser.parse_intermixed_args(args=None, namespace=None) A number of Unix commands allow the user to intermix optional arguments with positional arguments. The parse_intermixed_args() and parse_known_int...
7
6
64,070,128
2020-9-25
https://stackoverflow.com/questions/64070128/zen-of-python-explicit-is-better-than-implicit
I'm trying to understand what 'implicit' and 'explicit' really means in the context of Python. a = [] # my understanding is that this is implicit if not a: print("list is empty") # my understanding is that this is explicit if len(a) == 0: print("list is empty") I'm trying to follow the Zen of Python rules, but I'm cur...
The two statements have very different semantics. Remember that Python is dynamically typed. For the case where a = [], both not a and len(a) == 0 are equivalent. A valid alternative might be to check not len(a). In some cases, you may even want to check for both emptiness and listness by doing a == []. But a can be an...
14
15
64,068,659
2020-9-25
https://stackoverflow.com/questions/64068659/bar-chart-in-matplotlib-using-a-colormap
I have a df with two columns: y: different numeric values for the y axis days: the names of four different days (Monday, Tuesday, Wednesday, Thursday) I also have a colormap with four different colors that I made myself and it's a ListedColorMap object. I want to create a bar chart with the four categories (days of t...
Okay, I found a way to do this without having to scale my values: def my_barchart(my_df, my_cmap): fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.bar(my_df['days'], my_df['y'], color=my_cmap.colors) return fig Simply adding .colors after my_cmap works!
22
15
64,061,721
2020-9-25
https://stackoverflow.com/questions/64061721/opencv-to-close-the-window-on-a-specific-key
It seems really simple, but I can't get it to work and the couldn't find any questions regarding this particular issue (if there are, please point out in the comments). I am showing an image and want the window to close on a specific key, but strangely, any key causes it to close. This is my simple code for testing: im...
From my point of view, your program just terminates, and thus all windows are implicitly closed, regardless of which key you press. One idea might be to put a while True loop around the reading and checking of the pressed key: import cv2 img = cv2.imread('path/to/your/image.png') cv2.imshow('My Image', img) while True:...
9
8
64,061,426
2020-9-25
https://stackoverflow.com/questions/64061426/is-there-a-command-to-exit-a-module-when-imported-like-return-for-a-function
When you import a module in python, the module code is "run". Sometimes it is useful to have branching logic in the module such as checking package versions or platform or whatever. Is there a way to exit the entire module execution before hitting the end of the file, something equivalent to early return in a function?...
You can create a custom Loader that special-cases e.g. ImportError (1) as a shortcut to stop module execution. This can be registered via a custom Finder at sys.meta_path. So if you have the following module to be imported: # foo.py x = 1 raise ImportError # stop module execution here y = 2 You can use the following f...
9
2
64,057,445
2020-9-25
https://stackoverflow.com/questions/64057445/fastapi-post-does-not-recognize-my-parameter
I am usually using Tornado, and trying to migrate to FastAPI. Let's say, I have a very basic API as follows: @app.post("/add_data") async def add_data(data): return data When I am running the following Curl request: curl http://127.0.0.1:8000/add_data -d 'data=Hello' I am getting the following error: {"detail":[{"loc"...
Since you are sending a string data, you have to specify that in the router function with typing as from pydantic import BaseModel class Payload(BaseModel): data: str = "" @app.post("/add_data") async def add_data(payload: Payload = None): return payload Example cURL request will be in the form, curl -X POST "http://0....
13
11
64,055,314
2020-9-24
https://stackoverflow.com/questions/64055314/why-cant-pythons-walrus-operator-be-used-to-set-instance-attributes
I just learned that the new walrus operator (:=) can't be used to set instance attributes, it's supposedly invalid syntax (raises a SyntaxError). Why is this? (And can you provide a link to official docs mentioning this?) I looked through PEP 572, and couldn't find if/where this is documented. Research This answer men...
PEP 572 describes the purpose of this (emphasis mine): This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr. self.foo isn't a variable, it's an attribute of an object. The Syntax and semantics section specifies it further: NAME is an identifier. self.foo ...
17
23
64,053,954
2020-9-24
https://stackoverflow.com/questions/64053954/pad-rows-on-a-pandas-dataframe-with-zeros-till-n-count
Iam loading data via pandas read_csv like so: data = pd.read_csv(file_name_item, sep=" ", header=None, usecols=[0,1,2]) which looks like so: 0 1 2 0 257 503 48 1 167 258 39 2 172 242 39 3 172 403 81 4 180 228 39 5 183 394 255 6 192 179 15 7 192 347 234 8 192 380 243 9 192 437 135 10 211 358 234 I would like to pad t...
reindex with fill_value df_final = data.reindex(range(257), fill_value=0) Out[1845]: 0 1 2 0 257 503 48 1 167 258 39 2 172 242 39 3 172 403 81 4 180 228 39 .. ... ... .. 252 0 0 0 253 0 0 0 254 0 0 0 255 0 0 0 256 0 0 0 [257 rows x 3 columns]
6
8
64,032,271
2020-9-23
https://stackoverflow.com/questions/64032271/handling-accept-cookies-popup-with-selenium-in-python
I've been trying to scrape some information of this real estate website with selenium. However when I access the website I need to accept cookies to continue. This only happens when the bot accesses the website, not when I do it manually. When I try to find the corresponding element either by xpath or id, as I find it ...
You were very close! If you open your page in a new browser you'll note the page fully loads, then, a moment later your popup appears. The default wait strategy in selenium is just that the page is loaded. That draw delay between page loaded and display appearing is causing your scripts to fail. You have two good synch...
30
21
64,048,813
2020-9-24
https://stackoverflow.com/questions/64048813/what-shebang-should-i-use-to-consistently-point-to-python3
I have a script which uses the shebang #!/usr/bin/env python. It works great on machines where Python 3 is the only version available, but on the machines which have both Python 2 and Python 3, it runs the script with Python 2. If I modify the shebang to be #!/usr/bin/env python3, it would work on the machines with Pyt...
Unfortunately, there is no universally working way of doing this that would work across any and all up front unknown Linux hosts and you are largely left at the mercy of distro maintainers and local host configuration. alias won't help, because interpreter specified by #! handled by the kernel and /usr/bin/env it will ...
10
6
64,038,673
2020-9-24
https://stackoverflow.com/questions/64038673/could-not-build-wheels-for-which-use-pep-517-and-cannot-be-installed-directly
I am trying to install a package which uses PEP 517. The newest version of Pip won't allow me to install it due to an error involving building wheels for PEP 517. In the past, I've solved this issue by downgrading Pip, installing the package and upgrading Pip back to the latest version. However, after I downgrade pip i...
The easiest solution to deal with the error "Could not build wheels for ____ which use PEP 517 and cannot be installed directly" is the following: sudo pip3 install _____ --no-binary :all: Where ____ is obviously the name of the library you want to install.
67
26
64,020,570
2020-9-23
https://stackoverflow.com/questions/64020570/why-redis-zset-means-sorted-set
When I was studying Redis for my database, I learned that 'Zset' means 'Sorted Set'. What does 'Zset' actually stand for? I couldn't figure out why it also means 'Sorted Set'. It could be simple or too broad question, but I want to understand exactly what I learned.
A similar question is asked before on Redis's github page and the creator of Redis answered it Hello. Z is as in XYZ, so the idea is, sets with another dimension: the order. It's a far association... I know :) Set commands start with s Hash commands start with h List commands start with l Sorted set commands start w...
14
27
64,019,287
2020-9-23
https://stackoverflow.com/questions/64019287/why-doesnt-small-integer-caching-seem-to-work-with-int-objects-from-the-round
Can you please explain why this happens in Python v3.8? a=round(2.3) b=round(2.4) print(a,b) print(type(a),type(b)) print(a is b) print(id(a)) print(id(b)) Output: 2 2 <class 'int'> <class 'int'> False 2406701496848 2406701496656 >>> 2 is within the range of the small integer caching. So why are there different objec...
Looks like in 3.8, PyLong_FromDouble (which is what float.__round__ ultimately delegates to) explicitly allocates a new PyLong object and fills it in manually, without normalizing it (via the IS_SMALL_INT check and get_small_int cache lookup function), so it doesn't check the small int cache to resolve to the canonical...
8
9
63,988,804
2020-9-21
https://stackoverflow.com/questions/63988804/how-to-infer-frequency-from-an-index-where-a-few-observations-are-missing
Using pd.date_range like dr = pd.date_range('2020', freq='15min', periods=n_obs) will produce this DateTimeIndex with a 15 minute interval or frequency: DatetimeIndex(['2020-01-01 00:00:00', '2020-01-01 00:15:00', '2020-01-01 00:30:00', '2020-01-01 00:45:00', '2020-01-01 01:00:00'], dtype='datetime64[ns]', freq='15T') ...
You could compute the minimum time difference of values in the index (here min_delta), try to find 3 consecutive values in the index, each with this minimum time difference between them, and then call infer_freq on these consecutive values of the index: diffs = (df.index[1:] - df.index[:-1]) min_delta = diffs.min() mas...
8
4
63,996,623
2020-9-21
https://stackoverflow.com/questions/63996623/no-module-named-ctypes
I'm trying to install pyautogui, but pip keeps throwing errors. How to fix it? I've tried installing libffi library. Here is some code: python3 -m pip install pyautogui Defaulting to user installation because normal site-packages is not writeable Collecting pyautogui Using cached PyAutoGUI-0.9.50.tar.gz (57 kB) ERROR: ...
Required Install foreign function interface headers sudo apt install libffi-dev Reinstall Python Substitute desired python version Ubuntu sudo add-apt-repository ppa:deadsnakes/ppa -y && sudo apt install --reinstall python3.9-distutils MacOS Use brew install python3.9 or port install python3.9 (I recommend port) Window...
8
6
63,989,328
2020-9-21
https://stackoverflow.com/questions/63989328/can-i-combine-conv2d-and-leakyrelu-into-a-single-layer
The keras Conv2D layer does not come with an activation function itself. I am currently rebuilding the YOLOv1 model for practicing. In the YOLOv1 model, there are several Conv2D layers followed by activations using the leaky relu function. Is there a way to combine from keras.layers import Conv2D, LeakyReLU ... def mod...
You can just pass it as an activation: X = Conv2D(filters, kernel_size, activation=LeakyReLU())(X)
6
11
64,002,627
2020-9-22
https://stackoverflow.com/questions/64002627/python-tenacity-log-exception-on-retry
I'm using the tenacity package to retry a function. My retry decorator looks like this: @retry(wait=wait_exponential(multiplier=1/(2**5), max=60), after=after_log(logger, logging.INFO)) On exception I get a logging message like this: INFO:mymodule:Finished call to 'mymodule.MyClass.myfunction' after 0.001(s), this was...
You can set the before_sleep parameter. This callable receives the exc_info thrown by your code. Ref.: https://tenacity.readthedocs.io/en/latest/api.html#module-tenacity.before_sleep Example import logging from typing import Final from tenacity import ( after_log, before_sleep_log, retry, retry_if_exception_type, stop_...
6
7
63,963,532
2020-9-18
https://stackoverflow.com/questions/63963532/how-to-copy-gym-environment
Info: I am using OpenAI Gym to create RL environments but need multiple copies of an environment for something I am doing. I do not want to do anything like [gym.make(...) for i in range(2)] to make a new environment. Question: Given one gym env what is the best way to make a copy of it so that you have 2 duplicate but...
Astariul has an updated answer:: Their answer states: import copy env_2 = copy.deepcopy(env) For more info about 'copy.deepcopy', and the copy library Link to copy library documentation
8
3
63,979,540
2020-9-20
https://stackoverflow.com/questions/63979540/python-how-to-filter-specific-warning
How to filter the specific warning for specific module in python? MWE ERROR: cross_val_score(model, df_Xtrain,ytrain,cv=2,scoring='r2') /usr/local/lib/python3.6/dist-packages/sklearn/linear_model/_ridge.py:148: LinAlgWarning: Ill-conditioned matrix (rcond=3.275e-20): result may not be accurate. overwrite_a=True).T My ...
You have to pass category as a WarningClass not in a String: from scipy.linalg import LinAlgWarning warnings.filterwarnings(action='ignore', category=LinAlgWarning, module='sklearn')
12
15
63,968,710
2020-9-19
https://stackoverflow.com/questions/63968710/python-ctypes-and-mutability
I noticed that passing Python objects to native code with ctypes can break mutability expectations. For example, if I have a C function like: int print_and_mutate(char *str) { str[0] = 'X'; return printf("%s\n", str); } and I call it like this: from ctypes import * lib = cdll.LoadLibrary("foo.so") s = b"asdf" lib.prin...
Python makes assumptions about immutable objects, so mutating them will definitely break things. Here's a concrete example: >>> import ctypes as c >>> x = b'abc' # immutable string >>> d = {x:123} # Used as key in dictionary (keys must be hashable/immutable) >>> d {b'abc': 123} Now build a ctypes mutable buffer to the...
7
5
63,995,578
2020-9-21
https://stackoverflow.com/questions/63995578/change-colour-of-colorbar-in-python-matplotlib
I have a code that gives me a scatter plot of predicted vs actual values as a function of concentration. The data is pulled from an excel csv spreadsheet. This is the code: import matplotlib.pyplot as plt from numpy import loadtxt dataset = loadtxt("ColorPlot.csv", delimiter=',') x = dataset[:,0] y = dataset[:,1] z = d...
To get the right color bar, use the following code: colormap = plt.cm.get_cmap('plasma') # 'plasma' or 'viridis' colors = colormap(scaled_z) sc = plt.scatter(x, y, c=colors) sm = plt.cm.ScalarMappable(cmap=colormap) sm.set_clim(vmin=0, vmax=100) plt.colorbar(sm) plt.xlabel("Actual") plt.ylabel("Predicted") plt.show() ...
9
11
63,964,011
2020-9-18
https://stackoverflow.com/questions/63964011/precise-specification-of-await
The Python Language Reference specifies object.__await__ as follows: object.__await__(self) Must return an iterator. Should be used to implement awaitable objects. For instance, asyncio.Future implements this method to be compatible with the await expression. That's it. I find this specification very vague and not ve...
The language doesn't care which iterator you return. The error comes from a library, asyncio, which has specific ideas about the kind of values that must be produced by the iterator. Asyncio requires __await__ to produce asyncio futures (including their subtypes such as tasks) or None. Other libraries, like curio and t...
22
24
63,949,240
2020-9-18
https://stackoverflow.com/questions/63949240/python-global-variable-in-fastapi-not-working-as-normal
I have a simple FastAPI demo app which achieve a function: get different response json by calling a post api named changeResponse. The changeResponse api just changed a global variable, another api return different response through the same global variable. On local env, it works correctly, but the response always chan...
tiangolo/uvicorn-gunicorn-fastapi is based on uvicorn-gunicorn-docker image, which by defaults creates multiple workers. Excerpt from gunicorn_conf.py: default_web_concurrency = workers_per_core * cores Thus, the described situation arises because the request is processed by different workers (processes). Each of which...
12
11
63,975,284
2020-9-20
https://stackoverflow.com/questions/63975284/mt5-metatrader-5-connect-to-different-mt5-terminals-using-python
I've got multiple python programs that connect to Mt5 terminal using the following code. # Establish connection to the MetaTrader 5 terminal if not mt5.initialize("C:\\Program Files\\ICMarkets - MetaTrader 5 - 01\\terminal64.exe"): print("initialize() failed, error code =", mt5.last_error()) quit() The python module f...
From my experience, imho, the MT5 python API was not designed to handle multiple connections from the same machine simultaneously. I have overcome this by creating Virtual Machines and running everything through them. I used Oracle VM because it's free, I had past experience with it, but its not very good at sharing re...
6
3
64,010,263
2020-9-22
https://stackoverflow.com/questions/64010263/attributeerror-module-importlib-has-no-attribute-util
I've just upgraded from Fedora 32 to Fedora 33 (which comes with Python 3.9). Since then gcloud command stopped working: [guy@Gandalf32 ~]$ gcloud Error processing line 3 of /home/guy/.local/lib/python3.9/site-packages/XStatic-1.0.2-py3.9-nspkg.pth: Traceback (most recent call last): File "/usr/lib64/python3.9/site.py"...
Update from GCP support GCP support mentioned that the new version 318.0.0 released on 2020.11.10 should support python 3.9 I updated my gcloud sdk to 318.0.0 and now looks like python 3.9.0 is supported. To fix this issue run gcloud components update Fedora 33 includes python 2.7 and to force GCloud SDK to use it plea...
98
118
63,939,138
2020-9-17
https://stackoverflow.com/questions/63939138/is-there-a-way-to-use-python-3-9-type-hinting-in-its-previous-versions
In Python 3.9 we can use type hinting in a lowercase built-in fashion (without having to import type signatures from the typing module) as described here: def greet_all(names: list[str]) -> None: for name in names: print("Hello", name) I like very much this idea and I would like to know if it is possible to use this w...
Simply, import annotations from __future__ and you should be good to go. from __future__ import annotations import sys !$sys.executable -V #this is valid in iPython/Jupyter Notebook def greet_all(names: list[str]) -> None: for name in names: print("Hello", name) greet_all(['Adam','Eve']) Python 3.7.6 Hello Adam Hello E...
15
15
63,972,113
2020-9-19
https://stackoverflow.com/questions/63972113/big-sur-clang-invalid-version-error-due-to-macosx-deployment-target
I assume due to the fact Big Sur is sparkling new hotfixes for the new OS have not yet happen. When attempting to install modules that use clang for compilation, the following error is thrown: clang: error: invalid version number in 'MACOSX_DEPLOYMENT_TARGET=11.0' Currently running: Mac OS Big Sur, 11.0 Beta Intel CP...
Figure out the issue on my end. Previously I had installed XCode from the App Store (11.7) and set its SDKs as my default: sudo xcode-select --switch /Applications/Xcode.app/ However, it seems this come with an unsupported version of clang: λ clang --version Apple clang version 11.0.3 (clang-1103.0.32.62) Target: x86...
60
64
63,925,403
2020-9-16
https://stackoverflow.com/questions/63925403/custom-criterion-for-decisiontreeregressor-in-sklearn
I want to use a DecisionTreeRegressor for multi-output regression, but I want to use a different "importance" weight for each output (e.g. predicting y1 accurately is twice as important as predicting y2). Is there a way of including these weights directly in the DecisionTreeRegressor of sklearn? If not, how can I creat...
I am afraid you can only provide one weight-set when you fit https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html#sklearn.tree.DecisionTreeRegressor.fit And the more disappointing thing is that since only one weight-set is allowed, the algorithms in sklearn is all about one weight-s...
6
5
63,933,790
2020-9-17
https://stackoverflow.com/questions/63933790/robust-algorithm-to-detect-uneven-illumination-in-images-detection-only-needed
One of the biggest challenges in tesseract OCR text recognition is the uneven illumination of images. I need an algorithm that can decide the image is containing uneven illuminations or not. Test Images I Attached the images of no illumination image, glare image( white-spotted image) and shadow containing image. If w...
I suggest using the division trick to separate text from the background, and then calculate statistics on the background only. After setting some reasonable thresholds it is easy to create classifier for the illumination. def get_image_stats(img_path, lbl): img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_...
21
5
63,950,888
2020-9-18
https://stackoverflow.com/questions/63950888/typeerror-failed-to-convert-object-of-type-sparsetensor-to-tensor
I am building a text classification model for imdb sentiment analysis dataset. I downloaded the dataset and followed the tutorial given here - https://developers.google.com/machine-learning/guides/text-classification/step-4 The error I get is TypeError: Failed to convert object of type <class 'tensorflow.python.framewo...
There's a similar open issue that you can find here. Solution proposed is use Tensorflow version 2.1.0 and Keras version 2.3.1.
6
-1
63,989,813
2020-9-21
https://stackoverflow.com/questions/63989813/setting-a-custom-directory-for-confuse-yaml-configuration-files
I'm trying to use this library for setting up a YAML config file for a python project, but I don't want to use the suggested directories for configuration e.g. ~/.config/app or /etc/app for linux. I've tried setting the path using an environment variable as outlined in the documentation here. Does anybody have any expe...
I'm experimenting with the library and so far in order to put a config.yaml file in the root folder of my script I just did that: import confuse class MyConfiguration(confuse.Configuration): def config_dir(self): return './' config = MyConfiguration('SplitwiseToBuckets') print(config) Quite rude I know but for what I ...
6
2
64,014,568
2020-9-22
https://stackoverflow.com/questions/64014568/kivy-sounds-do-not-play-on-android-device-even-though-they-play-fine-on-laptop
I am trying to play a sound using Kivy. The sound plays perfectly and everything works perfectly on my laptop, but when I load the APK on my Android device, the sound does not play. I have manually allowed "storage permissions" on my android device, and in my buildozer.spec file I have included permissions to write and...
I tried to build a project in Kivy for android for and faced similar issue where in the sound play was working fine on Laptop but not on Android device. As i could see from your buildspec file it does not include the below requirement of ffpyplayer. Try to include this one and rebuild again clean. Hopefully it should r...
6
2
63,978,903
2020-9-20
https://stackoverflow.com/questions/63978903/python-import-path-for-sub-modules-if-put-in-namespace-package
I have a python modules written in C, it has a main module and a submodule(name with a dot, not sure this can be called real submodule): PyMODINIT_FUNC initsysipc(void) { PyObject *module = Py_InitModule3("sysipc", ...); ... init_sysipc_light(); } static PyTypeObject FooType = { ... }; PyMODINIT_FUNC init_sysipc_light(...
Quoting from https://www.python.org/dev/peps/pep-0489/#multiple-modules-in-one-library : To support multiple Python modules in one shared library, the library can export additional PyInit* symbols besides the one that corresponds to the library's filename. Note that this mechanism can currently only be used to load ex...
6
5
63,930,235
2020-9-17
https://stackoverflow.com/questions/63930235/how-to-find-multi-mode-of-an-array-column-in-pyspark
I want to find the mode of the task column in this dataframe: +-----+-----------------------------------------+ | id | task | +-----+-----------------------------------------+ | 101 | [person1, person1, person3] | | 102 | [person1, person2, person3] | | 103 | null | | 104 | [person1, person2] | | 105 | [person1, person...
Using Spark 2.3: You can solve this using a custom UDF. For the purposes of getting multiple mode values, I'm using a Counter. I use the except block in the UDF for the null cases in your task column. (For Python 3.8+ users, there is a statistics.multimode() in-built function you can make use of) Your dataframe: from ...
6
0
63,927,188
2020-9-16
https://stackoverflow.com/questions/63927188/keras-custom-loss-function-per-tensor-group
I am writing a custom loss function that requires calculating ratios of predicted values per group. As a simplified example, here is what my Data and model code looks like: def main(): df = pd.DataFrame(columns=["feature_1", "feature_2", "condition_1", "condition_2", "label"], data=[[5, 10, "a", "1", 0], [30, 20, "a", ...
I ended up figuring out a solution to this, though I would like some feedback on it (specifically some parts). Here is the solution: import pandas as pd import tensorflow as tf import keras.backend as K from keras.models import Sequential from keras.layers import Dense, Flatten, Dropout from tensorflow.python.ops impor...
6
4
63,955,581
2020-9-18
https://stackoverflow.com/questions/63955581/building-object-models-around-external-data
I want to integrate external data into a Django app. Let's say, for example, I want to work with GitHub issues as if they were formulated as normal models within Django. So underneath these objects, I use the GitHub API to retrieve and store data. In particular, I also want to be able to reference the GitHub issues fro...
The django way in this case would be to write a custom "db" backend. This repo looks abandoned but still can lead you to some ideas.
9
2
64,005,822
2020-9-22
https://stackoverflow.com/questions/64005822/how-to-specify-external-system-dependencies-to-a-python-package
When writing a Python package, I know how to specify other required Python packages in the setup.py file thanks to the field install_requires from setuptools.setup. However, I do not know how to specify external system dependencies that are NOT Python packages, i.e. a commands such as git or cmake (examples) that my pa...
My recommendation would be to check for the presence of those external dependencies not at install-time but at run-time. Either at the start of each run, or maybe at the first run. It's true that you could add this to your setup.py, but the setup.py is not always executed at install-time: for example if your project is...
8
6
64,014,746
2020-9-22
https://stackoverflow.com/questions/64014746/how-do-you-create-a-legend-for-kde-plot-in-seaborn
I have a kdeplot but I'm struggling to figure out how to create the legend. import matplotlib.patches as mpatches # see the tutorial for how we use mpatches to generate this figure! # Set 'is_workingday' to a boolean array that is true for all working_days is_workingday = daily_counts["workingday"] == "yes" is_not_work...
The other answer works nice when one single color is used per kdeplot. In case a colormap such as 'Reds' is used, this would show a very light red. A custom colormap can show a color from the middle of the range: from matplotlib import pyplot as plt import matplotlib.patches as mpatches import seaborn as sns import num...
10
10
64,016,590
2020-9-22
https://stackoverflow.com/questions/64016590/numpy-fortran-like-reshape
Let's say I have an array X of shape (6, 2) like this: import numpy as np X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]) I want to reshape it to an array of shape (3, 2, 2), so I did this: X.reshape(3, 2, 2) And got: array([[[ 1, 2], [ 3, 4]], [[ 5, 6], [ 7, 8]], [[ 9, 10], [11, 12]]]) However, I ...
You have to set the order option: >>> X.reshape(3, 2, 2, order='F') array([[[ 1, 2], [ 7, 8]], [[ 3, 4], [ 9, 10]], [[ 5, 6], [11, 12]]]) ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. see: https://numpy.org/doc/stabl...
6
5
64,014,291
2020-9-22
https://stackoverflow.com/questions/64014291/pandas-dataframe-round-not-accepting-pd-na-or-pd-nan
pandas version: 1.2 I have a dataframe that columns as 'float64' with null values represented as pd.NAN. Is there way to round without converting to string then decimal: df = pd.DataFrame([(.21, .3212), (.01, .61237), (.66123, .03), (.21, .18),(pd.NA, .18)], columns=['dogs', 'cats']) df dogs cats 0 0.21 0.32120 1 0.01 ...
df['dogs'] = df['dogs'].apply(lambda x: round(x,2) if str(x) != '<NA>' else x)
6
2
63,920,237
2020-9-16
https://stackoverflow.com/questions/63920237/why-does-client-recv1024-return-an-empty-byte-literal-in-this-bare-bones-webso
I need a web socket client server exchange between Python and JavaScript on an air-gapped network, so I'm limited to what I can read and type up (believe me I'd love to be able to run pip install websockets). Here's a bare-bones RFC 6455 WebSocket client-server relationship between Python and JavaScript. Below the code...
I tried running your example and it seem to be working as expected. At least server logs end with the following line: INFO - Got message: {"name":"ping","data":0} My environment: OS: Arch Linux; WebSocket client: Chromium/85.0.4183.121 running the JS-code you provided; WebSocket server: Python/3.8.5 running the Pytho...
6
1
64,004,193
2020-9-22
https://stackoverflow.com/questions/64004193/how-to-split-dataset-to-train-test-and-valid-in-python
I have a dataset like this my_data= [['Manchester', '23', '80', 'CM', 'Manchester', '22', '79', 'RM', 'Manchester', '19', '76', 'LB'], ['Benfica', '26', '77', 'CF', 'Benfica', '22', '74', 'CDM', 'Benfica', '17', '70', 'RB'], ['Dortmund', '24', '75', 'CM', 'Dortmund', '18', '74', 'AM', 'Dortmund', '16', '69', 'LM'] ] I...
You can simply use train_test split twice X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=1) also, the answer can be found here
7
11
63,998,612
2020-9-21
https://stackoverflow.com/questions/63998612/what-is-the-best-way-to-append-custom-message-to-the-output-when-pytest-raises-f
What I'm aiming at is - if I ran the following test: def test_func(): with pytest.raises(APIError): func() and the func() did not raise APIError - I want to get custom message to the output, e.g. "No APIError caught" Pytest had a feature specifically for this: with raises(SomeError, message="Custom message here"): pas...
You can replicate this behavior using the pytest.fail function after the function you expect to raise an exception, since that will only run if an exception is not raised. The deprecation notice explains the reasoning for its removal, and offers this alternate approach: import pytest def func(): return def test_func():...
6
8
63,998,196
2020-9-21
https://stackoverflow.com/questions/63998196/python-pyspark-correct-method-chaining-order-rules
Coming from a SQL development background, and currently learning pyspark / python I am a bit confused with querying data / chaining methods, using python. for instance the query below (taken from 'Learning Spark 2nd Edition'): fire_ts_df. select("CallType") .where(col("CallType").isNotNull()) .groupBy("CallType") .coun...
The important thing to note here is that chained methods necessarily do not occur in random order. The operations represented by these method calls are not some associative transformations applied flatly on the data from left to right. Each method call could be written as a separate statement, where each statement prod...
6
7
63,954,102
2020-9-18
https://stackoverflow.com/questions/63954102/numpy-vectorized-way-to-count-non-zero-bits-in-array-of-integers
I have an array of integers: [int1, int2, ..., intn] I want to count how many non-zero bits are in the binary representation of these integers. For example: bin(123) -> 0b1111011, there are 6 non-zero bits Of course I can loop over list of integers, use bin() and count('1') functions, but I'm looking for vectorized w...
Assuming your array is a, you can simply do: np.unpackbits(a.view('uint8')).sum() example: a = np.array([123, 44], dtype=np.uint8) #bin(a) is [0b1111011, 0b101100] np.unpackbits(a.view('uint8')).sum() #9 Comparison using benchit: #@Ehsan's solution def m1(a): return np.unpackbits(a.view('uint8')).sum() #@Valdi_Bo's ...
7
7
63,992,444
2020-9-21
https://stackoverflow.com/questions/63992444/how-to-convert-bytes-object-to-io-bytesio-python
I am making a simple flask API for uploading an image and do some progresses then store it in the data base as binary, then i want to download it by using send_file() function but, when i am passing an image like a bytes it gives me an error: return send_file(BytesIO.read(image.data), attachment_filename='f.jpg', as_a...
It seems you are confused io.BytesIO. Let's look at some examples of using BytesIO. >>> from io import BytesIO >>> inp_b = BytesIO(b'Hello World', ) >>> inp_b <_io.BytesIO object at 0x7ff2a71ecb30> >>> inp.read() # read the bytes stream for first time b'Hello World' >>> inp.read() # now it is positioned at the end so d...
7
13
63,993,139
2020-9-21
https://stackoverflow.com/questions/63993139/how-to-split-a-list-into-two-random-parts
I have 12 people who i need to divide into 2 different teams. What i need to do is pick random 6 numbers between 0 and 11 for the first team and do the same for the second one with no overlap. What is the most efficient way to do this? import random A = random.choice([x for x in range(12)]) B = random.choice([x for x i...
You can use sets and set difference, like this: import random all_players = set(range(12)) team1 = set(random.sample(all_players, 6)) team2 = all_players - team1 print(team1) print(team2) Example Output: {1, 5, 8, 9, 10, 11} {0, 2, 3, 4, 6, 7}
7
14
63,988,597
2020-9-21
https://stackoverflow.com/questions/63988597/i-need-to-change-the-type-of-few-columns-in-a-pandas-dataframe-cant-do-so-usin
In a dataframe with around 40+ columns I am trying to change dtype for first 27 columns from float to int by using iloc: df1.iloc[:,0:27]=df1.iloc[:,0:27].astype('int') However, it's not working. I'm not getting any error, but dtype is not changing as well. It still remains float. Now the strangest part: If I first ch...
I guess it is a bug in 1.0.5. I tested on my 1.0.5. I have the same issue as yours. The .loc also has the same issue, so I guess pandas devs break something in iloc/loc. You need to update to latest pandas or use a workaround. If you need a workaround, using assignment as follows df1[df1.columns[0:27]] = df1.iloc[:, 0:...
12
8
63,987,965
2020-9-21
https://stackoverflow.com/questions/63987965/typeerror-argument-of-type-windowspath-is-not-iterable-in-django-python
whenever I run the server or executing any commands in the terminal this error is showing in the terminal. The server is running and the webpage is working fine but when I quit the server or run any commands(like python manage.py migrate) this error is showing. `Watching for file changes with StatReloader Performing s...
I got this cleared by changing DATABASES in settings.py file: change 'NAME': BASE_DIR / 'db.sqlite3', to 'NAME': str(os.path.join(BASE_DIR, "db.sqlite3")) this works DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(os.path.join(BASE_DIR, "db.sqlite3")) } }
14
45
63,979,186
2020-9-20
https://stackoverflow.com/questions/63979186/jupyter-notebook-does-not-launch-importerror-dll-load-failed-while-importing
Recently my jupyter notebook stopped launching. When I try the command jupyter notebook from anaconda prompt but it gives error Traceback (most recent call last): File "C:\Users\Dell\anaconda3\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\Dell\anaconda3\lib\site-p...
I found what I did wrong (silly me). Microsoft visual C++ 2015-2019 was somehow removed when I tried to install openCV manually. Didn't think that such an install would make such big impact, have to keep that in mind now but installing the latest solved all the problems. P.S.: This solution might not work for someone e...
7
4
63,986,466
2020-9-21
https://stackoverflow.com/questions/63986466/how-can-i-check-the-sparsity-of-a-pandas-dataframe
In Pandas, How can I check how sparse a DataFrame? Is there any function available, or I will need to write my own? For now, I have this: df = pd.DataFrame({'a':[1,0,1,1,3], 'b':[0,0,0,0,1], 'c':[4,0,0,0,0], 'd':[0,0,3,0,0]}) a b c d 0 1 0 4 0 1 0 0 0 0 2 1 0 0 3 3 1 0 0 0 4 3 1 0 0 sparsity = sum((df == 0).astype(i...
One idea for your solution is convert to numpy array, compare and use mean: a = (df.to_numpy() == 0).mean() print (a) 0.65 If want use Sparse dtypes is possible use: #convert each column to SparseArray sparr = df.apply(pd.arrays.SparseArray) print (sparr) a b c d 0 1 0 4 0 1 0 0 0 0 2 1 0 0 3 3 1 0 0 0 4 3 1 0 0 print...
7
7
63,982,499
2020-9-20
https://stackoverflow.com/questions/63982499/keyerror-on-if-condition-in-dictionary-python
I have this problem: I hav this code that is trying to count bigrams in a text file. An if statement checks wether the tuple is in a dictionary. If it is, the value (counter) is one-upped. If it doesn't exist, the code shoud create a key-value pair with the tuple as key and the value 1. for i in range(len(temp_list)-1)...
What you were trying to do was if temp_tuple in bigramdict: instead of if bigramdict[temp_tuple] in bigramdict:
7
9
63,980,647
2020-9-20
https://stackoverflow.com/questions/63980647/how-can-i-stop-the-log-output-of-lightgbm
I would like to know how to stop lightgbm logging. What kind of settings should I use to stop the log? Also, is there a way to output only your own log with the lightgbm log stopped?
I think you can disable lightgbm logging using verbose=-1 in both Dataset constructor and train function, as mentioned here
13
12
63,978,820
2020-9-20
https://stackoverflow.com/questions/63978820/type-hints-for-dataclass-defined-inside-a-class-with-generic-types
I know that the title is very confusing, so let me take the Binary Search Tree as an example: Using ordinary class definition # This code passed mypy test from typing import Generic, TypeVar T = TypeVar('T') class BST(Generic[T]): class Node: def __init__( self, val: T, left: 'BST.Node', right: 'BST.Node' ) -> None: se...
Let's start with what is written in PEP 484 about scoping rules for type variables: A generic class nested in another generic class cannot use same type variables. The scope of the type variables of the outer class doesn't cover the inner one: T = TypeVar('T') S = TypeVar('S') class Outer(Generic[T]): class Bad(Iterab...
6
5
63,980,292
2020-9-20
https://stackoverflow.com/questions/63980292/how-to-delete-all-instances-of-a-repeated-number-in-a-list
I want a code that deletes all instances of any number that has been repeated from a list. E.g.: Inputlist = [2, 3, 6, 6, 8, 9, 12, 12, 14] Outputlist = [2,3,8,9,14] I have tried to remove the duplicated elements in the list already (by using the "unique" function), but it leaves a single instance of the element in th...
You can use a Counter >>> from collections import Counter >>> l = [2, 3, 6, 6, 8, 9, 12, 12, 14] >>> res = [el for el, cnt in Counter(l).items() if cnt==1] >>> res [2, 3, 8, 9, 14]
9
10
63,979,315
2020-9-20
https://stackoverflow.com/questions/63979315/python-difference-with-previous-row-by-group
i am trying to take diff value from previous row in a dataframe by grouping column "group", there are several similar questions but i can't get this working. date group value 0 2020-01-01 A 808 1 2020-01-01 B 331 2 2020-01-02 A 612 3 2020-01-02 B 1391 4 2020-01-03 A 234 5 2020-01-04 A 828 6 2020-01-04 B 820 6 2020-01-...
Shifts through each group to create a calculated column. Subtract that column from the original value column to create the difference column. df.sort_values(['group','date'], ascending=[True,True], inplace=True) df['shift'] = df.groupby('group')['value'].shift() df['diff'] = df['value'] - df['shift'] df = df[['date','g...
6
7
63,977,422
2020-9-20
https://stackoverflow.com/questions/63977422/error-trying-to-import-cv2opencv-python-package
I am trying to access my webcam with cv2(opencv-python) package. When I try to import it I get this error: Traceback (most recent call last): File "server.py", line 6, in <module> import cv2 File "/usr/local/lib/python3.8/dist-packages/cv2/__init__.py", line 5, in <module> from .cv2 import * ImportError: libGL.so.1: ca...
Install opencv-python-headless instead of opencv-python. Server (headless) environments do not have GUI packages installed which is why you are seeing the error. opencv-python depends on Qt which in turn depends on X11 related libraries. Other alternative is to run sudo apt-get install -y libgl1-mesa-dev which will pro...
12
46
63,975,678
2020-9-20
https://stackoverflow.com/questions/63975678/how-to-convert-a-dataframe-from-long-to-wide-with-values-grouped-by-year-in-the
The code below worked with the previous csv that I used, both csv's have the same amount of columns, and the columns have the same name. Data for the csv that worked here Data for csv that didnt here What does this error mean? Why am I getting this error? from pandas import read_csv from pandas import DataFrame from pa...
The issue with iteratively creating the dataframe in the manner shown, is it requires the new column to match the length of the existing dataframe, year, index. In the smaller dataset, all the years are 365 days without missing days. The larger dataset has mixed length years of 365 and 366 days and there is missing da...
6
3
63,975,914
2020-9-20
https://stackoverflow.com/questions/63975914/python-asyncio-typeerror-a-coroutine-was-expected
I'm trying python coroutine programming using asyncio. This is my code. import asyncio async def coro_function(): return 2 + 2 async def get(): return await coro_function() print(asyncio.iscoroutinefunction(get)) loop = asyncio.get_event_loop() a1 = loop.create_task(get) loop.run_until_complete(a1) But when I execute ...
You're passing in the function get. In order to pass in a coroutine, pass in get(). a1 = loop.create_task(get()) loop.run_until_complete(a1) Take a look at the types: >>> type(get) <class 'function'> >>> print(type(get())) <class 'coroutine'> get is a coroutine function, i.e. a function that returns a coroutine objec...
17
28
63,975,130
2020-9-20
https://stackoverflow.com/questions/63975130/how-to-get-only-specific-classes-from-pytorchs-fashionmnist-dataset
The FashionMNIST dataset has 10 different output classes. How can I get a subset of this dataset with only specific classes? In my case, I only want images of sneaker, pullover, sandal and shirt classes (their classes are 7,2,5 and 6 respectively). This is how I load my dataset. train_dataset_full = torchvision.dataset...
Finally found the answer. dataset_full = torchvision.datasets.FashionMNIST(data_folder, train = True, download = True, transform = transforms.ToTensor()) # Selecting classes 7, 2, 5 and 6 idx = (dataset_full.targets==7) | (dataset_full.targets==2) | (dataset_full.targets==5) | (dataset_full.targets==6) dataset_full.tar...
10
12
63,936,759
2020-9-17
https://stackoverflow.com/questions/63936759/scrapy-hidden-memory-leak
Background - TLDR: I have a memory leak in my project Spent a few days looking through the memory leak docs with scrapy and can't find the problem. I'm developing a medium size scrapy project, ~40k requests per day. I am hosting this using scrapinghub's scheduled runs. On scrapinghub, for $9 per month, you are essentia...
1.Scheruler queue/Active requests with self.numpages = 418. this code lines will create 418 request objects (including -to ask OS to delegate memory to hold 418 objects) and put them into scheduler queue : for page in tqdm(range(1, self.num_pages+1)): url = 'www.example.com/page={page}' yield scrapy.Request(url = url,...
6
4
63,972,580
2020-9-19
https://stackoverflow.com/questions/63972580/how-to-download-a-nested-json-into-a-pandas-dataframe
Looking to sharpen my data science skills. I am practicing url data pulls from a sports site and the json file has multiple nested dictionaries. I would like to be able to pull this data to map my own custom form of the leaderboard in matplotlib, etc., but am having a hard time getting the json to a workable df. The ma...
Simple and Quick Solution. A better solution might exist with JSON normalize from pandas but this is fairly good for your use case. def func(x): if not any(x.isnull()): return (x['round'], x['player']['firstName'], x['player']['identifier'], x['toParToday']['value'], x['totalScore']['value']) df = pd.DataFrame(data['st...
10
2
63,971,973
2020-9-19
https://stackoverflow.com/questions/63971973/celery-in-docker-container-error-mainprocess-consumer-cannot-connect-to-redis
A lot of frustration on this, been trying to make it work for days. I beg for help. It's a Django project with Postgres, Celery and Docker. First I tried with RabbitMQ, and I had the same error than now with Redis, then I changed to redis after multiple tries and the error is still the same, so I think the problem is a...
Try updating your app settings to use redis hostname as redis instead of 127.0.0.1 # Celery conf CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' Reference: Each container can now look up the hostname web or db and get back the appropriate container’s IP address. For example, ...
10
7
63,969,194
2020-9-19
https://stackoverflow.com/questions/63969194/how-to-calculate-pairwise-mutual-information-for-entire-pandas-dataset
I have 50 variables in my dataframe. 46 are dependent variables and 4 are independent variables (precipitation, temperature, dew, snow). I want to calculate the mutual information of my dependent variables against my independent. So in the end I want a dataframe like this Right now I am calculating it using the follow...
Using list comprehension: indep_vars = ['Temperature', 'Precipitation', 'Dew', 'Snow'] # set independent vars dep_vars = df.columns.difference(indep_vars).tolist() # set dependent vars from sklearn.feature_selection import mutual_info_regression as mi_reg df_mi = pd.DataFrame([mi_reg(df[indep_vars], df[dep_var]) for de...
9
4
63,967,363
2020-9-19
https://stackoverflow.com/questions/63967363/how-to-speed-up-numpy-all-and-numpy-nonzero
I need to check if a point lies inside a bounding cuboid. The number of cuboids is very large (~4M). The code I come up with is: import numpy as np # set the numbers of points and cuboids n_points = 64 n_cuboid = 4000000 # generate the test data points = np.random.rand(1, 3, n_points)*512 cuboid_min = np.random.rand(n_...
We can reduce memory congestion for all-reduction with slicing along the smallest axis length of 3 to get inside_cuboid - out = (points[0,0,:] > cuboid_min[:,0]) & (points[0,0,:] < cuboid_max[:,0]) & \ (points[0,1,:] > cuboid_min[:,1]) & (points[0,1,:] < cuboid_max[:,1]) & \ (points[0,2,:] > cuboid_min[:,2]) & (points[...
6
3
63,965,503
2020-9-19
https://stackoverflow.com/questions/63965503/return-value-from-list-according-to-index-number
I have been struggling to find the pandas solution to this without looping: input: df = pd.DataFrame({'A' : [[6,1,1,1], [1,5,1,1], [1,1,11,1], [1,1,1,20]]}) A 0 [6, 1, 1, 1] 1 [1, 5, 1, 1] 2 [1, 1, 11, 1] 3 [1, 1, 1, 20] output: A B 0 [6, 1, 1, 1] 6 1 [1, 5, 1, 1] 5 2 [1, 1, 11, 1] 11 3 [1, 1, 1, 20] 20 I have tried...
You can do a simple list comprehension: df['B'] = [s[i] for i, s in zip(df.index, df['A'])] Or if you want only diagonal values: df['B'] = np.diagonal([*df['A']]) A B 0 [6, 1, 1, 1] 6 1 [1, 5, 1, 1] 5 2 [1, 1, 11, 1] 11 3 [1, 1, 1, 20] 20
6
5
63,955,752
2020-9-18
https://stackoverflow.com/questions/63955752/topologicalerror-the-operation-geosintersection-r-could-not-be-performed
Hi Guys, I am trying to map the district shapefile into assembly constituencies. I have shape files for [Both].Basically I have to map all the variables given at district level in census data to assembly constituency level. So I am following a pycon talk. Everything is working fine but I am getting error in get_inters...
The error message tells you exactly what is going on. Some of your geometries are not valid, so you have to make them valid before doing your apply. The simple trick, which works in most of the cases is using buffer(0). merged['geometry'] = merged.buffer(0) Since the issue is with geometry validity and is raised by GE...
8
13
63,962,454
2020-9-18
https://stackoverflow.com/questions/63962454/numpy-find-index-of-second-highest-value-in-each-row-of-an-ndarray
I have a [10,10] numpy.ndarray. I am trying to get the index the second highest number in each row. So for the array: [101 0 1 0 0 0 1 1 2 0] [ 0 116 1 0 0 0 0 0 1 0] [ 1 4 84 2 2 0 2 4 6 1] [ 0 2 0 84 0 6 0 2 3 0] [ 0 0 1 0 78 0 0 2 0 11] [ 2 0 0 1 1 77 5 0 2 0] [ 1 2 1 0 1 2 94 0 1 0] [ 0 1 1 0 0 0 0 96 0 4] [ 1 5 4 ...
The amazing numpy.argsort() function makes this task really simple. Once the sorted indices are found, get the second to last column. m = np.array([[101, 0, 1, 0, 0, 0, 1, 1, 2, 0], [ 0, 116, 1, 0, 0, 0, 0, 0, 1, 0], [ 1, 4, 84, 2, 2, 0, 2, 4, 6, 1], [ 0, 2, 0, 84, 0, 6, 0, 2, 3, 0], [ 0, 0, 1, 0, 78, 0, 0, 2, 0, 11], ...
7
15
63,945,330
2020-9-17
https://stackoverflow.com/questions/63945330/plotly-how-to-add-text-labels-to-a-histogram
Is there a way how to display the counted value of the histogram aggregate in the Plotly.Express histogram? px.histogram(pd.DataFrame({"A":[1,1,1,2,2,3,3,3,4,4,4,5]}),x="A") If I would use regular histogram, I can specify text parameter which direct to the column which contain the value to display. px.bar(pd.DataFrame...
As far as I know, plotly histograms do not have a text attribute. It also turns out that it's complicated if at all possible to retrieve the applied x and y values and just throw them into appropriate annotations. Your best option seems to be to take care of the binning using numpy.histogram and the set up your figure ...
7
3
63,954,442
2020-9-18
https://stackoverflow.com/questions/63954442/how-to-parse-unix-timestamp-into-datetime-without-timezone-in-fast-api
Assume I have a pydantic model class EventEditRequest(BaseModel): uid: UUID name: str start_dt: datetime end_dt: datetime I send request with body b'{"uid":"a38a7543-20ca-4a50-ab4e-e6a3ae379d3c","name":"test event2222","start_dt":1600414328,"end_dt":1600450327}' So both start_dt and end_dt are unix timestamps. But in ...
You can use own @validator to parse datetime manually: from datetime import datetime from pydantic import BaseModel, validator class Model(BaseModel): dt: datetime = None class ModelNaiveDt(BaseModel): dt: datetime = None @validator("dt", pre=True) def dt_validate(cls, dt): return datetime.fromtimestamp(dt) print(Model...
6
8
63,954,751
2020-9-18
https://stackoverflow.com/questions/63954751/does-it-make-a-difference-if-you-iterate-over-a-list-or-a-tuple-in-python
I'm currently trying the wemake-python-styleguide and found WPS335: Using lists, dicts, and sets do not make much sense. You can use tuples instead. Using comprehensions implicitly create a two level loops, that are hard to read and deal with. It gives this example: # Correct: for person in ('Kim', 'Nick'): ... # Wro...
Using lists instead of tuples as constants makes no difference in CPython. As of some versions, both are compiled to tuples. >>> dis.dis(""" ... for person in ["Kim", "Nick"]: ... ... ... """) 2 0 SETUP_LOOP 12 (to 14) 2 LOAD_CONST 0 (('Kim', 'Nick')) 4 GET_ITER >> 6 FOR_ITER 4 (to 12) 8 STORE_NAME 0 (person) 3 10 JUMP...
7
6
63,953,605
2020-9-18
https://stackoverflow.com/questions/63953605/should-i-commit-static-files-into-git-repo-with-django-project
Should I commit and push my Django's project static files into my git repo? I know there is collectstatic command but it's just for prod deployment right? I work on the same project from 2 different computers and then, I have static files in one that I don't have on the other. Am I supposed to collectstatic from one to...
Yes, normally we commit static files. The command collectstatic just copies the static files from the individual app folders into one general folder (normally used only in PROD server). But the static files should already be present (and committed) in the individual app folders, so that each development PC and also the...
6
8
63,949,141
2020-9-18
https://stackoverflow.com/questions/63949141/get-indices-of-items-in-numpy-array-where-values-is-in-list
Is there a numpy way (and without for loop) to extract all the indices in a numpy array list_of_numbers, where values are in a list values_of_interest? This is my current solution: list_of_numbers = np.array([11,0,37,0,8,1,39,38,1,0,1,0]) values_of_interest = [0,1,38] indices = [] for value in values_of_interest: this_...
Use numpy.where with numpy.isin: np.argwhere(np.isin(list_of_numbers, values_of_interest)).ravel() Output: array([ 1, 3, 5, 7, 8, 9, 10, 11])
7
12
63,936,578
2020-9-17
https://stackoverflow.com/questions/63936578/docker-how-to-make-python-3-8-as-default
I'm trying to update an existing Dockerfile to switch from python3.5 to python3.8, previously it was creating a symlink for python3.5 and pip3 like this: RUN ln -s /usr/bin/pip3 /usr/bin/pip RUN ln -s /usr/bin/python3 /usr/bin/python I've updated the Dockerfile to install python3.8 from deadsnakes:ppa apt-get install ...
Replacing the system python in this way is usually not a good idea (as it can break operating-system-level programs which depend on those executables) -- I go over that a little bit in this video I made "why not global pip / virtualenv?" A better way is to create a prefix and put that on the PATH earlier (this allows s...
12
18
63,941,547
2020-9-17
https://stackoverflow.com/questions/63941547/what-is-the-difference-between-a-variable-and-a-parameter
I am learning python 3 and programming in general for the first time, but I can't seem to distinguish a parameter and a variable?
A variable is just something that refers/points to some data you have. x = 5 Here x is a variable. Variables can point to more kinds of data than just numbers, though. They can point to strings, functions, etc. A parameter is something that is passed into a function def my_function(y): print(y) Here y is a parameter....
6
6
63,940,952
2020-9-17
https://stackoverflow.com/questions/63940952/py-works-but-not-python-in-command-prompt-for-windows-10
I installed Python on my computer. When I type python in the command prompt I get the following message: 'python' is not recognized as an internal or external command, operable program or batch file. But when I type py it seems to be working and I get the following: Python 3.7.0 (v3.7.0, Jun 27 2018, 04:59:51) [MSC v....
py is itself located in C:\Windows (which is always part of the PATH), which is why you find it. When you installed Python, you didn't check the box to add it to your PATH, which is why it isn't there. In general, it's best to use the Windows Python Launcher, py.exe anyway, so this is no big deal. Just use py for launc...
14
8
63,936,321
2020-9-17
https://stackoverflow.com/questions/63936321/sqlalchemy-how-can-i-execute-a-raw-insert-sql-query-in-a-postgres-database
I’m building an app using Python and the clean architecture principles, with TDD. Some unit tests require executing some raw SQL queries against an in-memory database. I am trying to switch from sqlite to postgresql inmemory data, using pytest-postgres. Problem When using sqlite inmemory database, I can both insert an...
As pointed by others, injecting SQL like this is to be avoided in most cases. Here, the SQL is written in the unit test itself. There is no external input leaking to the SQL injection, which alleviates the security risk. Mike Organek’s solution did not fully work for me, but it pointed me to the right direction : I jus...
9
5
63,930,512
2020-9-17
https://stackoverflow.com/questions/63930512/how-to-combine-three-string-columns-to-one-which-have-nan-values-in-pandas
I have the following dataframe: A B C 0 NaN NaN cat 1 dog NaN NaN 2 NaN cat NaN 3 NaN NaN dog I would like to add a colunm with the value that doesnt have the NaN value. So that: A B C D 0 NaN NaN cat cat 1 dog NaN NaN dog 2 NaN cat NaN cat 3 NaN NaN dog dog would it be using an lambda function? or fillna? Any help...
use combine_first chained df['D'] = df.A.combine_first(df.B).combine_first(df.C) alternatively, forward fill and pick the last column df['D'] = df.ffill(axis=1).iloc[:,-1] # specifying the columns explicitly: df['D'] = df[['A', 'B', 'C']].ffill(1).iloc[:, -1]
8
6
63,929,902
2020-9-17
https://stackoverflow.com/questions/63929902/how-to-drop-row-at-certain-index-in-every-group-in-groupby-object
I'm trying to drop a row at certain index in every group inside a GroupBy object. The best I have been able to manage is: import pandas as pd x_train = x_train.groupby('ID') x_train.apply(lambda x: x.drop([0], axis=0)) However, this doesn't work. I have spent a whole day on this to no solution, so have turned to stack...
You can do it with cumcount idx= x_train.groupby('ID').cumcount() x_train = x_train[idx!=0]
6
7
63,925,623
2020-9-16
https://stackoverflow.com/questions/63925623/where-should-i-put-abstract-classes-in-a-python-package
I am adding abstract classes to my python package like this: class AbstractClass(ABC): @abstractmethod def do_something(self): pass There will be multiple subclasses that inherit from AbstractClass like this: class SubClass(AbstractClass): def do_something(self): pass I am wondering if there are any conventions for p...
No convention comes to mind. If this is all for just one project, I'd be looking to put the abstract class in with the concrete subclasses at whatever level they're at. If all the subclasses were in one file, then I'd put the abstract class in that file too. If all the subclasses were in individual files in a dir, I'd ...
6
7
63,922,309
2020-9-16
https://stackoverflow.com/questions/63922309/could-not-open-requirements-file-errno-2-no-such-file-or-directory-requirem
I'm trying to build a docker image on my ubuntu 18.04 machine and I have located requirements.txt in the same building directory but still its showing up this error. Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' The command '/bin/sh -c pip3 install -r requirements.txt' retur...
I suspect that you haven't copied over your requirements.txt file to your Docker image. Typically you add the following lines to your Dockerfile to copy your requirements.txt file and install it using pip: COPY requirements.txt /tmp/requirements.txt RUN python3 -m pip install -r /tmp/requirements.txt If you don't expl...
15
38
63,911,610
2020-9-16
https://stackoverflow.com/questions/63911610/python-difference-between-yaml-load-and-yaml-safe-load
I am seeing that PyYaml, truncates zero's while loading from yaml file, if one uses: yaml.safe_load(stream). It can be fixed, if one uses yaml.load(stream, Loader=yaml.BaseLoader), but is that advisable? It works with yaml.load and zeros are not truncated. I want to understand that would it be safe to switch to yaml.lo...
yaml.safe_load(sys.stdin) just does yaml.load(sys.stdin, Loader=yaml.SafeLoader). The facilities to execute arbitrary Python code (which makes loading unsafe) are implemented in yaml.Loader which is used by default. yaml.BaseLoader does not contain them. Therefore, if you use yaml.BaseLoader, loading will not execute a...
25
24
63,909,351
2020-9-15
https://stackoverflow.com/questions/63909351/how-to-rotate-xticklabels-in-a-seaborn-catplot
I'm not able to rotate my xlabels in Seaborn/Matplotlib. I have tried many different solutions but not able to fix it. I have seen many related questions here on stackoverflow, but they have not worked for me. My current plot looks like this, but I want the xlabels to rotate 90. @staticmethod def plotPrestasjon(plot):...
The correct way to set the xticklabels for sns.catplot, according to the documentation, is with the .set_xticklabels method (.e.g. g.set_xticklabels(rotation=30)). Using a loop to iterate through the Axes, should be used if changes need to be made on a plot by plot basis, within the FacetGrid. Building structured mult...
11
21
63,866,180
2020-9-13
https://stackoverflow.com/questions/63866180/how-to-convert-from-heic-to-jpg-in-python-on-windows
Im trying to convert HEIC to JPG using python. The only other answers about this topic used pyheif. I am on windows and pyheif doesn't support windows. Any suggestions? I am currently trying to use pillow.
The following code will convert an HEIC file format to a PNG file format from PIL import Image import pillow_heif heif_file = pillow_heif.read_heif("HEIC_file.HEIC") image = Image.frombytes( heif_file.mode, heif_file.size, heif_file.data, "raw", ) image.save("./picture_name.png", format("png"))
15
25
63,838,471
2020-9-10
https://stackoverflow.com/questions/63838471/possible-to-enforce-type-hints
Is there any advantage to using the 'type hint' notation in python? import sys def parse(arg_line: int) -> str: print (arg_line) # passing a string, returning None if __name__ == '__main__': parse(' '.join(sys.argv[1:])) To me it seems like it complicates the syntax without providing any actual benefit (outside of per...
Are there any plans for python to contain type constraints within the language itself? Almost certainly not, and definitely not before the next major version (4.x). What is the advantage of having a "type hint" ? Couldn't I just as easily throw that into the docstring or something? Off the top of my head, consider ...
27
21
63,847,850
2020-9-11
https://stackoverflow.com/questions/63847850/find-which-python-package-provides-a-specific-import-module
Without getting confused, there are tons of questions about installing Python packages, how to import the resulting modules, and listing what packages are available. But there doesn't seem to be the equivalent of a --what-provides option for pip, if you don't have a pip-style requirements.txt file or a Pipenv Pipfile. ...
Use the packages_distributions() function from importlib.metadata (or importlib-metadata). So for example, in your case where serial is the name of the "import package": import importlib.metadata # or: `import importlib_metadata` importlib.metadata.packages_distributions()['serial'] This should return a list containin...
11
9
63,894,169
2020-9-15
https://stackoverflow.com/questions/63894169/pandas-datareader-importerror-cannot-import-name-urlencode
I am working fine with pandas_datareader, then today I installed below both yahoo finance from the below link trying to solve another issue. No data fetched Web.DataReader Panda pip install yfinance pip install fix_yahoo_finance After the above installtion, pandas_datareader cannot be used anymore. I googled it and I ...
I encountered exactly the same error. I am using python anaconda 2020_07 version. The solution is to use the latest pandas-datareader v0.9 from anaconda channel. If you use the pandas-datareader package from conda-forge which is using older version v0.8.1, you will encounter the error. This is the status as of 20Dec202...
8
5
63,895,392
2020-9-15
https://stackoverflow.com/questions/63895392/seaborn-is-not-plotting-within-defined-subplots
I am trying to plot two displots side by side with this code fig,(ax1,ax2) = plt.subplots(1,2) sns.displot(x =X_train['Age'], hue=y_train, ax=ax1) sns.displot(x =X_train['Fare'], hue=y_train, ax=ax2) It returns the following result (two empty subplots followed by one displot each on two lines)- If I try the same co...
seaborn.distplot has been DEPRECATED in seaborn 0.11 and is replaced with the following: displot(), a figure-level function with a similar flexibility over the kind of plot to draw. This is a FacetGrid, and does not have the ax parameter, so it will not work with matplotlib.pyplot.subplots. histplot(), an axes-level ...
31
44
63,830,284
2020-9-10
https://stackoverflow.com/questions/63830284/fastapi-and-pydantic-recursionerror-causing-exception-in-asgi-application
Description I've seen similar issues about self-referencing Pydantic models causing RecursionError: maximum recursion depth exceeded in comparison but as far as I can tell there are no self-referencing models included in the code. I'm just just using Pydantic's BaseModel class. The code runs successfully until the func...
This was a simple issue that was resolved by amending the output response to match the pydantic model. This involved ensuring output within audit.py was the same structure and data types as those specified in the AuditResult class from the pydantic model.
9
3
63,910,610
2020-9-15
https://stackoverflow.com/questions/63910610/generate-typeddict-from-functions-keyword-arguments
foo.py: kwargs = {"a": 1, "b": "c"} def consume(*, a: int, b: str) -> None: pass consume(**kwargs) mypy foo.py: error: Argument 1 to "consume" has incompatible type "**Dict[str, object]"; expected "int" error: Argument 1 to "consume" has incompatible type "**Dict[str, object]"; expected "str" This is because object i...
This will be available in Python 3.12 via PEP 692: from typing import TypedDict, Unpack, Required, NotRequired class KWArgs(TypedDict): a: Required[int] b: NotRequired[str] def consume(**kwargs: Unpack[KWArgs]) -> None: a = kwargs["a"] b = kwargs.get("b", ...) consume() # Not allowed. consume(a=1) # Allowed. consume(a=...
13
6
63,822,152
2020-9-10
https://stackoverflow.com/questions/63822152/pytorch-rnn-is-more-efficient-with-batch-first-false
In machine translation, we always need to slice out the first timestep (the SOS token) in the annotation and prediction. When using batch_first=False, slicing out the first timestep still keeps the tensor contiguous. import torch batch_size = 128 seq_len = 12 embedding = 50 # Making a dummy output that is `batch_first=...
Performance There doesn't seem to be a considerable difference between batch_first=True and batch_first=False. Please see the script below: import time import torch def time_measure(batch_first: bool): torch.cuda.synchronize() layer = torch.nn.RNN(10, 20, batch_first=batch_first).cuda() if batch_first: inputs = torch.r...
8
5
63,823,395
2020-9-10
https://stackoverflow.com/questions/63823395/how-can-i-get-the-number-of-cuda-cores-in-my-gpu-using-python-and-numba
I would like to know how to obtain the total number of CUDA Cores in my GPU using Python, Numba and cudatoolkit.
Most of what you need can be found by combining the information in this answer along with the information in this answer. We'll use the first answer to indicate how to get the device compute capability and also the number of streaming multiprocessors. We'll use the second answer (converted to python) to use the compute...
10
20
63,873,066
2020-9-13
https://stackoverflow.com/questions/63873066/do-python-dict-literals-and-dictlist-of-pairs-keep-their-key-order
Do dict literals keep the order of their keys, in Python 3.7+? For example, is it guaranteed that {1: "one", 2: "two"} will always have its keys ordered this way (1, then 2) when iterating over it? (There is a thread in the Python mailing list with a similar subject, but it goes in all directions and I couldn't find an...
Yes, any method of constructing a dict preserves insertion order, in Python 3.7+. For literal key-value pairs, see the documentation: If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary See also: Martijn's answer on How to keep key...
7
7
63,893,783
2020-9-15
https://stackoverflow.com/questions/63893783/how-to-get-a-typeddict-corresponding-to-a-function-signature
Say I've got a function signature like this: def any_foo( bar: Bar, with_baz: Optional[Baz] = None, with_datetime: Optional[datetime] = None, effective: Optional[bool] = False, ) -> Foo I could of course just copy its declaration and fiddle with it enough to create the following TypedDict: AnyFooParameters = TypedDict...
The result of any_foo.__annotations__ is exactly what you want. For example: from typing import Optional def any_foo( req_int: int, opt_float: Optional[float] = None, opt_str: Optional[str] = None, opt_bool: Optional[bool] = False, ) -> int: pass And with any_foo.__annotations__, you can get this: {'req_int': int, 'op...
11
3