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
73,939,866
2022-10-3
https://stackoverflow.com/questions/73939866/initialize-dataclass-instance-with-functions
I'm trying to create a dataclass to store all relevant data in a single object. How can I initialize a dataclass instance where the values are evaluated from functions within the dataclass, which take parameters? This is where I am so far: @dataclass class Person: def Name(self): return f'My name is {self.name[0]} {sel...
First - and this is rather subtle - I note that it does not work to have dataclasses.field() as a type annotation. That is, name: field(...) is invalid. I can assume you mean to do name: str = field(...). Here str is the type annotation for name. But even with that approach, you would run into a TypeError based on how ...
5
10
73,948,788
2022-10-4
https://stackoverflow.com/questions/73948788/why-does-the-pydantic-dataclass-cast-a-list-to-a-dict-how-to-prevent-this-behav
I am a bit confused by the behavior of the pydantic dataclass. Why does the dict type accept a list of a dict as valid dict and why is it converted it to a dict of the keys? Am i doing something wrong? Is this some kind of intended behavior and if so is there a way to prevent that behavior? Code Example: from pydantic....
Hah, this is kind of amusing actually. Bear with me... Why does the dict type accept a list of a dict as valid dict and why is it converted it to a dict of the keys? This can be explained when we take a closer look at the default dict_validator used by Pydantic models. The very first thing it does (to any non-dict) ...
3
4
73,883,756
2022-9-28
https://stackoverflow.com/questions/73883756/pandas-read-csv-delimiter-used-in-a-text
I have a CSV file with ";" as separator made like this: col1;col2;col3;col4 4;hello;world;1;1 4;hi;1;1 4;hi;1;1 4;hi;1;1 Obviously by using ";" as sep it gives me the error about tokenizing data (obviously from the header less columns are expected), how can i obtain a dataframe like this: col1 col2 col3 col4 4 hello;w...
You could split off the outer cols until you are left with the remaining col2. This could be done in Pandas as follows: import pandas as pd df_raw = pd.read_csv("input.csv", delimiter=None, header=None, skiprows=1) df_raw[['col1', 'rest']] = df_raw[0].str.split(";", n=1, expand=True) df_raw[['col2', 'col3', 'col4']] = ...
3
2
73,953,999
2022-10-4
https://stackoverflow.com/questions/73953999/filter-and-apply-condition-between-multiple-rows
I have the following dataframe: client_id location_id region_name location_name 1 123 Florida location_ABC 6 123 Florida(P) location_ABC 6 845 Miami(P) location_THE 1 386 Boston location_WOP 6 386 Boston(P) location_WOP What I'm trying to do is: If some location_id has more than one client_id, I'll pick the client_id...
You can use idxmax with a custom groupby on the boolean Series equal to your preferred id, then slice: out = df.loc[df['client_id'].eq(1).groupby(df['location_id'], wort=False).idxmax()] output: client_id location_id region_name location_name 0 1 123 Florida location_ABC 2 6 845 Miami(P) location_THE 3 1 386 Boston l...
3
2
73,951,076
2022-10-4
https://stackoverflow.com/questions/73951076/overlay-of-two-imshow-plots-on-top-of-each-other-with-a-slider-to-change-the-op
The code below works to overlay two imshow plots, and to create a slider which changes the value of the global variable OPACITY. Unfortunately, img1.set_data(y); fig.canvas.draw_idle() doesn't redraw the new opacity. How to make an overlay of two imshow plots with a slider to change the opacity of the 2nd layer? impor...
You can re-set the opacity of the overlaying img1 within the update function by img1.set_alpha(): Code: import numpy as np, matplotlib.pyplot as plt, matplotlib.widgets as mpwidgets OPACITY = 0.5 x = np.random.random((100, 50)) y = np.linspace(0, 0.1, 100*50).reshape((100, 50)) # PLOT fig, (ax0, ax1) = plt.subplots(2...
4
2
73,946,012
2022-10-4
https://stackoverflow.com/questions/73946012/using-logging-basicconfig-with-multiple-handlers
I'm trying to understand the behaviour of the logging module when using basicConfig with multiple handlers. My aim is to have warning level on syslog messages, and debug level to a log file. This is my setup: import logging import logging.handlers import os from datetime import datetime log_format = logging.Formatter('...
It's because you need to set a level on the logger, as that's checked first, and if there is further processing to be done, then the event is passed to handlers, where it's checked against their levels. Level on logger - overall verbosity of application Level on handler - verbosity for the destination represented by t...
4
5
73,949,658
2022-10-4
https://stackoverflow.com/questions/73949658/how-can-i-sort-multiple-levels-of-a-pandas-multiindex-with-custom-key-functions
Say I have a dataframe with a MultiIndex like this: import pandas as pd import numpy as np my_index = pd.MultiIndex.from_product( [(3,1,2), ("small", "tall", "medium"), ("B", "A", "C")], names=["number", "size", "letter"] ) df_0 = pd.DataFrame(np.random.rand(27, 2), columns=["x", "y"], index=my_index) x y number size...
The ideal would be to use ordered Categorical data. Else, you can use a custom mapper based on the level name: # define here custom sorters # all other levels will be sorted by default order order = {'size': ['small', 'medium', 'tall']} def sorter(s): if s.name in order: return s.map({k:v for v,k in enumerate(order[s.n...
4
2
73,948,326
2022-10-4
https://stackoverflow.com/questions/73948326/how-to-replace-multiple-substring-at-once-and-not-sequentially
I want to replace multiple substring at once, for instance, in the following statement I want to replace dog with cat and cat with dog: I have a dog but not a cat. However, when I use sequential replace string.replace('dog', 'cat') and then string.replace('cat', 'dog'), I get the following. I have a dog but not a dog. ...
One way using re.sub: import re string = "I have a dog but not a cat." d = {"dog": "cat", "cat": "dog"} new_string = re.sub("|".join(d), lambda x: d[x.group(0)], string) Output: 'I have a cat but not a dog.'
3
10
73,945,687
2022-10-4
https://stackoverflow.com/questions/73945687/delete-duplicates-words-from-column
I have a dataframe like this: df3 = pd.DataFrame({'ID': ['Stay home, T5006, T5006, Stay home', 'Go for walk, T5007, T5007, Go for walk'], 'Name': ['Stay home, Go for walk, Stay home', 'Go outside, Go outside, Go outside'] }) ID Name 0 Stay home, T5006, T5006, Stay home Stay home, Go for walk, Stay home 1 Go for walk, T...
Use dict.fromkey trick for remove duplicates of splitted values, then join by , in lambda function: df3['ID'] = df3['ID'].apply(lambda x: ', '.join(dict.fromkeys(x.split(', ')))) Or use list comprehension: df3['ID'] = [', '.join(dict.fromkeys(x.split(', '))) for x in df3['ID']] print (df3) ID Name 0 Stay home, T5006...
3
2
73,929,564
2022-10-2
https://stackoverflow.com/questions/73929564/entrypoints-object-has-no-attribute-get-digital-ocean
I have made a deplyoment to Digital ocean, on staging (Heroku server) the app is working well, but Digital ocean it's failing with the error below, what could be the issue : AttributeError at /admin/ 'EntryPoints' object has no attribute 'get' Request Method: GET Request URL: https://xxxx/admin/ Django Version: 3.1 Exc...
Because importlib-metadata releases v5.0.0 yesterday which it remove deprecated endpoint. You can set importlib-metadata<5.0 in ur setup.py so it does not install latest version. Or if you use requirements.txt, you can as well set importlib-metadata below version 5.0 e.g importlib-metadata==4.13.0 For more info: https:...
76
116
73,940,751
2022-10-3
https://stackoverflow.com/questions/73940751/why-cant-i-call-a-function-from-another-function-using-exec
say, I have very simple piece of code py = """ a = 1 print (f'before all {a=}') def bar(n): print(f'bye {n=}') def foo(n): print(f'hello {n=}') bar(n) bar ('just works') foo ('sara') """ loc = {} glo = {} bytecode = compile(py, "script", "exec") exec(bytecode, glo, loc) as you can see I defined two functions: bar & fo...
From the docs: If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition. That's not what you want, so don't provide a locals. glo = {} exec(bytecode, glo) Output, for reference: before all a=1 bye n='just works' hello n='sara' bye n='sara'
4
1
73,939,648
2022-10-3
https://stackoverflow.com/questions/73939648/what-is-the-correct-way-to-run-a-pydrake-simulation-online
In Drake/pydrake, all of the examples I have seen create an instance of Simulator and then advance the simulation by a set duration, e.g. sim.AdvanceTo(10) will step the simulation until it has simulated 10 seconds of activity. How can I instead run a simulation indefinitely, where I don't have a specific duration to a...
You can do simulator.AdvanceTo(std::numeric_limits<double>::infinity()); to keep the simulation running indefinitely. https://github.com/RobotLocomotion/drake/tree/master/examples/kuka_iiwa_arm may be helpful as an example.
3
2
73,938,345
2022-10-3
https://stackoverflow.com/questions/73938345/django-rest-framework-integer-field-will-not-accept-empty-response
The models.py IntegerField is set-up: class DMCAModel(models.Model): tick = models.CharField(max_length=20) percent_calc = models.FloatField() ratio = models.IntegerField(blank=True, null=True, default=None) #The problem is here created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, relate...
Inside your serializer, you can use a CharField for the ratio field if you want to send an empty string and then convert to Int in the validation method. class DMCASerializer(serializers.ModelSerializer): ratio = serializers.CharField(required=False, allow_null=True, allow_blank=True) class Meta: model = DMCAModel fiel...
4
1
73,936,433
2022-10-3
https://stackoverflow.com/questions/73936433/python-id-of-function-of-instance-is-inconsistent
Please consider the following class A(object): def foo(self): pass a = A() # accessing a's foo seems consistent init1 = a.foo init2 = a.foo assert init1 == init2 assert id(a.foo) == id(a.foo) # Or is it? foos= [a.foo for i in range(10)] ids = [id(foo) for foo in foos] for i, id_ in enumerate(ids): for j, id__ in enumer...
The transformation of a function to an instance method happens every time the instance method attribute is accessed, so the id should be different every time, at least in the sense that a new object has been created. (see Python Data Model for details about method transformation and descriptors) The problem is doing th...
3
6
73,929,539
2022-10-2
https://stackoverflow.com/questions/73929539/plot-circles-and-scale-them-up-so-the-text-inside-doesnt-go-out-of-the-circle-b
I have some data where i have languages and relative unit size. I want to produce a bubble plot and then export it to PGF. I got most of my code from this answer Making a non-overlapping bubble chart in Matplotlib (circle packing) but I am having the problem that my text exits the circle boundary: How can I either, in...
I think both approaches that you outline are largely equivalent. In both cases, you have to determine the sizes of your text boxes in relation to the sizes of the circles. Getting precise bounding boxes for matplotlib text objects is tricky business, as rendering text objects is done by the backend, not matplotlib itse...
3
3
73,895,789
2022-9-29
https://stackoverflow.com/questions/73895789/plotly-volume-not-rendering-random-distribution-of-points
I have 3D vertices from a third-party data source. The plotly Volume object expects all the coordinates as 1D lists. The examples on their website use the mgrid function to populate the 3D space into the flatten function to get the 1D lists of each axis. https://plotly.com/python/3d-volume-plots/ I don't understand why...
I have not read the documentation closely enough. Draws volume trace between iso-min and iso-max values with coordinates given by four 1-dimensional arrays containing the value, x, y and z of every vertex of a uniform or non-uniform 3-D grid. The input has to be in the form of an orthogonal grid; thus a cloud of rand...
3
2
73,935,184
2022-10-3
https://stackoverflow.com/questions/73935184/generate-all-possible-sequences-of-n-elements-with-sequential-rules
I have a function get_appendable_values(sequence) that takes a sequence (even empty) and returns a list of all the values appendable (as a last element) to that sequence. I need to generate all the possible sequences of 4 elements, with respect to the rules defined in this function and starting with an empty sequence. ...
Yes, recursion is the key. To generate a sequence of size 4, you first generate all sequences of size 3, and add all possible endings to them. Likewise, to generate a sequence of size 3, you need all sequences of size 2... and so forth down to size 0. def get_appendable_values(sequence): '''Dummy rules''' if len(sequen...
3
6
73,934,683
2022-10-3
https://stackoverflow.com/questions/73934683/remove-column-name-suffix-from-dataframe-python
I have the following pandas DataFrame in python: attr_x header example_x other 3232 322 abv ideo 342 123213 ffee iie 232 873213 ffue iie 333 4534 ffpo iieu I want to remove the suffixes '_x' from all columns containing it. The original DataFrame is much longer. Example result: attr header example ...
Use str.removesuffix: df.columns = df.columns.str.removesuffix("_x") Or replace: df.columns = df.columns.str.replace(r'_x$', '')
3
3
73,932,808
2022-10-3
https://stackoverflow.com/questions/73932808/load-gitlab-ci-yml-with-pyyaml-fails-with-could-not-determine-constructor
Loading .gitlab-ci.yml fails when I try to load it with yaml.load. yaml.constructor.ConstructorError: could not determine a constructor for the tag '!reference' in "python.yml", line 9, column 7 That's the yaml I try to load. .python: before_script: - pip install -r requirements.txt script: - echo "Hello Python!" test...
Upgrade to ruamel.yaml>=0.15.x yaml_str = """ .python: before_script: - pip install -r requirements.txt script: - echo "Hello Python!" test: before_script: - !reference [.python, before_script] script: - pytest """ from ruamel.yaml import YAML yaml = YAML() yaml.preserve_quotes = True data = yaml.load(yaml_str)
3
1
73,931,204
2022-10-3
https://stackoverflow.com/questions/73931204/new-column-based-on-interaction-of-two-related-past-rows-in-pandas-dataframe
I have a dataframe of race results of MMA fighters sorted in descending order of date that looks like Race_ID Fighter_ID Date Result 1 1 2022-05-17 1 1 2 2022-05-17 0 2 1 2022-04-17 0 2 3 2022-04-17 1 3 2 2022-03-11 1 3 1 2022-03-11 0 4 2 2022-02-11 1 4 4 2022-02-11 0 5 3 2022-02-08 1 5 1 2022-02-08 0 6 2 2022-01-11 1 ...
Simplier solution is create helper Series by frozenset and used for DataFrameGroupBy.shift: g = df['Race_ID'].map(df.groupby('Race_ID')['Fighter_ID'].agg(frozenset)) df['History'] = df.groupby(['Fighter_ID', g])['Result'].shift(-1, fill_value=0) print (df) Race_ID Fighter_ID Date Result History 0 1 1 2022-05-17 1 0 1 1...
3
4
73,924,768
2022-10-2
https://stackoverflow.com/questions/73924768/attributeerror-module-flax-has-no-attribute-nn
I'm trying to run RegNeRF, which requires flax. On installing the latest version of flax==0.6.0, I got an error stating flax has no attribute optim. This answer suggested to downgrade flax to 0.5.1. On doing that, now I'm getting the error AttributeError: module 'flax' has no attribute 'nn' I could not find any solutio...
The flax.optim module has been moved to optax as of flax version 0.6.0; see Upgrading my Codebase to Optax for information on how to migrate your code. If you're using external code that imports flax.optim and can't update these references, you'll have to install flax version 0.5.3 or older. Regarding flax.nn: this mod...
6
4
73,923,051
2022-10-2
https://stackoverflow.com/questions/73923051/cannot-convert-base64-string-into-image
Can someone help me turn this base64 data into image? I don't know if it's because the data was not decoded properly or anything else. Here is how I decoded the data: import base64 c_data = { the data in the link (string type) } c_decoded = base64.b64decode(c_data) But it gave the error Incorrect Padding so I followed...
Not sure if you definitely need a Python solution, or you just want help decoding your image like the first line of your question says, and you thought Python might be needed. If the latter, you can just use ImageMagick in the Terminal: cat YOURFILE.TXT | magick inline:- result.png Or equivalently and avoiding "Usele...
4
3
73,922,260
2022-10-1
https://stackoverflow.com/questions/73922260/how-can-i-trigger-same-cloud-run-job-service-using-different-arguments
I'm trying to make a scrapy scraper work using cloud run. The main idea is that every 20 minutes a cloud scheduler cron should trigger the web scraper and get data from different sites. All sites have the same structure, so I would like to use same code and parallelize the execution of the scraping job, doing something...
According to that page of documentation, there is a trick. Define a number of task, let's say, you set the number of task equal to the number of site to scrap. use the --task parameter for that In your container (or in Cloud Storage, but if you do that, you have to download the file before starting the process), add a...
4
1
73,918,802
2022-10-1
https://stackoverflow.com/questions/73918802/valueerror-x-and-y-must-have-same-first-dimension-but-have-shapes-100-and
I'm trying to plot a simple function using python, numpy and matplotlib but when I execute the script it returns a ValueError described in the title. This is my code: """Geometrical interpretation: In Python, plot the function y = f(x) = x**3 − (1/x) and plot its tangent line at x = 1 and at x = 2.""" import numpy as n...
This was a good effort actually. You only needed to add the y variable using y=func(x). And then plt.plot(x,y)... so this works: import numpy as np import matplotlib.pyplot as plt def plot(func): plt.figure(figsize=(12, 8)) x = np.linspace(-100, 100, 100) y = func(x) plt.plot(x, y, '-', color='pink') plt.show() plt.clo...
7
5
73,898,903
2022-9-29
https://stackoverflow.com/questions/73898903/how-do-i-get-pyenv-to-display-the-executable-path-for-an-installed-version
Install a python version using: $ pyenv install 3.8.9 Installed Python-3.8.9 to /Users/robino/.pyenv/versions/3.8.9 List the python versions now available: $ pyenv versions * system 3.8.2 3.8.9 A week goes by and I forget where it is installed. Now suppose I want to get the executable path for 3.8.9 version. The foll...
By default, pyenv executable can be found at $(pyenv root)/versions/{VERSION}/bin/python. I am not aware of a command displaying all/any executables other than pyenv which python. If you'd like to get the path via commands though, another option would be to make a temporary subdirectory and set the local pyenv interpre...
16
21
73,914,281
2022-9-30
https://stackoverflow.com/questions/73914281/julia-transpose-grouped-data-passing-tuple-of-column-selectors
ds = Dataset([[1, 1, 1, 2, 2, 2], ["foo", "bar", "monty", "foo", "bar", "monty"], ["a", "b", "c", "d", "e", "f"], [1, 2, 3, 4, 5, 6]], [:g, :key, :foo, :bar]) In InmemoryDatasets, the transpose function can Pass Tuple of column selectors. transpose(groupby(ds, :g), (:foo, :bar), id = :key) Result: g foo bar monty foo...
In R, pivot_wider can be used for reshaping. library(tidyr) pivot_wider(ds, names_from = key, values_from = c(foo, bar)) -output # A tibble: 2 × 7 g foo_foo foo_bar foo_monty bar_foo bar_bar bar_monty <dbl> <chr> <chr> <chr> <int> <int> <int> 1 1 a b c 1 2 3 2 2 d e f 4 5 6 If we want to get the same column names, w...
3
5
73,914,589
2022-9-30
https://stackoverflow.com/questions/73914589/filter-and-move-text-in-another-column-in-substring
I have the following dataset: df = pd.DataFrame([ {'Phone': 'Fax(925) 482-1195', 'Fax': None}, {'Phone': 'Fax(406) 226-0317', 'Fax': None}, {'Phone': 'Fax+1 650-383-6305', 'Fax': None}, {'Phone': 'Phone(334) 585-1171', 'Fax': 'Fax(334) 585-1182'}, {'Phone': None, 'Fax': None}, {'Phone': 'Phone(334) 585-1171', 'Fax': 'F...
You have a bunch of rows, that is, a list of dicts. Simplest approach would be to massage each row prior to adding it to the dataframe. rows = [ ... ] def get_contacts(rows): for row in rows: phone, fax = row['Phone'], row['Fax'] if 'Fax' in phone: phone, fax = None, phone yield phone, fax df = pd.DataFrame(get_contact...
3
2
73,907,111
2022-9-30
https://stackoverflow.com/questions/73907111/exclude-multiple-marked-tests-with-pytest-from-command-line
I have the following in my pyproject.toml [tool.pytest.ini_options] markers = [ "plot: marks SLOW plot tests (deselect with '-m \"not plot\"')", "open_tutorial: marks the open_tutorial (which opens VSCode all the times)" ] and I have a bunch of test methods marked accordingly. If I run coverage run --branch -m pytest ...
According to pytest help: -m MARKEXPR only run tests matching given mark expression. For example: -m 'mark1 and not mark2'. If you want to use more than one marker you should use the and operator. pytest -m "not open_tutorial and not plot" will run all test without marks: open_tutorial and plot but: pytest -m "not o...
11
19
73,910,742
2022-9-30
https://stackoverflow.com/questions/73910742/why-is-my-python-decorator-classs-get-method-not-called-in-all-cases
So I'm trying to implement something akin to C# events in Python as a decorator for methods: from __future__ import annotations from typing import * import functools def event(function: Callable) -> EventDispatcher: return EventDispatcher(function) class EventDispatcher: def __init__(self, function: Callable) -> None: ...
The problem lies in the initializer of B: a.my_event += self.my_callback Note that the += operator is not just a simple call to __iadd__, but actually equivalent to: a.my_event = a.my_event.__iadd__(self.my_callback) This is also the reason why your __iadd__ method needs to return self. Because the class EventDispatc...
3
4
73,910,005
2022-9-30
https://stackoverflow.com/questions/73910005/how-to-sum-an-ndarray-over-ranges-bounded-by-other-indexes
For an array of multiple dimensions, I would like to sum along some dimensions, with the sum range defined by other dimension indexes. Here is an example: >>> import numpy as np >>> x = np.arange(2*3*4).reshape((2,3,4)) >>> x array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [...
You can use boolean masks: # get lower triangles m1 = np.arange(x.shape[1])[:,None]>np.arange(x.shape[2]) # get columns index >= depth index m2 = np.arange(x.shape[2])>=np.arange(x.shape[0])[:,None,None] # combine both mask to form 3D mask mask = m1 & m2 out = np.where(mask, x, 0).sum(axis=2) output: array([[ 0, 4, 17...
6
3
73,907,772
2022-9-30
https://stackoverflow.com/questions/73907772/connect-with-opcua-server-with-basic256sha256-in-python
Te following code is used to connect with the opcua server: from opcua import Client client = Client(url='opc.tcp://192.168.0.5:4840') client.set_user('user1') client.set_password('password') client.connect() Error message: Received an error: MessageAbort(error:StatusCode(BadSecurityPolicyRejected), reason:None) Proto...
You can use this script and adapt it to your needs: https://github.com/FreeOpcUa/python-opcua/blob/master/examples/generate_certificate.sh Also python-opcua is deprecated. So if you start a new project, I would recommend you to use asyncua. Asyncua also has a sync wrapper if you don't want to deal with asyncio.
4
3
73,899,633
2022-9-29
https://stackoverflow.com/questions/73899633/difference-with-nearest-conditional-rows-per-group-using-pandas
I have a dataframe (sample) like this: import pandas as pd data = [['A', '2022-09-01', False, 2], ['A', '2022-09-02', False, 3], ['A', '2022-09-03', True, 1], ['A', '2022-09-05', False, 4], ['A', '2022-09-08', True, 4], ['A', '2022-09-09', False, 2], ['B', '2022-09-03', False, 4], ['B', '2022-09-05', True, 5], ['B', '2...
IIUC use merge_asof with filtered rows by indicator and subtract column val: df['date'] = pd.to_datetime(df['date'] ) df = df.sort_values('date') df['Diff'] = df['val'].sub(pd.merge_asof(df, df[df['indicator']], on='date', by='group', direction='nearest')['val_y']) df = df.sort_index()
3
4
73,900,229
2022-9-29
https://stackoverflow.com/questions/73900229/in-a-new-project-graphene-or-strawberry-why
which lib is better to integrate with a new django project? i red the docs and still doesnt know how performatic or easier to integrate each one can be in prod environment. i used graphene before to integrate with some pipefy code that i did at work but im pretty new in graphql and dont know at this point what way i sh...
I'm the maintainer of Strawberry, so there might be some bias in my answer 😊 Both Strawberry and Graphene are based on GraphQL-core which is the library that provides the GraphQL execution, so in terms of performance they are comparable. For Strawberry we have a performance dashboard here: https://speed.strawberry.roc...
7
17
73,905,610
2022-9-30
https://stackoverflow.com/questions/73905610/how-to-generate-color-based-on-the-magnitude-of-the-values-in-python
I am trying to make a Bar plot in python so that the color of each bar is set based on the magnitude of that value. For example the list below is our numbers: List = [2,10,18,50, 100, ... 500] In this situation 2 should have the lightest color and 500 should have the darkest color values. The picture below which is fr...
Then you can use a Colormap (extra docs) from matplotlib In this example the bar_colors list is being creating with a scale between 0 and 100 but you can choose the scale as you want. import matplotlib.pyplot as plt import matplotlib.colors fig, ax = plt.subplots() names= ['A', 'B', 'C', 'D', 'E'] counts = [10, 30, 40,...
3
4
73,902,239
2022-9-29
https://stackoverflow.com/questions/73902239/indexing-python-dict-with-string-keys-using-enums
Is there a way to index a dict using an enum? e.g. I have the following Enum and dict: class STATUS(Enum): ACTIVE = "active" d = { "active": 1 } I'd like to add the appropriate logic to the class STATUS in order to get the following result: d[STATUS.ACTIVE] # returns 1 I understand that the type of STATUS.ACTIVE is n...
@ElmovanKielmo solution will work, however you can also achieve your desired result by making the STATUS Enum derive from str as well from enum import Enum class STATUS(str, Enum): ACTIVE = "active" d = {"active": 1} print(d[STATUS.ACTIVE]) # prints 1 Please keep in mind, that when inheriting from str, or any other ty...
5
7
73,898,848
2022-9-29
https://stackoverflow.com/questions/73898848/how-to-add-an-image-as-the-background-to-a-matplotlib-figure-not-to-plots-but
I am trying to add an image to the "whitespace" behind the various subplots of a matplotlib figure. Most discussions similar to this topic are to add images to the plots themselves, however I have not yet come across a means to change the background of the overall "canvas". The most similar function I have found is set...
You can use a dummy subplot, with the same size as the figure, and plot the background onto that subplot. import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np image = plt.imread('test.jpg') # make ticks white, for readability on colored background mpl.rcParams.update({'xtick.color': "white", 'yti...
4
7
73,900,510
2022-9-29
https://stackoverflow.com/questions/73900510/multiple-python-versions-in-the-same-ubuntu-machine
I am on an Ubuntu machine, where Python 3.10 is automatically installed. To do a given task in a shared codebase I need to use Python 3.9 for some issues with new versions. I would like to have both of the Python installed on my machine and be able to use both and switching if I need to. So, I am trying to install old ...
Python should be installed under the /usr/bin/ folder. If it's not there, you might have not actually installed the package. Check out this guide for installing specific versions (Scroll down to the "Use Deadsnakes PPA to Install Python 3 on Ubuntu" section.) This will allow you to install specific version of python li...
8
3
73,899,974
2022-9-29
https://stackoverflow.com/questions/73899974/pandas-create-multiple-rows-of-dummy-data-from-one-row
I'm building a machine learning model and I need to populate a test dataframe with synthetic data. I have time series data that currently looks like this: Date DayOfWeek Unit 2022-10-01 7 A 2022-10-02 1 A 2022-10-03 2 A What I need is to duplicate all the date rows, but I need a row for each 'Unit' (A,B,C,D) like this...
Suggest using itertools.product for the purpose: from itertools import product df = pd.DataFrame( data=product( pd.Series(pd.date_range('2022-10-01', '2022-10-03', freq='D')), "ABCD" ), columns=("Date", "Unit"), ) df["DayOfWeek"] = df["Date"].dt.dayofweek.add(1) # To Have Day of Week Starting with 1 df = df[["Date", "D...
3
2
73,899,080
2022-9-29
https://stackoverflow.com/questions/73899080/remove-duplicate-words-in-the-same-cell-within-a-column-in-python
i need somebody's help, i have a column with words, i want to remove the duplicated words inside each cell what i want to get is something like this words expected car apple car good car apple good good bad well good good bad well car apple bus food car apple bus food i've tried this but is not working ...
If you don't need to retain the original order of the words, you can create an intermediate set which will remove duplicates. df["expected"] = df["words"].str.split().apply(set).str.join(" ")
3
2
73,896,757
2022-9-29
https://stackoverflow.com/questions/73896757/pandas-regex-look-ahead-and-behind-from-a-1st-occurrence-of-character
I have python strings like below "1234_4534_41247612_2462184_2131_GHI.xlsx" "1234_4534__sfhaksj_DHJKhd_hJD_41247612_2462184_2131_PQRST.GHI.xlsx" "12JSAF34_45aAF34__sfhaksj_DHJKhd_hJD_41247612_2f462184_2131_JKLMN.OPQ.xlsx" "1234_4534__sfhaksj_DHJKhd_hJD_41FA247612_2462184_2131_WXY.TUV.xlsx" I would like to do the below...
Try (regex101): import re strings = [ "1234_4534_41247612_2462184_2131_ABCDEF.GHI.xlsx", "1234_4534__sfhaksj_DHJKhd_hJD_41247612_2462184_2131_PQRST.GHI.xlsx", "12JSAF34_45aAF34__sfhaksj_DHJKhd_hJD_41247612_2f462184_2131_JKLMN.OPQ.xlsx", "1234_4534__sfhaksj_DHJKhd_hJD_41FA247612_2462184_2131_WXY.TUV.xlsx", ] pat = re.co...
3
2
73,887,700
2022-9-28
https://stackoverflow.com/questions/73887700/is-there-a-way-to-unstack-a-dataframe-and-return-as-a-list-value
I have a dataframe looks like this: import pandas as pd df = pd.DataFrame({'type_a': [1,0,0,0,0,1,0,0,0,1], 'type_b': [0,1,0,0,0,0,0,0,1,1], 'type_c': [0,0,1,1,1,1,0,0,0,0], 'type_d': [1,0,0,0,0,1,1,0,1,0], }) I wanna create a new column based on those 4 columns, it will return the column names whenever the value in t...
This is also another way: import pandas as pd df['type'] = (pd.melt(df.reset_index(), id_vars='index') .query('value == 1') .groupby('index')['variable'] .apply(list)) type_a type_b type_c type_d type 0 1 0 0 1 [type_a, type_d] 1 0 1 0 0 [type_b] 2 0 0 1 0 [type_c] 3 0 0 1 0 [type_c] 4 0 0 1 0 [type_c] 5 1 0 1 1 [type_...
3
4
73,889,060
2022-9-29
https://stackoverflow.com/questions/73889060/python-pandas-timedelta-for-one-month
Is there a way to do a Timedelta for one month? Applying pd.Timedelta('1M') yields Timedelta('0 days 00:01:00'). Is there a code word for month?
Timedelta is for absolute offsets. A month "offset", by definition, might have different lengths depending on the value it's applied to. For those cases, you should use DateOffset: pandas.DateOffset(months=1) Functional example: import pandas as pd pd.Timestamp('2022-09-29 00:27:00') + pd.DateOffset(months=1) >>> Times...
6
6
73,888,639
2022-9-28
https://stackoverflow.com/questions/73888639/why-is-this-unpacking-expression-not-allowed-in-python3-10
I used to unpack a long iterable expression like this: In python 3.8.7: >>> _, a, (*_), c = [1,2,3,4,5,6] >>> a 2 >>> c 6 In python 3.10.7: >>> _, a, (*_), c = [1,2,3,4,5,6] File "<stdin>", line 1 _, a, (*_), c = [1,2,3,4,5,6] ^^ SyntaxError: cannot use starred expression here I'm not sure which version of python bet...
There's an official discussion here. The most relevant quote I can find is: Also the current behavior allows (*x), y = 1 assignment. If (*x) is to be totally disallowed, (*x), y = 1 should also be rejected. I agree. The final "I agree" is from Guido van Rossum. The rationale for rejecting (*x) was: Honestly this...
6
6
73,883,435
2022-9-28
https://stackoverflow.com/questions/73883435/is-python-3-path-write-text-from-pathlib-atomic
I was wondering if the Path.write_text(data) function from pathlib was atomic or not. If not, are there scenarios where we could end up with a file created in the filesystem but not containing the intended content? To be more specific, as the comment from @ShadowRanger suggested what I care about is to know if the file...
On the specific case of the file containing the original data or the new data, and nothing in between: No, it does not do any tricks with opening a temp file in the same directory, populating it, and finishing with an atomic rename to replace the original file. The current implementation is guaranteed to be at least tw...
3
2
73,879,229
2022-9-28
https://stackoverflow.com/questions/73879229/pydantic-perform-full-validation-and-dont-stop-at-the-first-error
Is there a way in Pydatic to perform the full validation of my classes? And return all the possible errors? It seems that the standard behaviour blocks the validation at the first encountered error. As an example: from pydantic import BaseModel class Salary(BaseModel): gross: int net: int tax: int class Employee(BaseMo...
What you are describing is not Pydantic-specific behavior. This is how exceptions in Python work. As soon as one is raised (and is not caught somewhere up the stack), execution stops. Validation is triggered, when you attempt to initialize a Salary instance. Failed validation triggers the ValidationError. The Python in...
5
3
73,882,042
2022-9-28
https://stackoverflow.com/questions/73882042/how-to-count-the-adjacent-values-with-values-of-1-in-a-geotiff-array
Let's that we have geotiff of 0 and 1. import rasterio src = rasterio.open('myData.tif') data = src.read(1) data array([[0, 1, 1, 0], [1, 0, 0, 1], [0, 0, 1, 0], [1, 0, 1, 1]]) I would like to have for each pixel 1 the sum of all adjacent pixels forming a cluster of ones and to have something like the following: array...
You can use scipy.ndimage.label: from scipy.ndimage import label out = np.zeros_like(data) labels, N = label(data) for i in range(N): mask = labels==i+1 out[mask] = mask.sum() output: array([[0, 2, 2, 0], [1, 0, 0, 1], [0, 0, 3, 0], [1, 0, 3, 3]])
3
2
73,876,937
2022-9-28
https://stackoverflow.com/questions/73876937/what-is-the-difference-between-keyword-pass-and-in-python
Is there any significant difference between the two Python keywords (...) and (pass) like in the examples def tempFunction(): pass and def tempFunction(): ... I should be aware of?
The ... is the shorthand for the Ellipsis global object in python. Similar to None and NotImplemented it can be used as a marker value to indicate the absence of something. For example: print(...) # Prints "Ellipsis" In this case, it has no effect. You could put any constant there and it would do the same. This is val...
7
5
73,876,790
2022-9-28
https://stackoverflow.com/questions/73876790/poetry-configuration-is-invalid-additional-properties-are-not-allowed-group
Recently, I faced this issue with Poetry. All my commands using poetry were failing with the following error. RuntimeError The Poetry configuration is invalid: - Additional properties are not allowed ('group' was unexpected)
I figured out the following issue. The code owners had updated the poetry core requirement to requires = ["poetry-core>=1.2.0"] My current poetry version was 1.1.12 I did the following to fix my issue. # remove the current poetry installation rm -rf /Users/myusername/.poetry # upgrade poetry version pip install poetr...
58
68
73,807,634
2022-9-21
https://stackoverflow.com/questions/73807634/how-can-i-select-a-button-contained-within-an-iframe-in-playwright-python-by-i
I am attempting to select a button within an iframe utilizing Python & Playwright... in Selenium I know you can do this by using indexes. Is this possible in playwright? I've been digging through the documentation and can't seem to figure it out. The button contained within the iframe that I am trying to select is: "bu...
From what I understand, you have a page that has content within an iframe. You want to use Playwright to access elements within that frame. The official docs to handle frames: Official docs: https://playwright.dev/python/docs/frames You could then try something like this: // Locate element inside frame const iframeButt...
7
12
73,830,524
2022-9-23
https://stackoverflow.com/questions/73830524/attributeerror-module-lib-has-no-attribute-x509-v-flag-cb-issuer-check
Recently I had to reinstall Python due to a corrupt executable. This made one of our Python scripts bomb with the following error: AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK' The line of code that caused it to bomb was: from apiclient.discovery import build I tried pip uninstalling an...
Upgrade the latest version of PyOpenSSL. python3 -m pip install pip --upgrade pip install pyopenssl --upgrade
188
306
73,822,353
2022-9-23
https://stackoverflow.com/questions/73822353/how-can-i-get-word-level-timestamps-in-openais-whisper-asr
I use OpenAI's Whisper python lib for speech recognition. How can I get word-level timestamps? To transcribe with OpenAI's Whisper (tested on Ubuntu 20.04 x64 LTS with an Nvidia GeForce RTX 3090): conda create -y --name whisperpy39 python==3.9 conda activate whisperpy39 pip install git+https://github.com/openai/whispe...
In openai-whisper version 20231117, you can get word level timestamps by setting word_timestamps=True when calling transcribe(): pip install openai-whisper import whisper model = whisper.load_model("large") transcript = model.transcribe( word_timestamps=True, audio="toto.mp3" ) for segment in transcript['segments']: p...
21
13
73,803,605
2022-9-21
https://stackoverflow.com/questions/73803605/psycopg2-programmingerror-the-connection-cannot-be-re-entered-recursively
Am calling an endpoint from flask using fetch api from react. I keep getting psycopg2.ProgrammingError: the connection cannot be re-entered recursively I the endpoint call is inside a loop. @app.get("/api/plot-project/<int:plot_id>/<int:project_id>") def check_and_deactivate(plot_id, project_id): with connection: with ...
This error happens when you are trying to call the context manager of the same connection, which is already called in the context manager. To fix that issue you have few options: To use the same connection without context manager and to commit or rollback changes. The code will look like: try: result = None with con...
5
2
73,810,377
2022-9-22
https://stackoverflow.com/questions/73810377/how-to-save-an-uploaded-image-to-fastapi-using-python-imaging-library-pil
I am using image compression to reduce the image size. When submitting the post request, I am not getting any error, but can't figure out why the images do not get saved. Here is my code: @app.post("/post_ads") async def create_upload_files(title: str = Form(),body: str = Form(), db: Session = Depends(get_db), files: l...
PIL.Image.open() takes as fp argumnet the following: fp – A filename (string), pathlib.Path object or a file object. The file object must implement file.read(), file.seek(), and file.tell() methods, and be opened in binary mode. Using a BytesIO stream, you would need to have something like the below (as shown in clie...
3
8
73,856,901
2022-9-26
https://stackoverflow.com/questions/73856901/how-can-i-use-paramspec-with-method-decorators
I was following the example from PEP 0612 (last one in the Motivation section) to create a decorator that can add default parameters to a function. The problem is, the example provided only works for functions but not methods, because Concate doesn't allow inserting self anywhere in the definition. Consider this exampl...
There is surprisingly little about this online. I was able to find someone else's discussion of this over at python/typing's Github, which I distilled using your example. The crux of this solution is Callback Protocols, which are functionally equivalent to Callable, but additionally enable us to modify the return type ...
8
14
73,829,894
2022-9-23
https://stackoverflow.com/questions/73829894/plotly-figure-how-to-get-the-number-of-rows-and-cols
I create a Plotly Figure instance this way: fig = go.Figure() fig = make_subplots(rows=3, cols=1, shared_xaxes=True, row_width=[0.3, 0.3, 0.4]) Lets assume that now I do not know how many rows and cols the Figure instance has. How can I obtain these values? For example, I expect something like this: rows = fig.get_row...
I had the same use case come up! I was happy to find you can do this: rows, cols = fig._get_subplot_rows_columns()
5
11
73,852,273
2022-9-26
https://stackoverflow.com/questions/73852273/openpyxl-not-found-in-exe-file-made-with-pyinstaller
I wrote a Python code using a virtual evn with pip, and I built it with pyinstaller to use it as executable, and it works. Now I'm moving to conda environment to use also geopandas, fiona and gdal. I can run it without any errors, but if I build the code into the .exe, this error raised: Traceback (most recent call las...
The error is referring to 'openpyxl.cell._writer' that is inside openpyxl. in fact, pyinstaller was actually able to find openpyxl. I checked inside, and I found that in the pip environment i was using the 3.0.9 version, while in the conda one I was using the 3.0.10. Downgrading to 3.0.9, no --hidden-import or other ne...
4
2
73,830,225
2022-9-23
https://stackoverflow.com/questions/73830225/init-got-an-unexpected-keyword-argument-cachedir-when-importing-top2vec
I keep getting this error when importing top2vec. TypeError Traceback (most recent call last) Cell In [1], line 1 ----> 1 from top2vec import Top2Vec File ~\AppData\Roaming\Python\Python39\site-packages\top2vec\__init__.py:1 ----> 1 from top2vec.Top2Vec import Top2Vec 3 __version__ = '1.0.27' File ~\AppData\Roaming\Pyt...
UPDATE 12 November 2022: There is new release (ver. 0.8.29) of hdbscan from 31 Oct. 2022 that fix the issue. See my original answer for more details. Original Answer: It looks like you are using latest (as of 23 Sept 2022) versions of hdbscan and joblib packages available on PyPI. cachedir was removed from joblib.Mem...
12
21
73,823,743
2022-9-23
https://stackoverflow.com/questions/73823743/attributeerror-module-rest-framework-serializers-has-no-attribute-nullboolea
After upgrading djangorestframework from djangorestframework==3.13.1 to djangorestframework==3.14.0 the code from rest_framework.serializers import NullBooleanField Throws AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField' Reading the release notes I don't see a deprecation. Wher...
For what it's worth, there's a deprecation warning in the previous version, which also suggests a fix: The NullBooleanField is deprecated and will be removed starting with 3.14. Instead use the BooleanField field and set allow_null=True which does the same thing.
7
4
73,860,427
2022-9-26
https://stackoverflow.com/questions/73860427/how-to-use-the-python-packaging-library-with-a-custom-regex
I'm trying to build and tag artifacts, the environment name gets appended at the end of the release, e.g.: 1.0.0-stg or 1.0.0-sndbx, none of them are PEP-440 compliance, raising the following error message: raise InvalidVersion(f"Invalid version: '{version}'") packaging.version.InvalidVersion: Invalid version: '1.0.0-s...
The original value of the version.VERSION_PATTERN has used regex groups to separate the types of the version. And if you see the pattern, it defines three types of releases: pre-release, post-release, and dev release. v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # p...
4
2
73,820,642
2022-9-22
https://stackoverflow.com/questions/73820642/always-defer-a-field-in-django
How do I make a field on a Django model deferred for all queries of that model without needing to put a defer on every query? Research This was requested as a feature in 2014 and rejected in 2022. Baring such a feature native to Django, the obvious idea is to make a custom manager like this: class DeferedFieldManager(m...
Set Meta.base_manager_name to 'objects'. class A(models.Model): big_field = models.TextField(null=True) b = models.ForeignKey(B, related_name="a_s") objects = DeferedFieldManager(["big_field"]) class Meta: base_manager_name = 'objects' From https://docs.djangoproject.com/en/4.1/topics/db/managers/#using-managers-for-r...
9
4
73,864,714
2022-9-27
https://stackoverflow.com/questions/73864714/python-can-bring-window-to-front-but-cannot-set-focus-win32gui-setforegroundwi
My program pops up a window every time the user presses F2 (in any application). I'm using pynput to capture the F2 button (works ok) I'm using tkinter to create the popup window (works ok) I'm using win32gui.SetForegroundWindow(windowHandel) to bring the tkinter window to the front and set the focus. And there is the ...
What you see is an intentional restriction in Windows. The restriction is described by Raymond Chen in article Foreground activation permission is like love: You can’t steal it, it has to be given to you. Remarks section of the SetForegroundWindow documentation gives more technical details about the restriction. There ...
3
5
73,838,387
2022-9-24
https://stackoverflow.com/questions/73838387/pandas-add-dataframes-columns-names-to-rows-after-join-procedure
I have the following dataframe: df1 = pd.DataFrame({'ID' : ['T1002.', 'T5006.', 'T5007.'], 'Parent': ['Stay home.', "Stay home.","Stay home."], 'Child' : ['2Severe weather.', "5847.", "Severe weather."]}) ID Parent Child 0 T1002. Stay home. 2Severe weather. 1 T5006. Stay home. 5847. 2 T5007. Stay home. Severe weather. ...
I want to add the two columns into one and also add the columns' name into the rows. I want also the columns names to be in bold. i would like to have the bold text on Excel. applying formats to substrings within cells in an excel worksheet requires writing a rich string It is necessary to construct a list of rich ...
3
4
73,840,143
2022-9-24
https://stackoverflow.com/questions/73840143/in-pytorch-how-do-i-update-a-neural-network-via-the-average-gradient-from-a-lis
I have a toy reinforcement learning project based on the REINFORCE algorithm (here's PyTorch's implementation) that I would like to add batch updates to. In RL, the "target" can only be created after a "prediction" has been made, so standard batching techniques do not apply. As such, I accrue losses for each episode an...
Gradient is a linear operation so gradient of the average is the same as the average of the gradient. Take some example data import torch a = torch.randn(1, 4, requires_grad=True); b = torch.randn(5, 4); You could store all the losses and compute the mean as you are doing, a.grad = None x = (a * b).mean(axis=1) x.mean...
4
3
73,854,849
2022-9-26
https://stackoverflow.com/questions/73854849/instantiate-threading-within-a-class
I have a class within a class and want to activate threading capabilities in the second class. Essentially, the script below is a reproducible template of my proper project. When I use @threading I get that showit is not iterable, so the tp.map thinks I do not have a list. However, when I run: if __name__ == '__main__'...
Considerations: Writing a decorator that takes an optional argument needs to be done a bit differently than the way you have done it. I am assuming you would like the threaded decorator to be able to support both functions and methods if that is not to difficult to accomplish. The decorated function/method can take a...
3
2
73,825,424
2022-9-23
https://stackoverflow.com/questions/73825424/type-annotation-for-an-iterable-class
I've got a class that extends ElementTree.Element: import xml.etree.ElementTree as ET from typing import cast class MyElement(ET.Element): def my_method(self): print('OK') xml = '''<test> <sub/> <sub/> </test>''' root: MyElement = cast( MyElement, ET.fromstring(xml, parser=ET.XMLParser(target=ET.TreeBuilder(element_fac...
Annotate the __iter__ of MyElement as a method to return Iterator[MyElement]. There is almost no additional runtime overhead. Pycharm and mypy will both pass: from collections.abc import Callable, Iterator class MyElement(ET.Element): def my_method(self): print('OK') __iter__: Callable[..., Iterator['MyElement']]
4
5
73,819,773
2022-9-22
https://stackoverflow.com/questions/73819773/pandas-comparing-2-dataframes-without-iterating
Considering I have 2 dataframes as shown below (DF1 and DF2), I need to compare DF2 with DF1 such that I can identify all the Matching, Different, Missing values for all the columns in DF2 that match columns in DF1 (Col1, Col2 & Col3 in this case) for rows with same EID value (A, B, C & D). I do not wish to iterate on ...
Firstly, you will need to filter df1 based on df2. new_df = df1.loc[df1['EID'].isin(df2['EID']), df2.columns] EID Col1 Col2 Col3 0 A a1 b1 c1 1 B a2 b2 c2 2 C None b3 c3 3 D a4 b4 c4 Next, since you have a big dataframe to compare, you can change both the new_df and df2 to numpy arrays. array1 = new_df.to_numpy() arra...
3
5
73,816,296
2022-9-22
https://stackoverflow.com/questions/73816296/password-field-is-visible-and-not-encrypted-in-django-admin-site
So to use email as username I override the build-in User model like this (inspired by Django source code) models.py class User(AbstractUser): username = None email = models.EmailField(unique=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email admin.py @admin...
You are not able to see the password in hashed state because the password field is a CharField which renders it as normal text field. In Django's admin side there's a field called ReadOnlyPasswordHashField in django.contrib.auth.forms which renders the password field to be in hashed state with password change link. Dja...
3
3
73,871,485
2022-9-27
https://stackoverflow.com/questions/73871485/how-to-remove-pytest-no-header-no-summary-q-parameters-in-pycharm
I see the parameters for running a default-settings pytest configuration are as follows: Launching pytest with arguments payments/tests/test_edd_countries.py --no-header --no-summary -q in payments/tests I would like to remove all of those parameters specifically: --no-header --no-summary -q How can that be achieved ...
The parameters --no-header --no-summary -q are added as an IDE setting (they aren't set in Run Configurations). They can be configured by going to File > Settings > Advanced Settings > Python and checking the option Pytest: do not add "--no-header --no-summary -q" as shown in the screenshot:
11
15
73,871,993
2022-9-27
https://stackoverflow.com/questions/73871993/does-python-cache-items-in-the-same-line-and-use-again-later
With this line: print(sum(tuple), len(tuple), sum(tuple)/len(tuple)) Will python cache sum(tuple) in the 0 index and use it in the average calculation (2 index)? Or will with calculate sum(tuple) again?
Python won't perform this optimization for you. You can see this by defining your own function instead of sum and observing the side effect: import functools def my_sum(x): print('my sum') return functools.reduce(lambda a, b: a + b, x) tup = (1, 2, 3) print(my_sum(tup), len(tup), my_sum(tup)/len(tup)) If you run this ...
3
3
73,868,794
2022-9-27
https://stackoverflow.com/questions/73868794/pandas-normalize-values-by-group
I find it hard to explain with words what I want to achieve, so please don't judge me for showing a simple example instead. I have a table that looks like this: main_col some_metadata value this True 10 this False 3 that True 50 that False 10 other True 20 other False 5 I want to normalize this da...
You can use groupby.transform('max') to get the max per group, then normalize in place: df['value'] /= df.groupby('main_col')['value'].transform('max').div(100) or: df['value'] *= df.groupby('main_col')['value'].transform('max').rdiv(100) output: main_col some_metadata value 0 this True 100.0 1 this False 30.0 2 tha...
5
5
73,858,980
2022-9-26
https://stackoverflow.com/questions/73858980/postgres-suddenly-raise-error-usr-lib-libpq-5-dylib-no-such-file
when I run Django project or any code related to Postgres : Referenced from: '/Users/mahmoudnasser/.local/share/virtualenvs/wyspp_backend-PwdII1PB/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so' Reason: tried: '/opt/homebrew/opt/postgresql/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.d...
To solve this problem just run the following command: sudo mkdir -p /usr/local/lib && sudo ln -s /opt/homebrew/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib /usr/local/lib/libpq.5.dylib
14
19
73,851,205
2022-9-26
https://stackoverflow.com/questions/73851205/django-q-objects-vs-python-code-better-performance
What would provide better performance using filtering conditions with Q in django ORM or simply fetching unfiltered objects and comparing in python. employee_qs = employee.objects.filter(state=States.ACTIVE, topic_assn__topic_id=instance.ss_topic_id).select_related('c_data').filter( Q(c_data__is_null=True) | Q(c_budget...
TLDR: Q objects will be faster. Why? Well filtering done with Q object will be done on the SQL server (either PostgreSQL, MariaDB). So two aspects should be considered: with Q objects, unfiltered data will not be transferred from your database to your django server (less data over the network make things faster) ; Q o...
4
11
73,848,347
2022-9-25
https://stackoverflow.com/questions/73848347/difference-in-time-between-successive-dataframe-rows
Similar to this question, I would like to compute the time difference between rows of a dataframe. Unlike that question however, the difference should be by groupby id. So foe example, this dataframe: df = pd.DataFrame( {'id': [6,6,6,6,6,10,10,10,10,10], 'timestamp': ['2016-04-01 00:04:00','2016-04-01 00:04:20','2016-0...
df.groupby('id')['timestamp'].diff().dt.total_seconds().fillna(0)
3
3
73,843,523
2022-9-25
https://stackoverflow.com/questions/73843523/implementing-from-scratch-cv2-warpperspective
I was making some experimentations with the OpenCV function cv2.warpPerspective when I decided to code it from scratch to better understand its pipeline. Though I followed (hopefully) every theoretical step, it seems I am still missing something and I am struggling a lot to understand what. Could you please help me? SR...
Your issue amounts to a typo. You mixed up the naming of your coordinates. The homography assumes (x,y,1) order, which would correspond to (j,i,1). Just use (x, y, 1) in the calculation, and (xw, yw, w) in the result of that (then x,y = xw/w, yw/w). the w factor mirrors the math, when formulated properly. Avoid indexin...
6
4
73,843,943
2022-9-25
https://stackoverflow.com/questions/73843943/regex-for-alternating-numbers
I am trying to write a regex pattern for phone numbers consisting of 9 fixed digits. I want to identify numbers that have two numbers alternating for four times such as 5XYXYXYXY I used the below sample number = 561616161 I tried the below pattern but it is not accurate ^5(\d)(?=\d\1).+ can someone point out what i a...
I would use: ^(?=\d{9}$)\d*(\d)(\d)(?:\1\2){3}\d*$ Demo Here is an explanation of the pattern: ^ from the start of the number (?=\d{9}$) assert exactly 9 digits \d* match optional leading digits (\d) capture a digit in \1 (\d) capture another digit in \2 (?:\1\2){3} match the XY combination 3 more times \d* more opti...
3
5
73,843,521
2022-9-25
https://stackoverflow.com/questions/73843521/awaiting-multiple-async-functions-in-sequence
I have been learning and exploring Python asyncio for a while. Before starting this journey I have read loads of articles to understand the subtle differences between multithreading, multiprocessing, and asyncio. But, as far as I know, I missed something on about a fundamental issue. I'll try to explain what I mean by ...
Do I need to use asyncio.gather(*tasks) for these two database queries? If necessary, why? If not, why? Do you need to? Nope, what you have done works. The request will take 6 seconds but will not be blocking so if you had another request coming in, FastAPI can process the two requests at the same time. I.e. two requ...
4
3
73,842,710
2022-9-25
https://stackoverflow.com/questions/73842710/count-the-group-occurrences
I have dataframe id webpage 1 google 2 bing 3 google 4 google 5 yahoo 6 yahoo 7 google 8 google Would like to count the groups like id webpage count 1 google 1 2 bing 2 3 google 3 4 google 3 5 yahoo 4 6 yahoo 4 7 google 5 8 google 5 I have tried using the cumcount or ngroup when using groupby it is grouping all occ...
I believe you need to cumsum() over the state transitions. Every time webpage differs from the previous row you increase your count. df["count"] = (df.webpage != df.webpage.shift()).cumsum()
3
4
73,842,214
2022-9-25
https://stackoverflow.com/questions/73842214/how-to-convert-comma-separated-string-to-list-that-contains-comma-in-items-in-py
I have a string for items separated by comma. Each item is surrounded by quotes ("), but the items can also contain commas (,). So using split(',') creates problems. How can I split this text properly in Python? An example of such string "coffee", "water, hot" What I want to achieve ["coffee", "water, hot"]
import ast s = '"coffee", "water, hot"' result = ast.literal_eval(f'[{s}]') print(result)
4
2
73,837,417
2022-9-24
https://stackoverflow.com/questions/73837417/freeze-panes-first-two-rows-and-column-with-openpyxl
Trying to freeze the first two rows and first column with openpyxl, however, whenever doing such Excel says that the file is corrupted and there is no freeze. Current code: workbook = openpyxl.load_workbook(path) worksheet = workbook[first_sheet] freeze_panes = Pane(xSplit=2000, ySplit=3000, state="frozen", activePane=...
To freeze the first two rows and first column, use the sample code below... ws.freeze_panes works. Note that, like you would do in excel, select the cell above and left of which you want to freeze. So, in your case, the cell should be B3. Hope this is what you are looking for. import openpyxl wb=openpyxl.load_workbook(...
3
4
73,836,651
2022-9-24
https://stackoverflow.com/questions/73836651/python-drop-columns-in-string-range
I want to drop all columns whose name starts by 'var' and whose content is 'None'. Sample of my dataframe: id var1 var2 newvar1 var3 var4 newvar2 1 x y dt None f None Dataframe that I want: id var1 var2 newvar1 var4 newvar2 1 x y dt f None I want to do this for several files and I do not know how many 'var' I have in...
Your error occurs because you have no column with that name. You can use df.columns to get a list of available columns, check if the name .startswith("var") and use df[col].isnull().all() to check if all values are None. import pandas as pd df = pd.DataFrame(columns=["id", "var1", "var2", "newvar1", "var3", "var4", "ne...
3
3
73,805,879
2022-9-21
https://stackoverflow.com/questions/73805879/poetry-installation-failing-on-mac-os-says-should-use-symlinks
I am trying to install poetry using the following command curl -sSL https://install.python-poetry.org | python3 - but it is failing with the following exception: Exception: This build of python cannot create venvs without using symlinks Below is the text detailing the error Retrieving Poetry metadata # Welcome to Poet...
Not the best solution, but you can install it using Homebrew, if you have it. That's what I did. brew install poetry
35
42
73,822,427
2022-9-23
https://stackoverflow.com/questions/73822427/while-debugging-python-in-pdb-how-to-print-output-to-file
Sometimes as I'm using pdb, I would like to save the output to a file, pdbSaves.txt. For example I would want to do something like pp locals() >> pdbSaves.txt, which actually gives *** NameError: name 'pdbSaves' is not defined. What is the correct way to do this?
In Python 3 the ">>" symbol is no longer usable with the regular "print" for redirecting the output. I had not before used it from inside the PDB, but, certainly, the support for it was removed at the same time. What you have to do is to use the regular way of output to file with the new print function - or, if you wan...
3
5
73,830,546
2022-9-23
https://stackoverflow.com/questions/73830546/have-to-make-a-customized-dataframe-from-a-dict-with-multiple-values
Please find below my input/output : INPUT : dico = {'abc': 'val1=343, val2=935', 'def': 'val1=95, val2=935', 'ghi': 'val1=123, val2=508'} OUTPUT (desired) : I tried with pd.DataFrame.from_dict(dico, index=dico.keys) but unfortunately I got an error. TypeError: DataFrame.from_dict() got an unexpected keyword argument...
Let's use a regex pattern to find the matching pairs corresponding to each value in the input dictionary then convert the pairs to dict and create a new dataframe import re pd.DataFrame([dict(re.findall(r'(\S+)=(\d+)', v)) for k, v in dico.items()], dico) Alternative pandas only approach with extractall (might be slow...
4
5
73,828,396
2022-9-23
https://stackoverflow.com/questions/73828396/list-find-the-first-index-and-count-the-occurrence-of-a-specific-list-in-list-o
we have a variable named location. location=[["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']] i want to find the first index and count occurrence of list["alpha",'Live'] in location. i tried the following: index= [location.index(...
does this solve you problem? location=[["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']] index= location.index(["alpha",'Live']) count = location.count(["alpha",'Live']) print('index',index) print('count', count) if ['alpha','live...
3
5
73,817,788
2022-9-22
https://stackoverflow.com/questions/73817788/neural-network-keeps-misclassifying-input-image-despite-performing-well-on-the-o
Link to the dataset in question Before I begin, few things that might be relevant: The input file format is JPEG. I convert them to numpy arrays using matplotlib's imread The RGB images are then reshaped and converted to grayscale images using tensorflow's image.resize method and image.rgb_to_grayscale method respecti...
I have downloaded and tested your model. The accuracy was as stated by you, when run against the Kaggle dataset. You were also on the right track with inverting the values of the input for your own image, the one that wasn't working. But you should have taken a look at the training inputs: the values are in the range o...
3
7
73,828,684
2022-9-23
https://stackoverflow.com/questions/73828684/i-want-to-check-if-any-key-is-pressed-is-this-possible
How do I check if ANY key is pressed? this is how I know to detect one key: import keyboard # using module keyboard while True: # making a loop if keyboard.is_pressed('a'): # if key 'q' is pressed print('You Pressed A Key!') break # finishing the loop How do I check if any key (not just letters) is pressed? For exampl...
while True: # Wait for the next event. event = keyboard.read_event() if event.event_type == keyboard.KEY_DOWN: print(event.name) # to check key name Press any key and get the key name.
3
4
73,827,249
2022-9-23
https://stackoverflow.com/questions/73827249/merge-lists-in-a-dataframe-column-if-they-share-a-common-value
What I need: I have a dataframe where the elements of a column are lists. There are no duplications of elements in a list. For example, a dataframe like the following: import pandas as pd >>d = {'col1': [[1, 2, 4, 8], [15, 16, 17], [18, 3], [2, 19], [10, 4]]} >>df = pd.DataFrame(data=d) col1 0 [1, 2, 4, 8] 1 [15, 16, 1...
This is not straightforward. Merging lists has many pitfalls. One solid approach is to use a specialized library, for example networkx to use a graph approach. You can generate successive edges and find the connected components. Here is your graph: You can thus: generate successive edges with add_edges_from find the ...
4
3
73,826,941
2022-9-23
https://stackoverflow.com/questions/73826941/filtering-pandas-dataframe-on-time-not-date
I have the dataframe below and want to filter by time. The time column comes up as an object when I use dtypes. To get the time to use as the filter criteria I use split: start_time = "25 September 2022, 13:00:00" split_time = start_time.split(", ")[1] I have tried converting split_time and the df column to datime but...
Comapre times generated by Series.dt.time with Timestamp.time: start_time = "25 September 2022, 13:00:00" dt = pd.to_datetime(start_time, format="%d %B %Y, %H:%M:%S") events_df['start_date'] = pd.to_datetime(events_df['start_date']) #if necessary events_df['time'] = pd.to_datetime(events_df['time']).dt.time filtered_df...
3
5
73,826,252
2022-9-23
https://stackoverflow.com/questions/73826252/how-to-plot-a-time-series-with-this-dataframe
I want to plot this dataframe like a time series, a line for every country that every year increases or decreases according to 'count'. How can i do this? country count Year 2005 Australia 2 2005 Austria 1 2005 Belgium 0 2005 Canada 4 2005 China 0 2006 Australia 3 2006 Austria 0 2006 Belgium 1 2006 Canada 5 2006 China...
You can use seaborn.lineplot: import seaborn as sns df.Year = pd.to_datetime(df.Year) sns.set(rc={'figure.figsize':(12, 8)}) # changed the figure size to avoid overlapping sns.lineplot(data=df, x=df['Year'].dt.strftime('%Y'), # show only years with strftime y=df['count'], hue='country') which gives
4
3
73,797,873
2022-9-21
https://stackoverflow.com/questions/73797873/importlib-metadata-packagenotfounderror-no-package-metadata-was-found-for-pypro
I wrote a code using the pyproj library and converted this code to an exe file for use on another computer. I added the pyproj to the requirements.txt file. And I installed the library with the requirements.txt file on the other computer I will use. When I run the exe file, I get the following error: importlib.metadata...
Here is my solution for those who have problems like above while running the exe file: pyinstaller --onefile --copy-metadata pyproj "example.py" For now this seems to have fixed the problem.
8
6
73,821,248
2022-9-22
https://stackoverflow.com/questions/73821248/sqlalchemy-get-bind-parameters-from-sql-dynamically
I'm trying to use pd and sqlalchemy to run all the sql files in a directory. Currently I can load the text of a sql file into a sqlalchemy.sql.text object, and send that directly to pd.read_sql. What should I use to locate the bind parameters within my sql script so that I can prompt the user for them? import sys, os, ...
You can obtain the names of the bind parameters from the compiled query: >>> q = text('select id, name from users where name = :p1 and age > :p2') >>> q.compile().params {'p1': None, 'p2': None} In the resulting dictionary, the keys correspond to the bind parameter names. The values are None until values are bound.
3
4
73,823,564
2022-9-23
https://stackoverflow.com/questions/73823564/how-to-create-this-dataframe-using-pandas
Please see this - I want to create a table similar to this using pandas in python? Can anyone guide? Unable to understand how to add "Total Marks" text corresponding to two columns ("Student id" & "Course id"). Thanks
As far as I'm aware, pandas doesn't really support merged cells/cells spanning multiple rows in the same way as Excel/HTML do. A pandas-esque way to include the total row for a single column would be something like the following: import pandas as pd columns = ['Student ID', 'Course ID', 'Marks'] data = [(103, 201, 67),...
4
5
73,821,319
2022-9-22
https://stackoverflow.com/questions/73821319/number-of-occurrences-of-digit-in-numbers-from-0-to-n
Given a number n, count number of occurrences of digits 0, 2 and 4 including n. Example1: n = 10 output: 4 Example2: n = 22 output: 11 My Code: n = 22 def count_digit(n): count = 0 for i in range(n+1): if '2' in str(i): count += 1 if '0' in str(i): count += 1 if '4' in str(i): count += 1 return count count_digit(n)...
Another brute force, seems faster: def count_digit(n): s = str(list(range(n+1))) return sum(map(s.count, '024')) Benchmark with n = 10**5: result time solution 115474 244 ms original 138895 51 ms Kelly 138895 225 ms islam_abdelmoumen 138895 356 ms CodingDaveS Code (Try it online!): from timeit import default_timer as...
3
0
73,821,359
2022-9-22
https://stackoverflow.com/questions/73821359/how-to-edit-lines-of-a-text-file-based-on-regex-conditions
import re re_for_identificate_1 = r"" with open("data_path/filename_1.txt","r+") as file: for line in file: #replace with a substring adding a space in the middle line = re.sub(re_for_identificate_1, " milesimo", line) #replace in txt with the fixed line Example filename_1.txt : unmilesimo primero 1001° dosmilesimos q...
You can use file.seek(0) to go beginning of the file, then write data and truncate the file. Like this: import re re_for_identificate_1 = "(?<!^)milesimo" tmp = "" with open("data.txt", "r+") as file: for line in file: line = re.sub(re_for_identificate_1, " milesimo", line) tmp += line file.seek(0) file.write(tmp) file...
4
4
73,820,799
2022-9-22
https://stackoverflow.com/questions/73820799/checking-match-on-two-ordered-lists
I will give the specific case and the generic case so we can help more people: I have a list of ordered lists and another list with the same length as each ordered list. Each list in the list of lists is students' answers from a large-scale evaluation, and the second is the correct answers from the test. I need to chec...
The others have done a fine job detailing how this can be done with list comprehensions. The following code is a beginner-friendly way of getting the same answer. final = [] # Begin looping through each list within list1 for test in list1: # Create a list to store each students scores within student = [] for student_an...
3
2
73,814,238
2022-9-22
https://stackoverflow.com/questions/73814238/recreate-pandas-dataframe-from-question-in-stackoverflow
This is a question from someone who tries to answer questions about pandas dataframes. Consider a question with a given dataset which is just the visualization (not the actual code), for example: numbers letters dates all 0 1 a 20-10-2020 NaN 1 2 b 21-10-2020 b 2 3 c 20-11-2020 4 3 4 d 20-10-2021 20-10-2020 4 5 e 10-1...
read_clipboard You can use pd.read_clipboard() optionally with a separator (e.g. pd.read_clipboard('\s\s+') if you have datetime strings or spaces in column names and columns are separated by at least two spaces): select text on the question and copy to clipboard (ctrl+c/command-c) move to python shell or notebook and...
4
7
73,813,602
2022-9-22
https://stackoverflow.com/questions/73813602/futurewarning-in-a-future-version-of-pandas-all-arguments-of-dataframe-any-and
Here is the Python statement creating the problem: nan_rows = df[df.isnull().any(1)] And it gives the following warning: FutureWarning: In a future version of pandas all arguments of DataFrame.any and Series.any will be keyword-only. It is a warning from production environment. I am sorry that I am not able to share ...
Starting from pandas 1.5, you get a FutureWarning. You must specify axis=1: nan_rows = df[df.isnull().any(axis=1)] In a future version only keywords arguments will be accepted, omitting the keyword will raise an error.
3
5
73,800,003
2022-9-21
https://stackoverflow.com/questions/73800003/how-to-specify-variable-type-of-a-pandas-series-string-or-typevar
I want to use type hinting for something like: def fo() -> pd.Series[np.float64]: return pd.Series(np.float64[0]) This won't work. From this answer: How to specify the type of pandas series elements in type hints? I understand I can use either: def fo() -> "pd.Series[np.float64]": return pd.Series(np.float64[0]) Or: ...
Both "solutions" you referenced are wrong I'll start with the second one: from typing import TypeVar import numpy as np, pandas as pd SeriesFloat64 = TypeVar('pd.Series[np.float64]') def fo() -> SeriesFloat64: return pd.Series(np.float64(0)) Is this type variable technically a valid annotation? Yes. Does it specify th...
4
1
73,809,795
2022-9-22
https://stackoverflow.com/questions/73809795/how-can-i-convert-a-string-true-to-boolean-python
So I have this data that list of True and False for example tf = ['True', 'False', 'False'] how can I convert tf to a bool. Once I print(tf[0]) it prints True
Use the ast module: import ast tf = ['True', 'False', 'False'] print(type(ast.literal_eval(tf[0]))) print(ast.literal_eval(tf[0])) Result: <class 'bool'> True Ast Documentation Literal_eval
3
4
73,797,666
2022-9-21
https://stackoverflow.com/questions/73797666/is-there-a-better-way-to-capture-all-the-regex-patterns-in-matching-with-nested
I am trying out a simple text-matching activity where I scraped titles of blog posts and try to match it with my pre-defined categories once I find specific keywords. So for example, the title of the blog post is "Capture Perfect Night Shots with the Oppo Reno8 Series" Once I ensure that "Oppo" is included in my cate...
You can create a reverse mapping that maps keywords to categories instead, so that you can efficiently return the corresponding category when a match is found: mapping = {keyword: category for category, keywords in categories.items() for keyword in keywords} def put_category(mapping, text): match = re.search(rf'\b(?:{"...
3
3