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
59,933,946
2020-1-27
https://stackoverflow.com/questions/59933946/difference-between-typevart-a-b-and-typevart-bound-uniona-b
What's the difference between the following two TypeVars? from typing import TypeVar, Union class A: pass class B: pass T = TypeVar("T", A, B) T = TypeVar("T", bound=Union[A, B]) I believe that in Python 3.12 this is the difference between these two bounds class Foo[T: (A, B)]: ... class Foo[T: A | B]: ... Here's a...
When you do T = TypeVar("T", bound=Union[A, B]), you are saying T can be bound to either Union[A, B] or any subtype of Union[A, B]. It's upper-bounded to the union. So for example, if you had a function of type def f(x: T) -> T, it would be legal to pass in values of any of the following types: Union[A, B] (or a union...
82
125
59,931,566
2020-1-27
https://stackoverflow.com/questions/59931566/how-to-monitor-celery-task-completion-with-prometheus
I am trying to use Prometheus for monitoring Celery tasks for which I am relatively new and I have a problem with incrementing a counter. It's just not incrementing if I am trying to do it inside of Celery.task E.g. from celery import Celery from prometheus_client import Counter app = Celery('tasks', broker='redis://lo...
By default, Celery uses process pool for workers. This doesn't go well with Prometheus Python client and you have to use its multiprocessing mode. You might rather want to use one of existing Celery exporters (such as this one) which take a different approach. They just start its own process and listen on events from w...
6
3
59,926,511
2020-1-27
https://stackoverflow.com/questions/59926511/pyspark-cannot-import-name-onehotencoderestimator
I have just started learning Spark. Currently, I am trying to perform One hot encoding on a single column from my dataframe. However I cannot import the OneHotEncoderEstimator from pyspark. I have try to import the OneHotEncoder (depacated in 3.0.0), spark can import it but it lack the transform function. Here is the o...
Your first problem is that encoder object has no 'transform' error. This is a category indexer. Before you can transform columns of object, you must train a OneHotEncoderEstimator using fit() function. In that way your encoder object will learn from data and will be able to transfer the data to encoded category vectors...
6
4
59,926,723
2020-1-27
https://stackoverflow.com/questions/59926723/select-rows-if-string-begins-with-certain-characters-in-pandas
I have a csv file as the given picture bellow I'm trying to find any word that will start with letter A and G or any list that I want but my code returns an error any Ideas what I'm doing wrong ? this is my code if len(sys.argv) == 1: print("please provide a CSV file to analys") else: fileinput = sys.argv[1] wdata =...
Use Series.str.startswith with convert list to tuple and filtering by DataFrame.loc with boolean indexing: wdata = pd.DataFrame({'words':['what','and','how','good','yes']}) L = ['a','g'] s = wdata.loc[wdata['words'].str.startswith(tuple(L)), 'words'] print (s) 1 and 3 good Name: words, dtype: object
7
5
59,925,873
2020-1-27
https://stackoverflow.com/questions/59925873/best-practice-for-conditionally-getting-values-from-python-dictionary
I have a dictionary in python with a pretty standard structure. I want to retrieve one value if present, and if not retrieve another value. If for some reason both values are missing I need to throw an error. Example of dicts: # Data that has been modified data_a = { "date_created": "2020-01-23T16:12:35+02:00", "date_m...
Assuming there are no false values and you don't really need False but just anything false: mod_date_a = data_a.get('date_modified') or data_a.get('date_created')
6
4
59,925,384
2020-1-27
https://stackoverflow.com/questions/59925384/python-remove-elements-that-are-greater-than-a-threshold-from-a-list
I would like to remove elements that are greater than a threshold from a list. For example, a list with elements a = [1,9,2,10,3,6]. I would like to remove all elements that are greater than 5. Return should be [1,2,3]. I tried using enumerate and pop but it doesn't work. for i,x in enumerate(a): if x > 5: a.pop(i)
Try using a list comprehension: >>> a = [1,9,2,10,3,6] >>> [x for x in a if x <= 5] [1, 2, 3] This says, "make a new list of x values where x comes from a but only if x is less than or equal to the threshold 5. The issue with the enumerate() and pop() approach is that it mutates the list while iterating over it -- som...
21
39
59,923,717
2020-1-26
https://stackoverflow.com/questions/59923717/is-there-a-way-of-subclassing-from-dict-and-collections-abc-mutablemapping-toget
Let's for the sake of example assume I want to subclass dict and have all keys capitalized: class capdict(dict): def __init__(self,*args,**kwds): super().__init__(*args,**kwds) mod = [(k.capitalize(),v) for k,v in super().items()] super().clear() super().update(mod) def __getitem__(self,key): return super().__getitem__...
What you could do: This likely won't work out well (i.e. not the cleanest design), but you could inherit from MutableMapping first and then from dict second. Then MutableMapping would use whatever methods you've implemented (because they are the first in the lookup chain): >>> class D(MutableMapping, dict): def __getit...
27
31
59,912,147
2020-1-25
https://stackoverflow.com/questions/59912147/why-does-subclassing-in-python-slow-things-down-so-much
I was working on a simple class that extends dict, and I realized that key lookup and use of pickle are very slow. I thought it was a problem with my class, so I did some trivial benchmarks: (venv) marco@buzz:~/sources/python-frozendict/test$ python --version Python 3.9.0a0 (venv) marco@buzz:~/sources/python-frozendict...
Indexing and in are slower in dict subclasses because of a bad interaction between a dict optimization and the logic subclasses use to inherit C slots. This should be fixable, though not from your end. The CPython implementation has two sets of hooks for operator overloads. There are Python-level methods like __contain...
10
15
59,901,350
2020-1-24
https://stackoverflow.com/questions/59901350/what-exactly-does-the-gc-collect-function-do
I am having trouble understanding what exactly the python function gc.collect() does. Does the function only collects those objects that are collectable, to free up the space at a later time once the gc.threshold is reached? or does gc.collect() collect objects and also automatically get rid of whatever it collected, s...
It depends! If called with no argument or with generation=2 as an argument, it would free the objects that are collectable. If called with generation=1 it would not clear the free lists. From the documentation: With no arguments, run a full collection. The optional argument generation may be an integer specifying whic...
7
5
59,879,577
2020-1-23
https://stackoverflow.com/questions/59879577/pandas-getting-typeerror-only-integer-scalar-arrays-can-be-converted-to-a-sca
After renaming a DataFrame's column(s), I get an error when merging on the new column(s): import pandas as pd df1 = pd.DataFrame({'a': [1, 2]}) df2 = pd.DataFrame({'b': [3, 1]}) df1.columns = [['b']] df1.merge(df2, on='b') TypeError: only integer scalar arrays can be converted to a scalar index
Replaced the code tmp.columns = [['POR','POR_PORT']] with tmp.rename(columns={'Locode':'POR', 'Port Name':'POR_PORT'}, inplace=True) and it worked.
11
6
59,904,631
2020-1-24
https://stackoverflow.com/questions/59904631/python-class-constants-in-dataclasses
Understanding that the below are not true constants, attempting to follow PEP 8 I'd like to make a "constant" in my @dataclass in Python 3.7. @dataclass class MyClass: data: DataFrame SEED = 8675309 # Jenny's Constant My code used to be: class MyClass: SEED = 8675309 # Jenny's Constant def __init__(data): self.data = ...
They are the same. dataclass ignores unannotated variables when determining what to use to generate __init__ et al. SEED is just an unhinted class attribute. If you want to provide a type hint for a class attribute, you use typing.ClassVar to specify the type, so that dataclass won't mistake it for an instance attribut...
33
53
59,902,102
2020-1-24
https://stackoverflow.com/questions/59902102/why-is-imperative-mood-important-for-docstrings
The error code D401 for pydocstyle reads: First line should be in imperative mood. I often run into cases where I write a docstring, have this error thrown by my linter, and rewrite it -- but the two docstrings are semantically identical. Why is it important to have imperative mood for docstrings?
From the docstring of check_imperative_mood itself: """D401: First line should be in imperative mood: 'Do', not 'Does'. [Docstring] prescribes the function or method's effect as a command: ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". (We'll ignore the irony that thi...
34
70
59,859,885
2020-1-22
https://stackoverflow.com/questions/59859885/how-to-define-python-enum-properties-if-mysql-enum-values-have-space-in-their-na
I have Python Enum class like this: from enum import Enum class Seniority(Enum): Intern = "Intern" Junior_Engineer = "Junior Engineer" Medior_Engineer = "Medior Engineer" Senior_Engineer = "Senior Engineer" In MYSQL database, seniority ENUM column has values "Intern", "Junior Engineer", "Medior Engineer", "Senior Engi...
As Shenanigator stated in the comment of my question, we can use aliases to solve this problem. Seniority = Enum( value='Seniority', names=[ ('Intern', 'Intern'), ('Junior Engineer', 'Junior Engineer'), ('Junior_Engineer', 'Junior_Engineer'), ('Medior Engineer', 'Medior Engineer'), ('Medior_Engineer', 'Medior_Engineer'...
11
4
59,898,490
2020-1-24
https://stackoverflow.com/questions/59898490/how-to-find-code-that-is-missing-type-annotations
I have a project that is fully annotated. Or at least I hope so, because it is entirely possible that there is a function or two somewhere in there that is missing type annotations. How can I find such functions (or any other blocks of code)?
You can use mypy for this. Just add some switches to the command call: $ mypy --disallow-untyped-calls --disallow-untyped-defs --disallow-incomplete-defs projectname This will find you all untyped defines plus incomplete defines and also warns you if you call a untyped function. For further information have a look at ...
12
15
59,894,720
2020-1-24
https://stackoverflow.com/questions/59894720/keras-and-tensorboard-attributeerror-sequential-object-has-no-attribute-g
I am using keras and trying to plot the logs using tensorboard. Bellow you can find out the error I am getting and also the list of packages versions I am using. I can not understand it is giving me the error of 'Sequential' object has no attribute '_get_distribution_strategy'. Package: Keras 2.3.1 Keras-Applications 1...
You are mixing imports between keras and tf.keras, they are not the same library and doing this is not supported. You should make all imports from one of the libraries, either keras or tf.keras.
13
14
59,878,319
2020-1-23
https://stackoverflow.com/questions/59878319/can-you-reverse-a-pytorch-neural-network-and-activate-the-inputs-from-the-output
Can we activate the outputs of a NN to gain insight into how the neurons are connected to input features? If I take a basic NN example from the PyTorch tutorials. Here is an example of a f(x,y) training example. import torch N, D_in, H, D_out = 64, 1000, 100, 10 x = torch.randn(N, D_in) y = torch.randn(N, D_out) model ...
It is possible but only for very special cases. For a feed-forward network (Sequential) each of the layers needs to be reversible; that means the following arguments apply to each layer separately. The transformation associated with one layer is y = activation(W*x + b) where W is the weight matrix and b the bias vector...
12
10
59,880,963
2020-1-23
https://stackoverflow.com/questions/59880963/how-to-print-docstring-for-class-attribute-element
I have a class: class Holiday(ActivitiesBaseClass): """Holiday is an activity that involves taking time off work""" Hotel = models.CharField(max_length=255) """ Name of hotel """ I can print the class docstring by typing: print(Holiday.__doc__) This outputs as: Holiday is an activity that involves taking time off wor...
Don't think it's possible to add docstring for specific field, but you can use field's help_text argument instead: Hotel = models.CharField(max_length=255, help_text="Name of hotel")
7
5
59,858,898
2020-1-22
https://stackoverflow.com/questions/59858898/how-to-convert-a-video-on-disk-to-a-rtsp-stream
I have a video file on my local disk and i want to create an rtsp stream from it, which i am going to use in one of my project. One way is to create a rtsp stream from vlc but i want to do it with code (python would be better). I have tried opencv's VideoWritter like this import cv2 _dir = "/path/to/video/file.mp4" cap...
You tried to expose RTP protocol via TCP server but please note that RTP is not RTSP and that RTP (and RTCP) can only be part of RTSP. Anyways, there is a way to create RTSP server with GStreamer and Python by using GStreamer's GstRtspServer and Python interface for Gstreamer (gi package). Assuming that you already hav...
10
16
59,860,465
2020-1-22
https://stackoverflow.com/questions/59860465/pybind11-importerror-dll-not-found-when-trying-to-import-pyd-in-python-int
I built a .pyd in Visual Studio 2019 (Community) that provides a wrapper for some functionality that's only present in the LibRaw. The solution compiles successfully without any warnings or errors. The project uses LibRaw, OpenCV and pybind11 as well as Python.h and the corresponding .lib-file. When i try to import the...
I quietly assumed, that Windows searches for .dlls in the same directories as the ones listed in the systems (/users) PATH-variable. However, that is not the case, as ProcMon revealed. For now, i copied the missing .dlls to the folder that contains the .pyd and everything works.
8
7
59,870,637
2020-1-23
https://stackoverflow.com/questions/59870637/unsupported-operand-types-for-windowspath-and-str
The code I'm working on throws the error Unsupported operand type(s) for +: 'WindowsPath' and 'str'. I have tried many things, and none have fixed this (aside from removing the line with the error, but that's not helpful). For context, this script (when it's done) is supposed to: Find a file (mp3) based on the ID you ...
What is happening is that you are using the "+" character to concatenate 2 different types of data Instead of using the error line: csp = str(path sp + "/" + ID + ".mp3") Try to use it this way: csp = str(Path(sp)) fullpath = csp + "/" + ID + ".mp3" Use the 'fullpath' variable to open file.
12
23
59,859,095
2020-1-22
https://stackoverflow.com/questions/59859095/reinstall-packages-automatically-into-virtual-environment-after-python-minor-ver
I've got several virtual environments (dozens) lying on my disk made by the venv module of Python 3.6. Now I've upgraded to Ubuntu 19.10 in a haste and only afterwards noticed that 3.6 is not available at all for Ubuntu 19.10 from the generally acknowledged sources. I've managed to upgrade the Python versions of these ...
In your new 3.7 venv you should have pkg_resources available - setuptools is automatically installed when created. If not, just pip install setuptools. setuptools library code is actually what pip is vendoring to make pip freeze work. But you can just freeze it manually. # in 3.7 runtime... import pkg_resources old_sit...
11
12
59,852,831
2020-1-22
https://stackoverflow.com/questions/59852831/write-a-multi-line-string-to-a-text-file-using-python
I'm trying to write multiple lines of a string to a text file in Python3, but it only writes the single line. e.g Let's say printing my string returns this in the console; >> print(mylongstring) https://www.link1.com https://www.link2.com https://www.link3.com https://www.link4.com https://www.link5.com https://www.lin...
Try closing the file: f = open("temporary.txt","w+") f.write(mylongstring) f.close() If that doesn't work try using: f = open("temporary.txt","w+") f.writelines(mylongstring) f.close() If that still doesn't work use: f = open("temporary.txt","w+") f.writelines([i + '\n' for i in mylongstring]) f.close()
9
5
59,783,735
2020-1-17
https://stackoverflow.com/questions/59783735/dataframe-convert-header-row-to-row-pandas
have a df with values df: 165 156 1 test greater 56gsa ------------------------------------- spin 201 2 normal lesser 12asgs pine 202 3 fast greater 5sasgs required output: 0 1 2 3 4 5 ------------------------------------- 165 156 1 test greater 56gsa spin 201 2 normal lesser 12asgs pine 202 3 fast greater 5sasgs
If DataFrame is created from file then header=None parameter is your friend: df = pd.read_csv(file, header=None) pandas >= 2.0: If not then convert column to one row DataFrame and concatenate (append not working anymore) to original data: df = pd.concat([df.columns.to_frame().T, df]) df.columns = range(len(df.columns)...
17
19
59,801,341
2020-1-18
https://stackoverflow.com/questions/59801341/how-to-use-np-max-for-empty-numpy-array-without-valueerror-zero-size-array-to-r
I get a case that when I tried to use np.max() in an empty numpy array it will report such error messages. # values is an empty numpy array here max_val = np.max(values) ValueError: zero-size array to reduction operation maximum which has no identity So the way I think to fix it is that I try to deal with the empty ...
In [3]: np.max([]) --------------------------------------------------------------------------- ... ValueError: zero-size array to reduction operation maximum which has no identity But check the docs. In newer numpy ufunc like max take an initial parameter that lets you work with an empty array: In [4]: np.max([], init...
15
24
59,753,517
2020-1-15
https://stackoverflow.com/questions/59753517/what-order-should-these-elements-be-in-a-python-module
When present, what is the order that these elements should be declared in a Python module? Hash bang (#!/usr/bin/env python) Encoding (# coding: utf-8) Future imports (from __future__ import unicode_literals, ...) Docstring If declared last, will the docstring work in a call help(module)?
Hash bang. The kernel literally looks at the first two bytes of the file to see if they are equal to #!, so it won't work otherwise. Encoding. According to the Python Language Reference it must be "on the first or second line". Docstring. According to PEP 257, a docstring is "a string literal that occurs as the firs...
13
14
59,801,387
2020-1-18
https://stackoverflow.com/questions/59801387/how-to-install-mod-wsgi-into-apache-on-windows
Other similar answers are out of date or focus on a particular error and not the whole process. What is the full installation process of mod_wsgi into an Apache installation on Windows 10?
Install Microsoft Visual C++ Build Tools: https://visualstudio.microsoft.com/visual-cpp-build-tools/ Point MOD_WSGI_APACHE_ROOTDIR to your installation (default is C:/Apache24). Use forward slashes: set MOD_WSGI_APACHE_ROOTDIR=C:/Users/me/apache For PowerShell this would be (with backward slashes): $env:MOD_WSGI_APA...
20
31
59,744,589
2020-1-15
https://stackoverflow.com/questions/59744589/how-can-i-convert-the-string-2020-01-06t000000-000z-into-a-datetime-object
As the question says, I have a series of strings like '2020-01-06T00:00:00.000Z'. How can I convert this series to datetime using Python? I prefer the method on pandas. If not is there any method to solve this task? Thank all. string '2020-01-06T00:00:00.000Z' convert to 2020-01-06 00:00:00 under datetime object
With Python 3.7+, that can be achieved with datetime.fromisoformat() and some tweaking of the source string: from datetime import datetime datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1] + '+00:00') Output: datetime.datetime(2020, 1, 6, 0, 0, tzinfo=datetime.timezone.utc) And here is a more Pythonic way to achi...
20
26
59,775,038
2020-1-16
https://stackoverflow.com/questions/59775038/visual-studio-code-syntax-highlighting-not-working
I am using Visual Studio Code (VSC) as my IDE. My computer just updated to Catalina 10.15.2 (19C57) and since the update, VSCode is no longer highlighting syntax errors. The extensions I have seem to be working and it recognizes my miniconda Python environment. Is there a solution for this yet? I was avoiding Catalina ...
In my case, the Catalina installation didn't remove my Python installation. After checking as suggested by @Brett Cannon in his comment, the update to Catalina uninstalled some extensions from VS Code. These are not available in the VS Code extension Marketplace anymore so there must be an issue regarding compatibility...
24
7
59,791,884
2020-1-17
https://stackoverflow.com/questions/59791884/set-the-legend-location-of-a-pandas-plot
I know how to set the legend location of matplotlib plot with plt.legend(loc='lower left'), however, I am plotting with pandas method df.plot() and need to set the legend location to 'lower left'. Does anyone know how to do it? Edited: I am actually looking for a way to do it through pandas' df.plot(), not via plt.lege...
With pandas 1.5.3 you can chain legend() behind plot() see matplotlib. Example: matched.set_index( matched.index.date ).plot(kind='barh', stacked=True ).legend( bbox_to_anchor=(1.0, 1.0), fontsize='small', );
38
11
59,796,680
2020-1-18
https://stackoverflow.com/questions/59796680/disable-pip-install-timeout-for-slow-connections
I recently moved to a place with terrible internet connection. Ever since then I have been having huge issues getting my programming environments set up with all the tools I need - you don't realize how many things you need to download until each one of those things takes over a day. For this post I would like to try t...
Use option --timeout <sec> to set socket time out. Also, as @Iain Shelvington mentioned, timeout = <sec> in pip configuration will also work. TIP: Every time you want to know something (maybe an option) about a command (tool), before googling, check the manual page of the command by using man <command> or use <command>...
7
13
59,752,632
2020-1-15
https://stackoverflow.com/questions/59752632/airflow-jinja-templating-in-params
I have an Airflow operator which allows me to query Athena which accepts a Jinja templated file as the query input. Usually, I pass variables such as table/database names, etc to the template for create table and add partition statements. This works fine for defined strings. My task definition looks like this: db = 's...
Since AWSAthenaOperator has both query as a templated field and accepts file extension .sql, you can include the jinja template in the files themselves. I modified your AWSAthenaOperator a bit to fit the example. add_partition_task= AWSAthenaOperator( task_id='add_partition', query='add_partition.sql', params={ 'databa...
7
4
59,763,933
2020-1-16
https://stackoverflow.com/questions/59763933/what-is-the-difference-between-the-random-choices-and-random-sample-function
I have the following list: list = [1,1,2,2]. After applying the sample method (rd.sample(list, 3)) the, output is [1, 1, 2]. After applying the choices method (rd.choices(list, 3)), the output is: [2, 1, 2]. What is the difference between these two methods? When should one be preferred over the other?
The fundamental difference is that random.choices() will (eventually) draw elements at the same position (always sample from the entire sequence, so, once drawn, the elements are replaced - with replacement), while random.sample() will not (once elements are picked, they are removed from the population to sample, so, o...
49
63
59,815,797
2020-1-20
https://stackoverflow.com/questions/59815797/how-to-save-plotly-express-plot-into-a-html-or-static-image-file
However, I feel saving the figure with plotly.express is pretty tricky. How to save plotly.express or plotly plot into a individual html or static image file? Anyone can help?
Adding to @vestland 's answer about saving to HTML, another way to do it according to the documentation would be: import plotly.express as px # a sample scatter plot figure created fig = px.scatter(x=range(10), y=range(10)) fig.write_html("path/to/file.html") You can read about it further (controlling size of the HTML...
60
11
59,760,328
2020-1-15
https://stackoverflow.com/questions/59760328/how-does-torch-distributed-barrier-work
I've read all the documentations I could find about torch.distributed.barrier(), but still having trouble understanding how it's being used in this script and would really appreciate some help. So the official doc of torch.distributed.barrier says it "Synchronizes all processes.This collective blocks processes until th...
First you need to understand the ranks. To be brief: in a multiprocessing context we typically assume that rank 0 is the first process or base process. The other processes are then ranked differently, e.g. 1, 2, 3, totalling four processes in total. Some operations are not necessary to be done in parallel or you just n...
21
52
59,845,407
2020-1-21
https://stackoverflow.com/questions/59845407/plotly-express-vs-altair-vega-lite-for-interactive-plots
Recently I am learning both Plotly express and Altair/Vega-Lite for interactive plotting. Both of them are quite impressive and I am wondering what their strengths and weaknesses are. Especially for creating interactive plots, are there any big differences between them and when is one more suitable than the other?
Trying to not get into personal preferences and too many details, here are some of the main similarities and differences between the two as far I am aware. Design principles Both Plotly express and Altair are high level declarative libraries, which means you express yourself in terms of data and relationships (like in ...
43
79
59,809,829
2020-1-19
https://stackoverflow.com/questions/59809829/swap-shift-enter-and-enter-in-python-interactive-window-vscode
In the interactive window in vscode you press shift-enter to run the code you just typed and enter to go to the next line. Can I swap this?
The current answers explain how to make "enter" execute the command but they don't give you the other half: make shift+enter insert a new line. Here is the complete solution (I aggregated multiple solutions from various answers to similar questions to credit to everyone else who helped). Bonus: I come from MATLAB so I ...
10
4
59,785,890
2020-1-17
https://stackoverflow.com/questions/59785890/how-to-get-the-location-of-all-text-present-in-an-image-using-opencv
I have this image that contains text (numbers and alphabets) in it. I want to get the location of all the text and numbers present in this image. Also I want to extract all the text as well. How do I get the coordinates as well as the all the text (numbers and alphabets) in my image? For eg 10B, 44, 16, 38, 22B etc
Here's a potential approach using morphological operations to filter out non-text contours. The idea is: Obtain binary image. Load image, grayscale, then Otsu's threshold Remove horizontal and vertical lines. Create horizontal and vertical kernels using cv2.getStructuringElement() then remove lines with cv2.drawConto...
9
13
59,762,996
2020-1-16
https://stackoverflow.com/questions/59762996/how-to-fix-attributeerror-partially-initialized-module
I am trying to run my script but keep getting this error: File ".\checkmypass.py", line 1, in <module> import requests line 3, in <module> response = requests.get(url) AttributeError: partially initialized module 'requests' has no attribute 'get' (most likely due to a circular import) How can I fix it?
Make sure the name of the file is not the same as the module you are importing – this will make Python think there is a circular dependency. Also check the URL and the package you are using. "Most likely due to a circular import" refers to a file (module) which has a dependency on something else and is trying to be imp...
136
115
59,768,704
2020-1-16
https://stackoverflow.com/questions/59768704/is-there-a-shortcut-in-vscode-to-execute-current-line-or-selection-in-debug-repl
I am developing with Python and commonly running code in an integrated terminal with Shift + Enter. However, when debugging the process seems to be more complicated. I need to copy the code, move focus to debug REPL (Ctrl + Shift + Y), paste, run and move focus back to the editor. Is there any easier way to do this?
If you use the vscode's integrated debugging you can set a shortcut for sending selection to debug Repl. I use this on my keybindings.json config file: { "key": "shift+alt+d", "command": "editor.debug.action.selectionToRepl" } The difference from the "workbench.action.terminal.runSelectedText" command is that you actu...
26
26
59,773,675
2020-1-16
https://stackoverflow.com/questions/59773675/why-am-i-getting-the-mysql-server-has-gone-away-exception-in-django
I'm working with Django 2.2.6. The same system that runs my django project also has a background service running, listening on a unix socket for requests. In Django Admin, if a user hits a button, Django sends a request on the unix socket, and the background service does something. My background service has full access...
I had exactly the same issue than yours. I implemented a monitoring script using watchdogs library, and, by the end of "wait_timeout", MySQL error would be raised. After a few tries with "django.db.close_old_connections()" function, it still did not work, but I was attempting to close old connections every defined time...
12
8
59,770,742
2020-1-16
https://stackoverflow.com/questions/59770742/adding-the-line-of-identity-to-a-scatter-plot-using-altair
I have created a basic scatter plot to compare two variables using altair. I expect the variables to be strongly correlated and the points should end up on or close to the line of identity. How can I add the line of identity to the plot? I would like it to be a line similar to those created by mark_rule, but extending ...
It's not perfect but you could make the line longer and set the scale domain. import altair as alt import numpy as np import pandas as pd norm = np.random.multivariate_normal([0, 0], [[2, 1.8],[1.8, 2]], 100) df = pd.DataFrame(norm, columns=['var1', 'var2']) chart = alt.Chart(df, width=500, height=500).mark_circle(size...
7
1
59,764,018
2020-1-16
https://stackoverflow.com/questions/59764018/aws-lambda-in-python-import-parent-package-directory-in-lambda-function-handler
I have a directory structure like the following in my serverless application(simplest app to avoid clutter) which I created using AWS SAM with Python 3.8 as the runtime: ├── common │ └── a.py ├── hello_world │ ├── __init__.py │ ├── app.py │ └── requirements.txt └── template.yaml I would like to import common/a.py modu...
I didn't find what I was looking for but I ended up with a solution to create a single Lambda function in the root which handles all the different API calls within the function. Yes my Lambda function is integrated with API Gateway, and I can get the API method and API path using event["httpMethod"] and event ["httpPat...
18
3
59,789,689
2020-1-17
https://stackoverflow.com/questions/59789689/spark-dag-differs-with-withcolumn-vs-select
Context In a recent SO-post, I discovered that using withColumn may improve the DAG when dealing with stacked/chain column expressions in conjunction with distinct windows specifications. However, in this example, withColumn actually makes the DAG worse and differs to the outcome of using select instead. Reproducible e...
This looks like a consequence of the the internal projection caused by withColumn. It's documented here in the Spark docs The official recommendation is to do as Jay recommended and instead do a select when dealing with multiple columns
19
6
59,809,495
2020-1-19
https://stackoverflow.com/questions/59809495/how-to-install-tensorflow-with-python-3-8
Whenever I try to install TensorFlow with pip on Python 3.8, I get the error that TensorFlow is not found. I have realized later on that it is not supported by Python 3.8. How can I install TensorFlow on Python 3.8?
As of May 7, 2020, according to Tensorflow's Installation page with pip, Python 3.8 is now supported. Python 3.8 support requires TensorFlow 2.2 or later. You should be able to install it normally via pip. Prior to May 2020: As you mentioned, it is currently not supported by Python 3.8, but is by Python 3.7. You want ...
13
15
59,821,618
2020-1-20
https://stackoverflow.com/questions/59821618/how-to-use-yapf-or-black-in-vscode
I installed yapf using: conda install yapf and add next lines in my .vscode/settings.json file: { //"python.linting.pylintEnabled": true, //"python.linting.pycodestyleEnabled": false, //"python.linting.flake8Enabled": true, "python.formatting.provider": "yapf", "python.formatting.yapfArgs": [ " — style", "{based_on_st...
The problem was in wrong settings. To use yapf, black or autopep8 you need: Install yapf / black / autopep8 (pip install black) Configure .vscode/settings.json in the next way: part of the file: { "python.linting.enabled": true, "python.linting.pylintPath": "pylint", "editor.formatOnSave": true, "python.formatting.pr...
27
39
59,838,238
2020-1-21
https://stackoverflow.com/questions/59838238/importerror-cannot-import-name-gi-from-partially-initialized-module-gi-mo
Looks like I have broken my python installation when I wanted to switch to python 3.8. Using Ubuntu 18.04. Trying to use the gi, gives the following error: $ python Python 3.8.1 (default, Dec 31 2019, 18:42:42) [GCC 7.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from gi.repos...
I had the same issue. I linked python3 to python3.6, for me it was pointing to 3.8. That solved the issue. cd /usr/bin/ rm python3 ln -s python3.6 python3 Thats all. Now my system started working fine.
43
52
59,823,283
2020-1-20
https://stackoverflow.com/questions/59823283/could-not-load-dynamic-library-cudart64-101-dll-on-tensorflow-cpu-only-install
I just installed the latest version of Tensorflow via pip install tensorflow and whenever I run a program, I get the log message: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found Is this bad? How do I fix the error?
Tensorflow 2.1+ What's going on? With the new Tensorflow 2.1 release, the default tensorflow pip package contains both CPU and GPU versions of TF. In previous TF versions, not finding the CUDA libraries would emit an error and raise an exception, while now the library dynamically searches for the correct CUDA version a...
162
148
59,768,651
2020-1-16
https://stackoverflow.com/questions/59768651/how-to-use-nox-with-poetry
I want to use nox in my project managed with poetry. What is not going well is that installing dev dependency in nox session. I have the noxfile.py as shown below: import nox from nox.sessions import Session from pathlib import Path __dir__ = Path(__file__).parent.absolute() @nox.session(python=PYTHON) def test(session...
Currently, session.install doesn't support poetry and install just runs pip in the shell. You can activate poetry with a more general method session.run. Example: @nox.session(python=False) def tests(session): session.run('poetry', 'shell') session.run('poetry', 'install') session.run('pytest') When you set up session...
10
6
59,838,433
2020-1-21
https://stackoverflow.com/questions/59838433/how-does-waitress-handle-concurrent-tasks
I'm trying to build a python webserver using Django and Waitress, but I'd like to know how Waitress handles concurrent requests, and when blocking may occur. While the Waitress documentation mentions that multiple worker threads are available, it doesn't provide a lot of information on how they are implemented and how...
Here's how the event-driven asynchronous servers generally work: Start a process and listen to incoming requests. Utilizing the event notification API of the operating system makes it very easy to serve thousands of clients from single thread/process. Since there's only one process managing all the connections, you do...
22
16
59,815,698
2020-1-20
https://stackoverflow.com/questions/59815698/mutagens-save-does-not-set-or-change-cover-art-for-mp3-files
I am trying to use Mutagen for changing ID3 (version 2.3) cover art for a bunch of MP3 files in the following way: from mutagen.mp3 import MP3 from mutagen.id3 import APIC file = MP3(filename) with open('Label.jpg', 'rb') as albumart: file.tags['APIC'] = APIC( encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=...
I needed to set the cover to the "APIC:" tag, instead of the "APIC" tag (which I guess is how IDv2.3 is specified).
7
0
59,762,414
2020-1-16
https://stackoverflow.com/questions/59762414/how-to-use-multiprocessing-to-drop-duplicates-in-a-very-big-list
Let's say I have a huge list containing random numbers for example L = [random.randrange(0,25000000000) for _ in range(1000000000)] I need to get rid of the duplicates in this list I wrote this code for lists containing a smaller number of elements def remove_duplicates(list_to_deduplicate): seen = set() result=[] ...
I'm skeptic even your greatest list is big enough so that multiprocessing would improve timings. Using numpy and multithreading is probably your best chance. Multiprocessing introduces quite some overhead and increases memory consumption like @Frank Merrow rightly mentioned earlier. That's not the case (to that extend)...
7
7
59,817,473
2020-1-20
https://stackoverflow.com/questions/59817473/sort-a-list-from-an-index-to-another-index
Suppose I have a list [2, 4, 1, 3, 5]. I want to sort the list just from index 1 to the end, which gives me [2, 1, 3, 4, 5] How can I do it in Python? (No extra spaces would be appreciated)
TL;DR: Use sorted with a slicing assignment to keep the original list object without creating a new one: l = [2, 4, 1, 3, 5] l[1:] = sorted(l[1:]) print(l) Output: [2, 1, 3, 4, 5] Longer Answer: After the list is created, we will make a slicing assignment: l[1:] = Now you might be wondering what does [1:], it is sli...
19
18
59,843,346
2020-1-21
https://stackoverflow.com/questions/59843346/dict-pop-versus-dict-get-on-the-default-return-value
I'm trying to figure out what is the reason for having None as the default value for dict.get but no default value (without specifying the default value) for dict.pop {}.get('my_key') # output: None {}.pop('my_key') # output: KeyError: 'my_key' I was thinking that the reason for not having implicit default value for d...
My take on this is to allow a dict to be used with different contexts. With dict.get(key) we always get a value even if the key is not present in dict. The default value can be provided. No exception is raised. The dict is not changed. With dict.pop(key) we get a value only when the key is present in dict, otherwise an...
9
2
59,802,468
2020-1-18
https://stackoverflow.com/questions/59802468/post-install-script-with-python-poetry
Post-install script with Python setuptools Exactly this question, but with Poetry and no Setuptools. I want to run print('Installation finished, doing other things...') when my package is installed. With Setuptools you could just modify setup.py, but in Poetry there specifically is no setup.py. What I actually want t...
It's not currently possible (and probably won't ever be) The entire idea of poetry is that a package can be installed without running any arbitrary Python code. Because of that, custom post-install scripts will probably never exist (from the author of poetry, the link you gave in your question). What you could do inste...
12
12
59,846,065
2020-1-21
https://stackoverflow.com/questions/59846065/read-the-docs-build-fails-with-cannot-import-name-packagefinder-from-pip-in
The build of Sphinx docs on read-the-docs fails with the following error (complete log below): ImportError: cannot import name 'PackageFinder' from 'pip._internal.index' (/home/docs/checkouts/readthedocs.org/user_builds/cascade-python/envs/latest/lib/python3.7/site-packages/pip/_internal/index/__init__.py) Did I do so...
The issue and the fix are described in read-the-docs issue #6554 (https://github.com/readthedocs/readthedocs.org/issues/6554): Currently all builds are failing because the automatic upgrade (since #4823 ) to pip 20.0 was buggy (see pypa/pip#7620 ). There's now a 20.0.1 release which seems to have fixed the problem for ...
25
27
59,774,722
2020-1-16
https://stackoverflow.com/questions/59774722/why-is-time-sleep-accuracy-influenced-by-chrome
I've noticed some strange behaviour that may or may not be specific to my system. (lenovo t430 running windows 8) With this script: import time now = time.time() while True: then = now now = time.time() dif = now - then print(dif) time.sleep(0.01) I get the following output (what I would consider nominal) with a brows...
I extra fired up Windows 7 to replicate your findings and I can confirm it. It's a Windows thing with the type of timer used and a default resolution of 15.6 ms (minimum 0.5 ms). Applications can alter the current resolution (WinAPI function: timeBeginPeriod) and Chrome does so. This function affects a global Windows ...
24
15
59,841,876
2020-1-21
https://stackoverflow.com/questions/59841876/why-define-create-foo-in-a-django-models-manager-instead-of-overriding-create
Reading the Django docs, it advices to make a custom creation method for a model named Foo by defining it as create_foo in the manager: class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title) # do something with the book return book class Book(models.Model): title = models.CharF...
Yes, obviously, you can do that. But if you look closer to the example you are quoting from documentation, it is not about whether you should override create or not, it is about If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. preservi...
10
12
59,765,486
2020-1-16
https://stackoverflow.com/questions/59765486/vscode-remote-jupyter-notebook-open-an-existing-notebook-in-a-specific-folder
I can connect to a remote Jupyter Notebook server with a token from VSCode through the "Python: Specify Jupyter server URI" command from the Command Palette. However, I didn't find a way to do 2 things: Open an existing Notebook on the remote Jupyter Notebook server. Specify a folder to connect to, where my existing ...
Currently, VSCode doesn't support this functionality. See this issue: https://github.com/microsoft/vscode-python/issues/8161
7
5
59,847,074
2020-1-21
https://stackoverflow.com/questions/59847074/unmelt-only-part-of-a-column-from-pandas-dataframe
I have the following example dataframe: df = pd.DataFrame(data = {'RecordID' : [1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5], 'DisplayLabel' : ['Source','Test','Value 1','Value 2','Value3','Source','Test','Value 1','Value 2','Source','Test','Value 1','Value 2','Source','Test','Value 1','Value 2','Source','Test','Value 1'...
We can achieve your result by applying logic and pivotting, we split your data by checking if DisplayLabel contains Value and then we join them back together: mask = df['DisplayLabel'].str.contains('Value') df2 = df[~mask].pivot(index='RecordID', columns='DisplayLabel', values='Value') dfpiv = ( df[mask].rename(columns...
11
7
59,842,469
2020-1-21
https://stackoverflow.com/questions/59842469/luigi-is-there-a-way-to-pass-false-to-a-bool-parameter-from-the-command-line
I have a Luigi task with a boolean parameter that is set to True by default: class MyLuigiTask(luigi.Task): my_bool_param = luigi.BoolParameter(default=True) When I run this task from terminal, I sometimes want to pass that parameter as False, but get the following result: $ MyLuigiTask --my_bool_param False error: un...
Found the solution in Luigi docs: class MyLuigiTask(luigi.Task): my_bool_param = luigi.BoolParameter( default=True, parsing=luigi.BoolParameter.EXPLICIT_PARSING) def run(self): print(self.my_bool_param) Here EXPLICIT_PARSING tell Luigi that adding the flag --my_bool_param false in the terminal call to MyLuigiTask, wil...
7
7
59,839,782
2020-1-21
https://stackoverflow.com/questions/59839782/confusion-matrix-font-size
I have a Confusion Matrix with really small sized numbers but I can't find a way to change them. from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, rf_predictions) ax = plt.subplot() sns.set(font_scale=3.0) #edited as suggested sns.heatmap(cm, annot=True, ax=ax, cmap="Blues", fmt="g"); # annot=T...
Use sns.set to change the font size of the heatmap values. You can specify the font size of the labels and the title as a dictionary in ax.set_xlabel, ax.set_ylabel and ax.set_title, and the font size of the tick labels with ax.tick_params. from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, rf_...
9
10
59,833,435
2020-1-21
https://stackoverflow.com/questions/59833435/zsh-command-not-found-conda-after-upgrading-to-catalina-and-even-after-reinstal
I recently updated my MacOS to Catalina, and now I have the infamous "zsh command not found: conda" when I enter "conda" in my terminal. I've read a number of solutions, and the easiest for me to try was to reinstall Anaconda in my home directory (specifically, the 2019.10 version of the installer installs in Users/myn...
From the Anaconda install docs: In order to initialize after the installation process is done, first run source <path to conda>/bin/activate and then run conda init. However, If you are on macOS Catalina, the new default shell is zsh. You will instead need to run source <path to conda>/bin/activate followed by conda...
7
23
59,832,252
2020-1-20
https://stackoverflow.com/questions/59832252/taking-the-maximum-values-of-each-row-in-a-tensor-pytorch
Suppose I have a tensor of the form [[-5, 0, -1], [3, 100, 87], [17, -34, 2], [45, 1, 25]] I want to find the maximum value in each row and return a rank 1 tensor as follows: [0, 100, 17, 45] How would I do this in PyTorch?
You can use the torch.max() function. So you can do something like x = torch.Tensor([[-5, 0, -1], [3, 100, 87], [17, -34, 2], [45, 1, 25]]) out, inds = torch.max(x,dim=1) and this will return the maximum values across each row (dimension 1). It will return max values with their indices.
8
11
59,829,077
2020-1-20
https://stackoverflow.com/questions/59829077/how-to-display-r-squared-value-on-my-graph-in-python
I am a Python beginner so this may be more obvious than what I'm thinking. I'm using Matplotlib to graphically present my predicted data vs actual data via a neural network. I am able to calculate r-squared, and plot my data, but now I want to combine the value on the graph itself, which changes with every new run. My ...
If I understand correctly, you want to show R2 in the graph. You can add it to the graph title: ax.set_title('R2: ' + str(r2_score(y_test, y_predicted))) before plt.show()
7
4
59,826,571
2020-1-20
https://stackoverflow.com/questions/59826571/pandas-dataframe-copydeep-true-doesnt-actually-create-deep-copy
I've been experimenting for a while with pd.Series and pd.DataFrame and faced some strange problem. Let's say I have the following pd.DataFrame: df = pd.DataFrame({'col':[[1,2,3]]}) Notice, that this dataframe includes column containing list. I want to modify this dataframe's copy and return its modified version so tha...
From the docs here, in the Notes section: When deep=True, data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to copy.deepcopy in the Standard Library, which recursively copies object data (see examples below). This is referenced again in this...
7
8
59,825,672
2020-1-20
https://stackoverflow.com/questions/59825672/pandas-overwrite-values-in-multiple-columns-at-once-based-on-condition-of-values
I have such DataFrame: df = pd.DataFrame(data={ 'col0': [11, 22,1, 5] 'col1': ['aa:a:aaa', 'a:a', 'a', 'a:aa:a:aaa'], 'col2': ["foo", "foo", "foobar", "bar"], 'col3': [True, False, True, False], 'col4': ['elo', 'foo', 'bar', 'dupa']}) I want to get length of the list after split on ":" in col1, then I want to overwrit...
Use Series.str.count, add 1, compare by Series.gt and assign list to filtered columns in list: df.loc[df['col1'].str.count(":").add(1).gt(2), ['col1','col2','col3']] = ["", "", False] print (df) col0 col1 col2 col3 col4 0 11 False elo 1 22 a:a foo False foo 2 1 a foobar True bar 3 5 False dupa
13
8
59,822,973
2020-1-20
https://stackoverflow.com/questions/59822973/keep-duplicates-by-key-in-a-list-of-dictionaries
I have a list of dictionaries, and I would like to obtain those that have the same value in a key: my_list_of_dicts = [{ 'id': 3, 'name': 'John' },{ 'id': 5, 'name': 'Peter' },{ 'id': 2, 'name': 'Peter' },{ 'id': 6, 'name': 'Mariah' },{ 'id': 7, 'name': 'John' },{ 'id': 1, 'name': 'Louis' } ] I want to keep those item...
Another concise way using collections.Counter: from collections import Counter my_list_of_dicts = [{ 'id': 3, 'name': 'John' },{ 'id': 5, 'name': 'Peter' },{ 'id': 2, 'name': 'Peter' },{ 'id': 6, 'name': 'Mariah' },{ 'id': 7, 'name': 'John' },{ 'id': 1, 'name': 'Louis' } ] c = Counter(x['name'] for x in my_list_of_dict...
7
10
59,820,159
2020-1-20
https://stackoverflow.com/questions/59820159/identify-leading-and-trailing-nas-in-pandas-dataframe
Is there a way to identify leading and trailing NAs in a pandas.DataFrame Currently I do the following but it seems not straightforward: import pandas as pd df = pd.DataFrame(dict(a=[0.1, 0.2, 0.2], b=[None, 0.1, None], c=[0.1, None, 0.1]) lead_na = (df.isnull() == False).cumsum() == 0 trail_na = (df.iloc[::-1].isnull(...
How about this df.ffill().isna() | df.bfill().isna() Out[769]: a b c 0 False True False 1 False False False 2 False True False df = pd.concat([df] * 1000, ignore_index=True) In [134]: %%timeit ...: lead_na = (df.isnull() == False).cumsum() == 0 ...: trail_na = (df.iloc[::-1].isnull() == False).cumsum().iloc[::-1] == ...
7
6
59,816,481
2020-1-20
https://stackoverflow.com/questions/59816481/how-to-convert-pandas-dataframe-to-hierarchical-dictionary
I have the following pandas dataframe: df1 = pd.DataFrame({'date': [200101,200101,200101,200101,200102,200102,200102,200102],'blockcount': [1,1,2,2,1,1,2,2],'reactiontime': [350,400,200,250,100,300,450,400]}) I am trying to create a hierarchical dictionary, with the values of the embedded dictionary as lists, that loo...
Here is another way using pivot_table: d = df1.pivot_table(index='blockcount',columns='date', values='reactiontime',aggfunc=list).to_dict() print(d) {200101: {1: [350, 400], 2: [200, 250]}, 200102: {1: [100, 300], 2: [450, 400]}}
16
22
59,811,781
2020-1-19
https://stackoverflow.com/questions/59811781/tf-function-valueerror-creating-variables-on-a-non-first-call-to-a-function-de
I would like to know why this function: @tf.function def train(self,TargetNet,epsilon): if len(self.experience['s']) < self.min_experiences: return 0 ids=np.random.randint(low=0,high=len(self.replay_buffer['s']),size=self.batch_size) states=np.asarray([self.experience['s'][i] for i in ids]) actions=np.asarray([self.exp...
Using tf.function you're converting the content of the decorated function: this means that TensorFlow will try to compile your eager code into its graph representation. The variables, however, are special objects. In fact, when you were using TensorFlow 1.x (graph mode), you were defining the variables only once and th...
11
11
59,813,807
2020-1-19
https://stackoverflow.com/questions/59813807/understanding-invalid-decimal-literal
100_year = date.today().year - age + 100 ^ SyntaxError: invalid decimal literal I'm trying to understand what the problem is.
Python identifiers can not start with a number. The 'arrow' points to year because underscore is a valid thousands separator in Python >= 3.6, so 100_000 is a valid integer literal.
13
27
59,810,276
2020-1-19
https://stackoverflow.com/questions/59810276/why-is-my-poetry-virtualenv-using-the-system-python-instead-of-the-pyenv-python
I've recently installed both Pyenv and Poetry and want to create a new Python 3.8 project. I've set both the global and local versions of python to 3.8.1 using the appropriate Pyenv commands (pyenv global 3.8.1 for example). When I run pyenv version in my terminal the output is 3.8.1. as expected. Now, the problem is t...
Alright, I figured the problem. A little embarrassingly, I had not run pyenv shell 3.8.1 before running any of the other commands. Everything works now. Thank you all for your efforts.
105
41
59,780,302
2020-1-17
https://stackoverflow.com/questions/59780302/pip3-install-pyqt5-user-fails
Errors are present when trying to install PyQt5 via pip3. The automated message wants me to add more detail, but I don't have any. All the detail is in the code. ➜ ~ pip3 install PyQt5 --user Collecting PyQt5 Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'New...
I had the same error installing tensorflow. Upgrading "setuptools" and "pip" to the latest minor version worked for me.
8
12
59,799,635
2020-1-18
https://stackoverflow.com/questions/59799635/keep-common-rows-within-every-group-of-a-pandas-dataframe
Given the following pandas data frame: | a b --+----- 0 | 1 A 1 | 2 A 2 | 3 A 3 | 4 A 4 | 1 B 5 | 2 B 6 | 3 B 7 | 1 C 8 | 3 C 9 | 4 C If you group it by column b I want to perform an action that keeps only the rows where they have column a in common. The result would be the following data frame: | a b --+----- 0 | ...
You can try pivot_table with dropna here then filter using sreries.isin : s = df.pivot_table(index='a',columns='b',aggfunc=len).dropna().index df[df['a'].isin(s)] Similarly with crosstab: s = pd.crosstab(df['a'],df['b']) df[df['a'].isin(s[s.all(axis=1)].index)] a b 0 1 A 2 3 A 4 1 B 6 3 B 7 1 C 8 3 C
7
9
59,790,440
2020-1-17
https://stackoverflow.com/questions/59790440/how-to-sort-a-list-of-sub-lists-by-the-contents-of-sub-lists-where-sub-lists-co
I have a list containing thousands of sub-lists. Each of these sub-lists contain a combination of mixed strings and boolean values, for example: lst1 = [['k', 'b', False], ['k', 'a', True], ['a', 'a', 'a'], ['a', 'b', 'a'], ['a', 'a' , False], ...] I want to sort this list in accordance with the contents of the sub-li...
These handle any lengths, not just length 3. And bools in any places, not just the last column. For keying, they turn each element of each sublist into a tuple. Solution 1: sorted(lst1, key=lambda s: [(e is False, e is True, e) for e in s]) Turns strings into (False, False, thestring) so they come first. Turns True i...
7
3
59,789,037
2020-1-17
https://stackoverflow.com/questions/59789037/get-highest-duration-from-a-list-of-strings
I have a list of durations like below ['5d', '20h', '1h', '7m', '14d', '1m'] where d stands for days, h stands for hours and m stands for minutes. I want to get the highest duration from this list(14d in this case). How can I get that from this list of strings?
Pure python solution. We could store mapping between our time extensions (m, h, d) and minutes (here time_map), to find highest duration. Here we're using max() with key argument to apply our mapping. inp = ['5d', '20h', '1h', '7m', '14d', '1m'] time_map = {'m': 1, 'h': 60, 'd': 24*60} print(max(inp, key=lambda x:int(x...
9
13
59,780,089
2020-1-17
https://stackoverflow.com/questions/59780089/one-liner-to-assign-if-not-none
Is there a way to do an assignment only if the assigned value is not None, and otherwise do nothing? Of course we can do: x = get_value() if get_value() is not None but this will read the value twice. We can cache it to a local variable: v = get_value() x = v if v is not None but now we have made two statements for a...
In python 3.8 you can do something like this if (v := get_value()) is not None: x = v Updated based on Ryan Haining solution, see in comments
27
26
59,777,009
2020-1-16
https://stackoverflow.com/questions/59777009/merging-two-dataframes-based-on-indexes-from-two-other-dataframes
I'm new to pandas have tried going through the docs and experiment with various examples, but this problem I'm tacking has really stumped me. I have the following two dataframes (DataA/DataB) which I would like to merge on a per global_index/item/values basis. DataA DataB row item_id valueA row item_id valueB 0 x A1 0 ...
First, you can create the 'global_index' column using the function pd.cut: for df, m in [(df_A, map_A), (df_B, map_B)]: bins = np.insert(m['num_rows'].cumsum().values, 0, 0) # create bins and add zero at the beginning df['global_index'] = pd.cut(df['row'], bins=bins, labels=m['global_index'], right=False) Next, you ca...
13
8
59,768,672
2020-1-16
https://stackoverflow.com/questions/59768672/handling-pylint-warning-of-inconsistent-return-statement
I'm running PyLint on some code and I'm getting the warning of "Either all return statements in a function should return an expression or none of them should. (inconsistent-return-statements)." Here is the code I have: def determine_operand_count(opcode_form, opcode_byte): if opcode_form == OP_FORM.VARIABLE: if opcode_...
Pylint complains about what is happening when you reach the very end of the function. What should happen at the end of the function? (added a return and the warning goes away) def determine_operand_count(opcode_form, opcode_byte): if opcode_form == OP_FORM.VARIABLE: if opcode_byte & 0b00100000 == 0b00100000: return OP_...
9
9
59,769,492
2020-1-16
https://stackoverflow.com/questions/59769492/spyder-4-is-not-displaying-plots-and-displays-message-like-this-uncheck-mute-i
I wrote this code. It should display the plots in spyder ide. import pandas as pd import numpy as np import matplotlib.pyplot as plt from IPython.display import display from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error import scipy.signal import scipy.stats from sklearn....
What you have is neither an error nor a warning. It's an instruction. You can find the options following: Ignore the console outputs, that's just to give you orientation in Spyder 4.0.1.
15
53
59,768,259
2020-1-16
https://stackoverflow.com/questions/59768259/filtering-dataframe-on-groups-where-count-of-element-is-different-than-1
I'm working with a DataFrame having the following structure: import pandas as pd df = pd.DataFrame({'group':[1,1,1,2,2,2,2,3,3,3], 'brand':['A','B','X','C','D','X','X','E','F','X']}) print(df) group brand 0 1 A 1 1 B 2 1 X 3 2 C 4 2 D 5 2 X 6 2 X 7 3 E 8 3 F 9 3 X My goal is to view only the groups having exactly one ...
Use series.eq to check if brand is equal to X , then groupby and transform sum and filter groups in which X count is equal to 1: df[df['brand'].eq('X').groupby(df['group']).transform('sum').eq(1)] group brand 0 1 A 1 1 B 2 1 X 7 3 E 8 3 F 9 3 X
11
10
59,761,539
2020-1-16
https://stackoverflow.com/questions/59761539/simple-way-to-do-multiple-dispatch-in-python-no-external-libraries-or-class-bu
I'm writing a throwaway script to compute some analytical solutions to a few simulations I'm running. I would like to implement a function in a way that, based on its inputs, will compute the right answer. So for instance, say I have the following math equation: tmax = (s1 - s2) / 2 = q * (a^2 / (a^2 - b^2)) It seems...
In statically typed languages like C++, you can overload functions based on the input parameter types (and quantity) but that's not really possible in Python. There can only be one function of any given name. What you can do is to use the default argument feature to select one of two pathways within that function, some...
9
4
59,755,609
2020-1-15
https://stackoverflow.com/questions/59755609/selenium-common-exceptions-invalidargumentexception-message-invalid-argument-e
I have a list of URLs in a .txt file that I would like to run using selenium. Lets say that the file name is b.txt in it contains 2 urls (precisely formatted as below): https://www.google.com/,https://www.bing.com/, What I am trying to do is to make selenium run both urls (from the .txt file), however it seems that eve...
This error message... Traceback (most recent call last): . driver.get(link) . self.execute(Command.GET, {'url': url}) . raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidArgumentException: Message: invalid argument (Session info: chrome=79.0.3945.117) ...implies that the url passed a...
19
18
59,759,107
2020-1-15
https://stackoverflow.com/questions/59759107/how-to-avoid-poor-performance-of-pandas-mean-with-datetime-columns
I have a pandas (version 0.25.3) DataFrame containing a datetime64 column. I'd like to calculate the mean of each column. import numpy as np import pandas as pd n = 1000000 df = pd.DataFrame({ "x": np.random.normal(0.0, 1.0, n), "d": pd.date_range(pd.datetime.today(), periods=n, freq="1H").tolist() }) Calculating the ...
You could restrict it to the numeric values: df.mean(numeric_only=True) Then it runs very fast as well. Here is the text from the documentation: numeric_only : bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. ...
7
5
59,752,380
2020-1-15
https://stackoverflow.com/questions/59752380/set-content-type-when-uploading-to-azure-blob-storage
I am uploading a static site using the Azure Blob storage client library. blob_service_client = BlobServiceClient.from_connection_string(az_string) blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name) print("\nUploading to Azure Storage as blob:\n\t" + local_file_name) wit...
Looking at the code here, one of the parameters to this method is content_settings which is of type ContentSettings. You can define content_type there.
17
12
59,748,008
2020-1-15
https://stackoverflow.com/questions/59748008/telegram-bot-api-is-the-chat-id-unique-for-each-user-contacting-the-bot
We are using python API for telegram bots and need to be able to identify the user. Is the chat_id unique for each user connecting the bot? Can we trust the chat_id to be consistent? e.g same chat_id will tell us that this is the same user, and each user connecting with the bot will have one chat_id that is consistent...
Is the chat_id unique for each user connecting the bot? Yes chat_id will always be unique for each user connecting to your bot. If the same user sends messages to different bots, they will always 'identify' themselves with their unique id. Keep in mind that getUpdates shows the users id, and the id from the chat. { "...
10
10
59,748,851
2020-1-15
https://stackoverflow.com/questions/59748851/split-a-list-into-sublists-based-on-a-set-of-indexes-in-python
I have a list similar to below ['a','b','c','d','e','f','g','h','i','j'] and I would like to separate by a list of index [1,4] In this case, it will be [['a'],['b','c'],['d','e','f','g','h','i','j']] As [:1] =['a'] [1:4] = ['b','c'] [4:] = ['d','e','f','g','h','i','j'] Case 2: if the list of index is [0,6] It wi...
Something along these lines: mylist = ['a','b','c','d','e','f','g','h','i','j'] myindex = [1,4] [mylist[s:e] for s, e in zip([0]+myindex, myindex+[None])] Output [['a'], ['b', 'c', 'd'], ['e', 'f', 'g', 'h', 'i', 'j']]
7
8
59,683,237
2020-1-10
https://stackoverflow.com/questions/59683237/deep-copy-of-pandas-dataframes-and-dictionaries
I'm creating a small Pandas dataframe: df = pd.DataFrame(data={'colA': [["a", "b", "c"]]}) I take a deepcopy of that df. I'm not using the Pandas method but general Python, right? import copy df_copy = copy.deepcopy(df) A df_copy.head() gives the following: Then I put these values into a dictionary: mydict = df_c...
TLDR To get deepcopy: df_copy = pd.DataFrame( columns = df.columns, data = copy.deepcopy(df.values) ) Disclaimer Notice that putting mutable objects inside a DataFrame can be an antipattern so make sure you need it and understand what you are doing. Why your copy is not independent When applied on an object, copy....
8
17
59,695,334
2020-1-11
https://stackoverflow.com/questions/59695334/custom-color-palette-in-seaborn
I have a scatterplot that should show the changes in bond lengths depending on temperature. I wanted to give each temperature a specific color, but it doesn't seem to work - plot uses the default seaborn palette. Is there a way to map temperature to color, and make seaborn use it? import pandas as pd import matplotlib....
I figured it out. You had to paste the number of colors into the palette: sns.set_style("whitegrid") plot = sns.scatterplot(df.loc[:,'length'], df.loc[:,'type'], hue = df.loc[:,'temperature'], palette=sns.color_palette(palette, len(palette)), legend = False, s = 200)
14
23
59,693,359
2020-1-11
https://stackoverflow.com/questions/59693359/when-to-use-iostr-iobytes-and-textio-binaryio-in-python-type-hinting
From the documentation, it says that: Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open(). — Python Docs: typing.IO The docs did not specify when BinaryIO/TextIO shall be used over their counterparts IO[str] and IO[bytes]. Th...
BinaryIO and TextIO directly subclass IO[bytes] and IO[str] respectively, and add on a few extra methods -- see the definitions in typeshed for the specifics. So if you need these extra methods, use BinaryIO/TextIO. Otherwise, it's probably best to use IO[...] for maximum flexibility. For example, if you annotate a met...
21
24
59,661,042
2020-1-9
https://stackoverflow.com/questions/59661042/what-do-single-star-and-slash-do-as-independent-parameters
In the following function definition, what do the * and / account for? def func(self, param1, param2, /, param3, *, param4, param5): print(param1, param2, param3, param4, param5) NOTE: Not to mistake with the single|double asterisks in *args | **kwargs (solved here)
The function parameter syntax(/) is to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments.(This is new in Python 3.8) Documentation specifies some of the use cases/benefits of positional-only parameters It allows pure Python functions to fully emulate behavio...
101
128
59,650,243
2020-1-8
https://stackoverflow.com/questions/59650243/communication-between-async-tasks-and-synchronous-threads-in-python
I am looking for the best solution for communication between async tasks and methods/functions that run in a thread pool executor from concurrent.futures. In previous synchronous projects, I would use the queue.Queue class. I assume that any method should be thread safe and therefore the asyncio.queue will not work. I...
I would recommend going the other way around: using the asyncio.Queue class to communicate between the two worlds. This has the advantage of not having to spend a slot in the thread pool on operations that take a long time to complete, such as a get(). Here is an example: class Queue: def __init__(self): self._loop = a...
10
12
59,740,840
2020-1-14
https://stackoverflow.com/questions/59740840/why-my-program-to-scrape-nse-website-gets-blocked-in-servers-but-works-in-local
This python code is running on the local computer but is not running on Digital Ocean Amazon AWS Google Collab Heroku and many other VPS. It shows different errors at different times. import requests headers = { 'authority': 'beta.nseindia.com', 'cache-control': 'max-age=0', 'dnt': '1', 'upgrade-insecure-requests': '...
Use the nsefetch() function as documented here https://unofficed.com/nse-python/documentation/nsefetch/ In case you want python-requests method from nsepython import * payload= nsefetch('https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?segmentLink=17&instrument=OPTIDX&symbol=BANKN...
7
5
59,645,272
2020-1-8
https://stackoverflow.com/questions/59645272/how-do-i-pass-an-async-function-to-a-thread-target-in-python
I have the following code: async some_callback(args): await some_function() and I need to give it to a Thread as a target: _thread = threading.Thread(target=some_callback, args=("some text")) _thread.start() The error that I get is "some_callback is never awaited". Any ideas how can I solve this problem?
You can do it by adding function between to execute async: import asyncio async def some_callback(args): await some_function() def between_callback(args): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(some_callback(args)) loop.close() _thread = threading.Thread(target=between_call...
71
80
59,725,933
2020-1-14
https://stackoverflow.com/questions/59725933/plot-fft-as-a-set-of-sine-waves-in-python
I saw someone do this in a presentation but I'm having a hard time reproducing what he was able to do. Here's a slide from his presentation: Pretty cool. He decomposed a dataset using FFT, then plotted the appropriate sine waves that the FFT specified. So in an effort to recreate what he did, I created a series of poi...
The discrete Fourier transform gives you the coefficients of complex exponentials that, when summed together, produce the original discrete signal. In particular, the k'th Fourier coefficient gives you information about the amplitude of the sinusoid that has k cycles over the given number of samples. Note that since yo...
9
7
59,681,461
2020-1-10
https://stackoverflow.com/questions/59681461/read-a-big-mbox-file-with-python
I'd like to read a big 3GB .mbox file coming from a Gmail backup. This works: import mailbox mbox = mailbox.mbox(r"D:\All mail Including Spam and Trash.mbox") for i, message in enumerate(mbox): print("from :",message['from']) print("subject:",message['subject']) if message.is_multipart(): content = ''.join(part.get_pay...
Here's a quick and dirty attempt to implement a generator to read in an mbox file message by message. I have opted to simply ditch the information from the From separator; I'm guessing maybe the real mailbox library might provide more information, and of course, this only supports reading, not searching or writing bac...
18
17
59,684,674
2020-1-10
https://stackoverflow.com/questions/59684674/should-i-add-pythons-pyc-files-to-dockerignore
I've seen several examples of .dockerignore files for Python projects where *.pyc files and/or __pycache__ folders are ignored: **/__pycache__ *.pyc Since these files/folders are going to be recreated in the container anyway, I wonder if it's a good practice to do so.
Yes, it's a recommended practice. There are several reasons: Reduce the size of the resulting image In .dockerignore you specify files that won't go to the resulting image, it may be crucial when you're building the smallest image. Roughly speaking the size of bytecode files is equal to the size of actual files. Byteco...
27
21
59,645,430
2020-1-8
https://stackoverflow.com/questions/59645430/python-moving-file-on-sftp-server-to-another-folder
I wrote this script to save a file from an SFTP remote folder to a local folder. It then removes the file from the SFTP. I want to change it so it stops removing files and instead saves them to a backup folder on the SFTP. How do I do that in pysftp? I cant find any documentation regarding it... import pysftp cnopts = ...
Use Connection.rename: sftp.rename(remote_dir + file, remote_backup_dir + file) Obligatory warnings: Do not set cnopts.hostkeys = None, unless you do not care about security. For the correct solution see Verify host key with pysftp. Do not use pysftp. It's dead. Use Paramiko. See pysftp vs. Paramiko.
10
11
59,674,072
2020-1-10
https://stackoverflow.com/questions/59674072/sklearns-class-stratifiedshufflesplit
I'm little confused about how does the class StratifiedShuffleSplit of Sklearn works. The code below is from Géron's book "Hands On Machine Learning", chapter 2, where he does a stratified sampling. from sklearn.model_selection import StratifiedShuffleSplit split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, rand...
Since you did not provide a dataset, I use sklearn sample to answer this question. Prepare dataset # generate data import numpy as np from sklearn.model_selection import StratifiedShuffleSplit data = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]]) group_label = np.array([0, 0, 0, 1, 1, 1]) This generate a d...
11
17
59,713,920
2020-1-13
https://stackoverflow.com/questions/59713920/how-to-make-that-when-you-click-on-the-text-it-was-copied-pytelegrambotapi
I am writing a telegram to the bot. I ran into such a problem. I need the bot to send a message (text) when clicked on which it was copied (as a token from @BotFather)
If I understand you correctly, you wish to send a message, that when the user presses it, the text is automatically copied to the user's clipboard, just like the BotFather sends the API token? This is done by the MarkDown parse_mode; Send a message with &parse_mode=MarkDown and wrap the 'pressable' text in back-ticks...
16
31