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 |
|---|---|---|---|---|---|---|
78,762,002 | 2024-7-18 | https://stackoverflow.com/questions/78762002/contradictory-error-when-using-polars-read-csv-with-multiple-files-for-csv-gz | I'm trying to read multiple csv.gz files into a dataframe but it's not working as I expect. When I use this globbing pattern: pl.read_csv('folder_1\*.csv.gz') It returns this error: ComputeError: cannot scan compressed csv; use read_csv for compressed data This error occurred with the following context stack: >[1] '... | When I pass a glob string blah/blah/blah/*.csv.gz to pl.read_csv, it passes this to pl.scan_csv because it is a glob string. See polars.io.csv.functions line 514 et seq in version 1.1.0. There are two separate questions here: How do you read multiple CSVs? You can read multiple CSVs by passing a glob string to pl.scan... | 2 | 2 |
78,763,470 | 2024-7-18 | https://stackoverflow.com/questions/78763470/find-if-any-number-appears-more-than-n-4-times-in-a-sorted-array | I was asked the following in an interview: Given a sorted array with n numbers (where n is a multiple of 4), return whether any number appears more than n/4 times. My initial thought was to iterate over the array and keep a counter: limit = len(nums) // 4 counter = 1 for i in range(1, len(nums)): if nums[i] == nums[i... | A number that appears more than n/4 times in nums must be one of the elements of nums[::len(nums)//4]. For each candidate number, we perform a binary search for the first position where it appears, and check whether the same number appears len(nums)//4 spots later: import bisect def check(nums): n = len(nums) assert n ... | 4 | 3 |
78,763,118 | 2024-7-18 | https://stackoverflow.com/questions/78763118/create-discrete-colorbar-from-colormap-in-python | I want to use a given colormap (let's say viridis) and create plots and colorbars with discrete colors from that colormap. I used to use mpl.cm.get_cmap("viridis", 7) for 7 different colors, but this function is deprecated and will be removed. The recommendation is to use matplotlib.colormaps[name] or matplotlib.colorm... | A simple option to replace matplotlib.cm.get_cmap (deprecated in 3.7.0) is to use matplotlib.pyplot.get_cmap (that was preserved in the API for backward compatibility). Another one woud be to make a resampled colormap (used under the hood) : resampled(lutsize) [source] Return a new colormap with lutsize entries. Note... | 1 | 6 |
78,762,850 | 2024-7-18 | https://stackoverflow.com/questions/78762850/why-the-addion-of-float32-array-and-float64-scalar-is-float32-array-in-numpy | If one add float32 and float64 scalars, the result is float64: float32 is promoted to float64. However, I find that, adding a float32 array and a float64 scalar, the result is a float32 array, rather than one might expect to be a float64 array. I have written some code repreduce the problem. My question is why the dtyp... | why the dtype of np.add(np.array([a]), b) is float32? Because NumPy's promotion rules involving scalars pre-NEP 50 were confusing*. Using the NEP 50 rules in your version of NumPy, the behavior is as you expect: import numpy as np import sys # Use this to turn on the NEP 50 promotion rules np._set_promotion_state("we... | 3 | 3 |
78,760,761 | 2024-7-17 | https://stackoverflow.com/questions/78760761/django-database-routers-allow-migrate-model-throws-the-following-typeerror | the "allow_migrate_model" function within my database routers keeps throw the following error when I try to run python manage.py makemigrations: ... File "C:\Users\...\lib\site-packages\django\db\utils.py", line 262, in allow_migrate allow = method(db, app_label, **hints) TypeError: allow_migrate() missing 1 required ... | Ah also for some reason if a rewrite it into a staticmethod. You likely registered the router as: # settings.py # import of DefaultRouter and LibraryRouter # … DATABASE_ROUTERS = [DefaultRouter, LibraryRouter] Then it is not an instance: it targets it as a class, that is the problem: the method(…) is called as BaseRo... | 2 | 2 |
78,760,293 | 2024-7-17 | https://stackoverflow.com/questions/78760293/find-value-in-column-which-contains-list-and-take-another-value-from-next-colum | I have two tables df1 = pd.DataFrame([{'a': 1}, {'a': 2}, {'a': 8}]) df1['b'] = "" df2 = pd.DataFrame([{'e': [1,2,3], 'f': 1},{'e': [4,5,6], 'f': 2},{'e': [7,8,9], 'f': 3}]) e f I would like to insert a value into df1['b'] from df2['f'] based on the condition that value in df['a'] is somewhere in df2['e'] Mostly I wou... | I would explode, create a mapping Series, and map: df1['b'] = df1['a'].map(df2.explode('e').set_index('e')['f']) Output: a b 0 1 1 1 2 1 2 8 3 Intermediate mapping Series: df2.explode('e').set_index('e')['f'] e 1 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 3 Name: f, dtype: int64 | 2 | 1 |
78,759,687 | 2024-7-17 | https://stackoverflow.com/questions/78759687/numpy-sum-n-successive-array-elements-where-n-comes-from-a-list | Here is code I am trying to optimize: import numpy as np rng = np.random.default_rng() num = np.fromiter((rng.choice([0, 1], size=n, p=[1-qEff, qEff]).sum() for n in num), dtype='int') What it does is it takes array num, where each element represents a bucket with given number of items. For each item it rolls a dice (... | To add buckets you can get the indices for reduceat from a call to cumsum, but you will have to add a 0 in front and get rid of the last entry, which is equal to the total number of items and is added automatically by reduceat. Something like this should work: indices = np.concatenate(([0], np.cumsum(num)[:-1])) num = ... | 2 | 2 |
78,759,751 | 2024-7-17 | https://stackoverflow.com/questions/78759751/dropping-rows-of-a-dataframe-where-selected-columns-has-na-values | I have below code df = pd.DataFrame(dict( age=[5, 6, np.nan], born=[pd.NaT, pd.Timestamp('1939-05-27'), pd.Timestamp('1940-04-25')], name=['Alfred', 'Batman', np.nan], toy=[np.nan, 'Batmobile', 'Joker'])) Now I want to drop those rows where columns name OR toy have NaN/empty string values. I tried with below code df[~... | what is wrong df[~df[['name', 'toy']].isna()] returns a DataFrame (2D), thus you will apply a mask on the whole DataFrame, keeping values that are truthy (the shape remains unchanged). You're essentially doing: df.where(~df[['name', 'toy']].isna()) Which will mask the non target columns with NaN and the NaN values fro... | 2 | 1 |
78,759,219 | 2024-7-17 | https://stackoverflow.com/questions/78759219/how-to-test-django-models-against-a-db-without-manage-py-in-a-standalone-package | Context: I am developing a standalone Django package that is intended to be added to existing Django projects. This package includes Django models with methods that interact directly with a database. I want to write tests for these methods using pytest and pytest-django. I need to run these tests in a CI/CD environmen... | You don't need manage.py to run migrate. The same commands are available via the django-admin command that Django installs, but you'll need to set the DJANGO_SETTINGS_MODULE variable that manage.py would ordinarily set. IOW, if you'd generally run python manage.py and your project settings are myproject.settings, you c... | 2 | 0 |
78,757,696 | 2024-7-17 | https://stackoverflow.com/questions/78757696/python-check-if-the-last-value-in-a-sequence-is-relatively-higher-than-the-res | For a list of percentage data, I need to check if the last value (90.2) is somehow higher and somewhat "abnormal" than the rest of the data. Clearly it is in this sequence. delivery_pct = [59.45, 55.2, 54.16, 66.57, 68.62, 64.19, 60.57, 44.12, 71.52, 90.2] But for the below sequnece the last value is not so: delivery_p... | Once you've determined a threshold (deviation from mean) you could do this: import statistics t = 2 # this is the crucial value pct = [59.45, 55.2, 54.16, 66.57, 68.62, 64.19, 60.57, 44.12, 71.52, 90.2] mean = statistics.mean(pct) tsd = statistics.pstdev(pct) * t lo = mean - tsd hi = mean + tsd print(*[x for x in pct i... | 2 | 3 |
78,729,842 | 2024-7-10 | https://stackoverflow.com/questions/78729842/symbol-not-found-in-flat-namespace-bcp-batch | I'm using pyenv to manage my python versions. When i use python 3.12.4 or python3.9^, i get this error: File "src/pymssql/_pymssql.pyx", line 1, in init pymssql._pymssql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pymssql/_mssql.cpython-312-darwin.so, 0x0002): sy... | also another way that works: pip install --no-binary :all: pymssql --no-cache --force | 3 | 1 |
78,735,592 | 2024-7-11 | https://stackoverflow.com/questions/78735592/how-to-compute-a-column-in-polars-dataframe-using-np-linspace | Consider the following pl.DataFrame: df = pl.DataFrame( data={ "np_linspace_start": [0, 0, 0], "np_linspace_stop": [8, 6, 7], "np_linspace_num": [5, 4, 4] } ) shape: (3, 3) ┌───────────────────┬──────────────────┬─────────────────┐ │ np_linspace_start ┆ np_linspace_stop ┆ np_linspace_num │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i... | As mentioned in the comments, adding an np.linspace-style function to polars is an open feature request. Until this is implemented a simple implementation using polars' native expression API could look as follows. Update. Modern polars supports broadcasting of operations between scalar and list columns. This can be us... | 4 | 6 |
78,756,903 | 2024-7-16 | https://stackoverflow.com/questions/78756903/ps-camera-taking-too-much-light-on-opencv | I installed a third-party driver and firmware to use my PS 4 Camera on PC and I need it to do a object detection project. Everything works fine on camera on Windows (the screen resolution looks buggy but this is simply how Windows read Sony data format). Here is how it looks (I have a red light in the room): -- When I... | I solved the problem! With ffmpeg/ffplay I figured out that this cam can only support certain frame/resolution combinations: [dshow @ 000002e52f473900] pixel_format=yuyv422 min s=3448x808 fps=8 max s=3448x808 fps=60.0002 (tv, bt470bg/bt709/unknown, topleft) [dshow @ 000002e52f473900] pixel_format=yuyv422 min s=1748x408... | 2 | 1 |
78,734,751 | 2024-7-11 | https://stackoverflow.com/questions/78734751/how-do-i-persist-faiss-indexes | In the langchain wiki of FAISS, https://python.langchain.com/v0.2/docs/integrations/vectorstores/faiss/, it only talks about saving indexes to files. db.save_local("faiss_index") new_db = FAISS.load_local("faiss_index", embeddings) docs = new_db.similarity_search(query) How can I save the indexes to databases, such th... | In fact, FAISS is considered as an in-memory database itself in order to vector search based on similarity that you can serialize and deserialize the indexes using functions like write_index and read_index within the FAISS interface directly or using save_local and load_local within the LangChain integration which typi... | 2 | 2 |
78,754,451 | 2024-7-16 | https://stackoverflow.com/questions/78754451/defining-previous-timestep-dependent-ramping-constraints-in-python-gekko | I am building an MPC optimization (IMODE = 6) in Python GEKKO with multiple state (SV) and manipulated (MV) variables. Inside my problem, I would like to define ramping constraints of the following kind: |x(tk) - x(tk-1)| <= Cx for the SV, where Cx is a constant, tk is the current time step and tk-1 is the previous 0.9... | For the constraint |x(tk) - x(tk-1)| <= Cx for a state variable, create a new variable dx that is the defined as the derivative of the variable x and set a constraint on the ramp rate. # State Variable x = m.SV(value=0,ub=2) dx = m.SV(value=0,lb=-0.5,ub=0.5) # Process model m.Equation(5*x.dt() == -x + 3*u) m.Equation(d... | 2 | 0 |
78,752,644 | 2024-7-16 | https://stackoverflow.com/questions/78752644/pytest-fixtures-not-found-when-running-tests-from-pycharm-ide | I am having trouble with pytest fixtures in my project. I have a root conftest.py file with some general-use fixtures and isolated conftest.py files for specific tests. The folder structure is as follows: product-testing/ ├── conftest.py # Root conftest.py ├── tests/ │ └── grpc_tests/ │ └── collections/ │ └── test_coll... | After hours of debugging and calls I found the solution, IDK maybe one day it will help someone. First of all, putting contest files in a separate directory from pytest is not a good idea, pytest can't see the files, so the files should be put in the same directory or at least on the path to the test file. So I have mo... | 5 | 2 |
78,756,165 | 2024-7-16 | https://stackoverflow.com/questions/78756165/how-to-contract-nodes-and-apply-functions-to-node-attributes | I have a simple graph with the attributes height and area import networkx as nx nodes_list = [("A", {"height":10, "area":100}), ("B", {"height":12, "area":200}), ("C", {"height":8, "area":150}), ("D", {"height":9, "area":120})] G = nx.Graph() G.add_nodes_from(nodes_list) edges_list = [("A","B"), ("B","C"), ("C","D")] G... | I don't think there is a builtin way, especially since you have custom aggregation functions. Here is an alternative way, using a custom function: def contract_merge(G, n1, n2): H = nx.contracted_nodes(G, n1, n2) d_n1 = H.nodes[n1] d_n2 = d_n1.pop('contraction')[n2] d_n1['height'] = (d_n1['height']+d_n2['height'])/2 d_... | 2 | 1 |
78,755,449 | 2024-7-16 | https://stackoverflow.com/questions/78755449/type-of-union-or-union-of-types | In Python, is Type[Union[A, B, C]] the same as Union[Type[A], Type[B], Type[C]]? I think they are equivalent, and the interpreter seems to agree. ChatGPT (which, from my past experience, tends to be wrong with this type of questions) disagrees so I was wondering which one is more correct. To be clear: I want a union of... | They are the same. You can use reveal_type and check. class A: ... class B: ... class C: ... def something(a: type[A | B | C]) -> None: reveal_type(a) def something_else(b: type[A] | type[B]| type[C]) -> None: reveal_type(b) mypy main.py main.py:6: note: Revealed type is "Union[type[main.A], type[main.B], type[main.C]... | 3 | 6 |
78,752,520 | 2024-7-16 | https://stackoverflow.com/questions/78752520/how-can-i-get-the-subarray-indicies-of-a-binary-array-using-numpy | I have an array that looks like this r = np.array([1, 0, 0, 1, 1, 1, 0, 1, 1, 1]) and I want an output of [(0, 0), (3, 5), (7, 9)] right now I am able to accomplish this with the following function def get_indicies(array): indicies = [] xstart = None for x, col in enumerate(array): if col == 0 and xstart is not None:... | The solution I came up with is to separately find the indices where the first occurrence of 1 is and the indices where the last occurrence of 1 is. def get_indices2(arr): value_diff = np.diff(arr, prepend=0, append=0) start_idx = np.nonzero(value_diff == 1)[0] end_idx = np.nonzero(value_diff == -1)[0] - 1 # -1 to inclu... | 3 | 5 |
78,750,943 | 2024-7-15 | https://stackoverflow.com/questions/78750943/split-a-pandas-dataframe-column-into-multiple-based-on-text-values | I have a pandas dataframe with a column. id text_col 1 Was it Accurate?: Yes\n\nReasoning: This is a sample : text 2 Was it Accurate?: Yes\n\nReasoning: This is a :sample 2 text 3 Was it Accurate?: No\n\nReasoning: This is a sample: 1. text I have to break the text_col into two columms "Was it accurate?" and "Reasonin... | The issue is not due to colons, but to newlines in your sample text. Those are not matched by . by default. You should add the re.DOTALL flag. Example: import re import pandas as pd df = pd.DataFrame({'id': [1, 2, 3], 'text_col': ['Was it Accurate?: Yes\n\nReasoning: This is a sample: text', 'Was it Accurate?: Yes\n\nR... | 2 | 0 |
78,753,705 | 2024-7-16 | https://stackoverflow.com/questions/78753705/resolving-runtime-nzec-error-in-python-code | I was solving a problem on HackerEarth which is as follows: You are provided an array A of size N that contains non-negative integers. Your task is to determine whether the number that is formed by selecting the last digit of all the N numbers is divisible by 10. Print "Yes" if possible and "No" if not. Here's what I... | https://help.hackerearth.com/hc/en-us/articles/360002673433-types-of-errors Hackerearth says For interpreted languages like Python, NZEC will usually mean Usually means that your program has either crashed or raised an uncaught exception Many runtime errors Usage of an external library that is not used by the judg... | 2 | 0 |
78,753,820 | 2024-7-16 | https://stackoverflow.com/questions/78753820/using-polars-with-python-and-being-thrown-the-following-exception-attributeerro | I am trying to apply a function to a Dataframe column (series) that retrieves the day of the week based on the timestamps in the column. However, I am being thrown the following exception, even though the Polars docs include documentation for polars.Expr.apply. AttributeError: 'Expr' object has no attribute 'apply'. M... | apply was renamed to .map_elements() some time ago. Previous versions printed a deprecation warning, but it was eventually removed after a grace period. You're likely looking at the docs for an older version of Polars, but there is a "version switcher" on the docs site: As for the actual task, you can also do it nat... | 7 | 6 |
78,743,465 | 2024-7-13 | https://stackoverflow.com/questions/78743465/python-3-10-4-scikit-learn-import-hangs-when-executing-via-cpp | Python 3.10.4 is embedded into cpp application. I'm trying to import sklearn library which is installed at custom location using pip --target. sklearn custom path (--target path) is appended to sys.path. Below is a function from the script which just prints the version information. Execution using Command Line works we... | https://github.com/scipy/scipy/issues/21189 Looks like Scipy and Numpy do not support Embedded python | 5 | 2 |
78,753,451 | 2024-7-16 | https://stackoverflow.com/questions/78753451/should-i-and-how-should-i-align-the-types-hints-my-abstract-class-and-concrete | I'm having an abstract class in Python like this class Sinker(ABC): @abstractmethod def batch_write(self, data) -> None: pass The concrete class is expected to write data to some cloud databases. My intention of writing abstract class this way was to make sure the concrete classes always implement the batch_write() me... | You can make Sinker a generic class so the type of items in the list passed to batch_write can be parameterized: from abc import ABC, abstractmethod class Sinker[T](ABC): @abstractmethod def batch_write(self, data: list[T]) -> None: ... class StrSinker(Sinker[str]): def batch_write(self, data: list[str]) -> None: pass ... | 2 | 2 |
78,749,739 | 2024-7-15 | https://stackoverflow.com/questions/78749739/why-does-iterating-break-up-my-text-file-lines-while-a-generator-doesnt | For each line of a text file I want to do heavy calculations. The amount of lines can be millions so I'm using multiprocessing: num_workers = 1 with open(my_file, 'r') as f: with multiprocessing.pool.ThreadPool(num_workers) as pool: for data in pool.imap(my_func, f, 100): print(data) I'm testing interactively hence Th... | imap chunking is an implementation detail, your function will be called with a single element of the iterable regardless of the chunk size. for line in file: result = my_func(line) Becomes for result in pool.imap(my_func, file, some_chunk_size): pass It is syntactically the same as builtins.map without the chunk size... | 3 | 2 |
78,751,680 | 2024-7-15 | https://stackoverflow.com/questions/78751680/nested-named-regex-groups-how-to-maintain-the-nested-structure-in-match-result | A small example: import re pattern = re.compile( r"(?P<hello>(?P<nested>hello)?(?P<other>cat)?)?(?P<world>world)?" ) result = pattern.match("hellocat world") print(result.groups()) print(result.groupdict() if result else "NO RESULT") produces: ('hellocat', 'hello', 'cat', None) {'hello': 'hellocat', 'nested': 'hello',... | Since you don't mind using implementation details of the re module (which are subject to undocumented future changes), what you want is then possible by overriding the hooks that are called when the parser enters and leaves a capture group. Reading the source code of the Python implementation of re's parser we can find... | 3 | 5 |
78,752,268 | 2024-7-15 | https://stackoverflow.com/questions/78752268/least-common-multiple-of-natural-numbers-up-to-a-limit-say-10000000 | I'm working on a small Python program for myself and I need an algorithm for fast multiplication of a huge array with prime powers (over 660 000 numbers, each is 7 digits). The result number is over 4 millions digits. Currently I'm using math.prod, which calculates it in ~10 minutes. But that's too slow, especially if ... | There are two keys to making this fast. First, using the fastest mult implementation you can get. For "sufficiently large" multiplicands, Python's Karatsuba mult is O(n^1.585). The decimal module's much fancier NTT mult is more like O(n log n). But fastest of all is to install the gmpy2 extension package, which wraps G... | 7 | 8 |
78,747,712 | 2024-7-15 | https://stackoverflow.com/questions/78747712/find-number-of-redundant-edges-in-components-of-a-graph | I'm trying to solve problem 1319 on Leetcode, which is as follows: There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirec... | When you do: adj_list = defaultdict(list) for connection in connections: adj_list[connection[0]].append(connection[1]) # adj_list[connection[1]].append(connection[0]) You will only create dictionary keys for one-directional edges. You need to add the edges in the reverse direction (that you have commented out) and the... | 4 | 1 |
78,752,121 | 2024-7-15 | https://stackoverflow.com/questions/78752121/how-does-numpy-polyfit-return-a-slope-and-y-intercept-when-its-documentation-say | I have seen examples where slope, yintercept = numpy.polyfit(x,y,1) is used to return slope and y-intercept, but the documentation does not mention "slope" or "intercept" anywhere. The documentation also states three different return options: p: ndarray, shape (deg + 1,) or (deg + 1, K) Polynomial coefficients, highes... | slope, yintercept = numpy.polyfit(x, y, 1) Both full and cov parameters are False, so it's the first option, "Polynomial coefficients, highest power first". deg is 1, so "p: ndarray, shape (deg + 1,)" is an array of shape (2,). With tuple assignment, slope is p[0], the xdeg-0 = x1 coefficient, yintercept is p[1], t... | 2 | 1 |
78,751,960 | 2024-7-15 | https://stackoverflow.com/questions/78751960/how-to-save-generator-object-to-png-jpg-or-other-image-files | I'm using timeseries-generator from GitHub to get synthetic line graphs. That works good. But now I want to save the plots into a file as separate png images. This is my code so far: i=range(0,4) #first number inclusive, second exclusive for element in i: outpath = "PATH" c=random.random() o=random.random() s=random.ra... | g.plot() simply calls the plot() method of the underlying Pandas dataframe. You should get the dataframe and export it on your own: fig = g.ts.plot(kind='line', figsize=(20, 16)).get_figure() fig.savefig(path.join(outpath,"graph_{0}.png".format(element))) | 2 | 1 |
78,750,662 | 2024-7-15 | https://stackoverflow.com/questions/78750662/np-where-on-a-numpy-mxn-matrix-but-return-m-rows-with-indices-where-condition-ex | I am trying to use np.where on a MxN numpy matrix, where I want to return the same number of M rows but the indices in each row where the element exists. Is this possible to do so? For example: a = [[1 ,2, 2] [2, 3, 5]] np.where(a == 2) I would like this to return: [[1, 2], [0]] | One option is to post-process the output of where, then split: a = np.array([[1, 2, 2], [2, 3, 5]]) i, j = np.where(a == 2) out = np.split(j, np.diff(i).nonzero()[0]+1) Alternatively, using a list comprehension: out = [np.where(x==2)[0] for x in a] Output: [array([1, 2]), array([0])] using this output to average ano... | 3 | 1 |
78,747,351 | 2024-7-14 | https://stackoverflow.com/questions/78747351/sympy-how-to-factor-expressions-inside-parentheses-only | I want to simplify the following expression using sympy: -8*F_p + 8*Omega*u + 6*alpha*u*(u**2 + v**2) - 5*beta*u*(u**4 + 2*u**2*v**2 + v**4) - 8*gamma*omega*v So it ends up like -8*F_p + 8*Omega*u + 6*alpha*u*r**2 - 5*beta*u*r**4 - 8*gamma*omega*v with r**2=u**2+v**2 It is not working though, but when I use factor(u*... | Sometimes the easiest thing to do is to re-arrange the expression you are trying to replace: >>> f.subs(v**2, r**2 - u**2).expand() -8*F_p + 8*Omega*u + 6*alpha*r**2*u - 5*beta*r**4*u - 8*gamma*omega*v For an older version of SymPy, that doesn't replace the v**2 in the way you want, you might have to fall back to usin... | 2 | 2 |
78,742,550 | 2024-7-12 | https://stackoverflow.com/questions/78742550/how-to-use-glob-pattern-to-read-many-csvs-into-one-polars-data-frame-with-pydriv | If I have 2 .csv files stored locally data/file_1.csv and data/file_2.csv which both have the same schema, it is easy to polars-read both of them in to 1 concatenated data frame like so: pl.read_csv('data/file_*.csv') But if I am storing these same 2 files within Google Drive (not a GCS bucket), and I am using GDriveF... | Although pydrive2 has an fsspec interface, it doesn't seem to declare a protocol or register itself with fsspec, so calls like fsspec.open("gdrive://...", ) are not automatically recognised. This is the intended usage, so I suggest an issue should be raised with them to make sure this gets implemented. You could call f... | 5 | 0 |
78,749,458 | 2024-7-15 | https://stackoverflow.com/questions/78749458/how-to-create-a-python-type-alias-for-a-parametrized-type | jaxtyping provides type annotations that use a str as parameter (as opposed to a type), e.g.: Float[Array, "dim1 dim2"] Let's say I would like to create a type alias which combines the Float and Array part. This means I would like to be able to write MyOwnType["dim1 dim2"] instead. To my understanding I cannot use Ty... | You need to override/define __class_getitem__, not __getitem__ (which applies to instances of _Singleton, not _Singleton itself). class _Singleton: def __class_getitem__(self, shape: str) -> Float: return Float[Array, shape] | 4 | 2 |
78,748,429 | 2024-7-15 | https://stackoverflow.com/questions/78748429/apply-permutation-array-on-multiple-axes-in-numpy | Let's say I have an array of permutations perm which could look like: perm = np.array([[0, 1, 2], [1, 2, 0], [0, 2, 1], [2, 1, 0]]) If I want to apply it to one axis, I can write something like: v = np.arange(9).reshape(3, 3) print(v[perm]) Output: array([[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[3, 4, 5], [6, 7, 8], [0, ... | How about: p1 = perm[:, :, np.newaxis] p2 = perm[:, np.newaxis, :] v[p1, p2] The zeroth axis of p1 and p2 is just the "batch" dimension of perm, which allows you to do many permutations in one operation. The other dimension of perm, which corresponds with the indices, is aligned along the first axis in p1 and the seco... | 6 | 4 |
78,747,409 | 2024-7-14 | https://stackoverflow.com/questions/78747409/suppress-stdout-message-from-c-c-library | I am attempting to suppress a message that is printed to stdout by a library implemented in C. My specific usecase is OpenCV, so I will use it for the MCVE below. The estimateChessboardSharpness function has a printout when the grid size is too small (which happens here). I made a PR to fix it, but in the meantime, I'd... | Assuming a UNIX-like platform, (you'll get an OSError if not) You can save the underlying fd with backup = os.dup(sys.stdout.fileno()) point it to a different file (eg. different) with os.dup2(different.fileno(), sys.stdout.fileno()) and resume normal service with os.dup2(backup, sys.stdout.fileno()) Do note that th... | 2 | 2 |
78,745,907 | 2024-7-14 | https://stackoverflow.com/questions/78745907/is-there-a-way-to-expose-a-plot-generated-using-a-pandas-dataframe-as-a-jupyter | Current Workflow Right now, me, as an ML engineer, am using a jupyter notebook to plot some pandas dataframes. Basically, inside the jupyter notebook, I am setting some hard-coded configurations like k_1:float=2.3 date_to_analyse:str='2024-06-17' # 17th June region_to_analyse:str='montana' ... Based on the hardcoded p... | If you can expose the notebook to users (load credentials via env vars etc.) you can use IPython widgets. Google collab has forms and allows you to hide the code, if you think filling out a form an pressing the play button left of the field is managable for your userbase that is an option as well. While not totally ser... | 2 | 1 |
78,744,848 | 2024-7-13 | https://stackoverflow.com/questions/78744848/impact-on-performance-when-using-sql-like-padding-in-polars | Description: I have been using SQL-like padding in my Polars DataFrame queries for better readability and easier commenting of conditions. This approach involves using True (analogous to 1=1 in SQL) to pad the conditional logic. SQL Example In SQL, padding with 1=1 makes it easy to add or remove conditions: SELECT * FR... | Personally for SQL i switched to “and at the end of the line” cause i think it’s much more readable like that. It does make commenting out the last line trickier, but i just don’t like 1=1 dummy condition. Luckily, in modern dataframe library like polars you don’t need to do that anymore. Just pass multiple filter cond... | 4 | 3 |
78,744,860 | 2024-7-13 | https://stackoverflow.com/questions/78744860/using-pandas-concat-along-axis-1-returns-a-concatenation-along-axis-0 | I am trying to horizontally concatenate a pair of data frames with identical indices, but the result is always a vertical concatenation with NaN values inserted into every column. dct_l = {'1':'a', '2':'b', '3':'c', '4':'d'} df_l = pd.DataFrame.from_dict(dct_l, orient='index', columns=['Key']) dummy = np.zeros((4,3)) i... | You have different dtypes for your two indexes: df_e.index Index([1, 2, 3, 4], dtype='int64') df_l.index Index(['1', '2', '3', '4'], dtype='object') which will break the alignment (1 != '1'). Make sure they are identical. For example: pd.concat([df_l.rename(int), df_e], axis=1) Key POW KLA CSE 1 a 0.0 0.0 0.0 2 b 0.0 ... | 3 | 2 |
78,744,571 | 2024-7-13 | https://stackoverflow.com/questions/78744571/output-repeating-and-non-repating-digits-using-regex-from-s-1222311 | I am finding it difficult to write regex expression. Need your help in getting expected output. import re pattern1=r'(\d)\1{1,}' s = '1222311' c=re.finditer(pattern,s) for i in c: print(i.__getitem__(0)) I managed to get repeating digit but not able to get non repeating digit. How to frame regex to get non repeating d... | Changing your pattern to r'(\d)(\1*)' will select all digits, and group together each set of consecutive digits. Then with your list of matches, simply sort them based on length: import re s = '1222311' pattern = r'(\d)\1*' repeating_digits = [] non_repeating_digits = [] # finditer produces the following matches `['1',... | 2 | 1 |
78,743,607 | 2024-7-13 | https://stackoverflow.com/questions/78743607/socket-cant-find-af-unix-attribute | I'm using an Arch Linux machine and trying to run the following code from a Python file. import socket import sys if __name__ == "__main__": print(sys.platform) server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) and it keeps telling me that AttributeError: module 'socket' has no attribute 'AF_UNIX' Things tri... | The error is caused by an unlucky choice of variable name. The variable socket shadows the module of the same name. The first time the line is run, it works fine: import socket socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # works fine, but now socket points to the object returned by the socket.socket() ca... | 2 | 2 |
78,733,152 | 2024-7-11 | https://stackoverflow.com/questions/78733152/how-to-terminate-a-function-which-is-working-in-python | I want to make a code which works like this: after certain seconds I want to terminate the working function in the main function. I've tried the below code but when the code in the loop function isn't an async function(like await asyncio.sleep(1)) it doesn't work. import asyncio async def loop(): while True: pass async... | Use multiprocessing. When you want a function to be terminated after certain seconds, then all the function should start running simultaneously. My comments inside the code explains the rest. import multiprocessing as mp import time as t # function which needs to be terminated after certain seconds def func1(): # Do so... | 3 | 2 |
78,742,818 | 2024-7-13 | https://stackoverflow.com/questions/78742818/regex-find-matches-only-outside-of-single-quotes | I currently have a regex that selects all occurrences of (, , , );: (\s\()|(,\s)|(\),)|(\);) however, I've been trying to figure out a way so that if anything is between single quotes 'like this, for example', it'll ignore any of the matches listed above. I tried many different solutions, however none of them seemed to... | Expressing a not-find is a tricky thing, as everything around a regex is designed to work in a positive / greedy way (find as much as possible, whenever somehow possible). The easiest and most likely fastest thing you could to is to remove the parts you want to exclude prior to applying your search, assuming quotes alw... | 2 | 1 |
78,742,511 | 2024-7-12 | https://stackoverflow.com/questions/78742511/cumulative-calculation-across-rows | Suppose I have a function: def f(prev, curr): return prev * 2 + curr (Just an example, could have been anything) And a Polars dataframe: | some_col | other_col | |----------|-----------| | 7 | ... | 3 | | 9 | | 2 | I would like to use f on my dataframe cumulatively, and the output would be: | some_col | other_col | |... | It depends on the exact operation you need to perform. The example you've given can be expressed in terms of .cum_sum() with additional arithmetic: def plus_prev_times_2(col): x = 2 ** pl.int_range(pl.len() - 1).reverse() y = 2 ** pl.int_range(1, pl.len()) cs = (x * col.slice(1)).cum_sum() return cs / x + col.first() *... | 4 | 3 |
78,734,383 | 2024-7-11 | https://stackoverflow.com/questions/78734383/asyncio-how-to-chain-coroutines | I have the following test code, where I am trying to chain together different coroutines. The idea is that I want to have one coroutine that downloads data, and as soon as data is downloaded I want to get the data into the second routine which then process the data. The code below works, whenever I skip the process_dat... | The problem is that the line tg.create_task(process_data(download_dummy(task))) wont call process_data with the result of download_dummy, but with an awaitable - that is, the paramter that gets inside process_data have to be awaited to get to its value. For simple, hard-coded, pipelines, I´d usually just create a small... | 2 | 1 |
78,737,630 | 2024-7-11 | https://stackoverflow.com/questions/78737630/a-kerastensor-cannot-be-used-as-input-to-a-tensorflow-function | I have been following a machine-learning book by Chollet and I keep getting this error in this block of code, specifically in the 3rd line. It seems I am passing a Keras tensor into a tf function but I don't know how to get around this. import tensorflow as tf inputs = keras.Input(shape=(None,), dtype="int64") embedded... | Wrap the TensorFlow function (tf.one_hot) in a layer. And, replace the call to the function with a call to the new layer. eg: class EmbeddedLayer(keras.Layer): def call(self, x): return tf.one_hot(x, depth=max_tokens) inputs = keras.Input(shape=(None,), dtype="int64") embedded = EmbeddedLayer()(inputs) x = layers.Bidir... | 3 | 5 |
78,741,275 | 2024-7-12 | https://stackoverflow.com/questions/78741275/using-something-like-mydataframe-print-instead-of-printmydataframe | When I run a script from the Spyder console using runfile, source file lines containing expressions (e.g., "HELLO") don't print out to the console. I have to explicitly print, e.g., print("HELLO"). Is there a way to output the string representation of a pandas DataFrame using a method? Something like the very last chai... | I would just save the dataframe to a variable and print the variable. In any case, you can use pipe to achieve the behavior you're looking for: import pandas as pd df = pd.DataFrame({"a": [1, 2, 3]}) df.add(4).pipe(print) a 0 5 1 6 2 7 | 2 | 5 |
78,740,033 | 2024-7-12 | https://stackoverflow.com/questions/78740033/how-to-instantly-terminate-a-thread-using-ollama-python-api-with-tkinter-to-str | I'm using ollama to stream a response from llama2 large language model. The functionality I need is, when I click the stop button, it should stop the thread immediately. The code below works but the problem is, it always waits for the first chunk to be available before it checks if stop is True. Sometimes the response ... | You cannot instantly terminate a thread in python. This ollama API currently offers an async client, you can use the async client and cancel the Task, this should close the async connection almost instantly. import tkinter as tk import ollama import threading import asyncio from typing import Optional # Create the main... | 2 | 1 |
78,739,598 | 2024-7-12 | https://stackoverflow.com/questions/78739598/python-rgba-image-non-zero-pixels-extracting-numpy-mask-speed-up | I need to extract non-zero pixels from RGBA Image. Code below works, but because I need to deal with really huge images, some speed up will be salutary. Getting "f_mask" is the longest task. Is it possible to somehow make things work faster? How to delete rows with all zero values ([0, 0, 0, 0]) faster? import numpy as... | Analysis ~np.all(f_pts == 0, axis=1) is sub-optimal for several reasons: First of all, the operation is memory-bound (typically by the RAM bandwidth) because the image is huge (400 MB in memory) -- even the boolean masks are huge (100 MB). Moreover, Numpy creates multiple temporary arrays: one for the result of f_pts =... | 2 | 3 |
78,736,930 | 2024-7-11 | https://stackoverflow.com/questions/78736930/pycord-unknown-interaction | I'm trying to make a embed message with buttons. For support system but I'm getting Unknown interaction error. I added ephemeral=True to defer. Also changed this: interaction.response.send_messageto this interaction.followup.send() embed = discord.Embed( title="Are You Looking For Help?", description="Use buttons man."... | Edit: Based on furhter information, I would say that the issue also intermittently comes from a slow internet connection with discord from the computer your bot is running on. This means that upon recieving the interaction on your computer, the interaction will already have timed out, simply because it didn't arrive fa... | 4 | 4 |
78,737,053 | 2024-7-11 | https://stackoverflow.com/questions/78737053/importerror-cant-import-name-perf-counter-what-may-be-the-reason | I`ve been working on my code for Micropython-flashed ESP8266, and well... this error occured: from time import perf_counter ImportError: can't import name perf_counter I believe that the whole code itself is irrelevant, as the problem occurs during the import itself. What may be relevant though, is the list of funct... | In micropython, according to its documentation the time module doesn't have perf_counter. | 3 | 3 |
78,735,531 | 2024-7-11 | https://stackoverflow.com/questions/78735531/numpy-memory-error-when-masking-along-only-certain-axis-despite-having-sufficie | I have a large array and I want to mask out certain values (set them to nodata). But I'm experiencing an out-of-memory error despite having sufficient RAM. I have shown below an example that reproduces my situation. My array is 14.5 GB and the mask is ~7GB, but I have 64GB of RAM dedicated to this, so I don't understan... | I suspect the issue here is that combining slice-based and mask-based indexing leads to a memory-inefficient codepath. You might try expressing it this way so that you're using entirely mask-based indexing: arr[mask[None]] = nodata I don't know enough about the implementation of np.ndarray.__setitem__ to guess at why ... | 2 | 1 |
78,735,133 | 2024-7-11 | https://stackoverflow.com/questions/78735133/how-to-get-a-square-wave-with-specific-tails-length-by-using-numpy | I'm trying to represent a special square ware characterized by some feature as represented here: all values are related to thick parameter. Tails are related to the thick parameter and to the total length (the size of the tail is equal to three times the thickness plus a remainder which depends on the number of notche... | In your "OK" examples the parts do not add up to the length... I don't fully understand what numpy array you are trying to build, but to compute the values of the parameters, I think the easiest way is to take away from length the two default tails and one gap. What's left will be an unknonwn number of gap pairs includ... | 4 | 1 |
78,734,439 | 2024-7-11 | https://stackoverflow.com/questions/78734439/filling-in-plotted-polygon-shape-in-ternary-plot | I've plotted a polygon on a set of ternary axes using python-ternary and joined up the vertices to form a region on the plot. However, I'd like to be able to fill this region so that it is a shape rather than just the outline. I used the following code to generate the axes and a set of vertices for the polygon: import ... | Calling tax.ax.fill() will go to matplotlib's standard ax.fill(). That function doesn't work with ternary coordinates, it needs regular x and y coordinates. As tax.fill() isn't implemented in the ternary library, you can use project_sequence() from ternary.helpers to convert the ternary coordinates to regular xs and ys... | 4 | 2 |
78,733,218 | 2024-7-11 | https://stackoverflow.com/questions/78733218/how-to-format-string-date-for-aws-glue-crawler-data-frame-to-correctly-identify | I have some json data (sample below). aws glue crawler reads this data and creates a glue catalog database with table , and sets the date field as a string field . is there a way , i can format date in my json file such that crawler can identify this as a date field ? I plan to read this data into dynamic frame via aws... | You can use to_date to convert the string field to the date field in the spark dataframe as follows: from pyspark.sql.functions import to_date data=gluecontext.create_dynamic_frame.from_catalog(database="sample", table_name="table") data_frame = data.toDF() # convert the string field to the date field in the spark data... | 4 | 3 |
78,733,472 | 2024-7-11 | https://stackoverflow.com/questions/78733472/how-to-initialise-a-list-defined-at-the-class-level-from-a-common-method-outside | I have a list defined at the class level in Python and below is my code: class TestStudentReg(unittest.TestCase): student_id_list = [] I'm trying to initialise the list by reading values from a csv file and below is the method that i use within the same class i.e., TestStudentReg @classmethod def initialise_student_id... | There are multiple ways to solve your problem. Here I will list three with increasing readability and overall quality: def student_id_list_initialiser(class_obj, **kwargs): cls = class_obj filename = 'input/student_testdata.csv' with open(filename, 'r') as csvfile: datareader = (csv.reader(csvfile, delimiter="|")) next... | 2 | 2 |
78,733,361 | 2024-7-11 | https://stackoverflow.com/questions/78733361/how-to-take-the-average-of-all-previous-entries-in-a-group | I'd like to do the following in python using the polars library: Input: df = pl.from_repr(""" ┌──────┬────────┐ │ Name ┆ Number │ │ --- ┆ --- │ │ str ┆ i64 │ ╞══════╪════════╡ │ Mr.A ┆ 1 │ │ Mr.A ┆ 4 │ │ Mr.A ┆ 5 │ │ Mr.B ┆ 3 │ │ Mr.B ┆ 5 │ │ Mr.B ┆ 6 │ │ Mr.B ┆ 10 │ └──────┴────────┘ """) Output: shape: (7, 3) ┌─────... | cum_sum() and cum_count() to calculate cumulative average. shift() so it's calculated for 'previous' row. over() to do the whole operation within Name. df.with_columns( (pl.col.Number.cum_sum() / pl.col.Number.cum_count()) .shift(1, fill_value=0) .over("Name") .alias("average") ) ┌──────┬────────┬──────────┐ │ Name ┆... | 5 | 4 |
78,732,336 | 2024-7-10 | https://stackoverflow.com/questions/78732336/groupby-multiple-columns-and-extract-top-rows-based-on-non-grouped-column-value | I am trying to solve a problem some what very similar to: https://platform.stratascratch.com/coding/10362-top-monthly-sellers?code_type=2 here is my data frame: product seller market total_sales books s1 de 10 books s2 jp 20 books s3 in 30 books s1 de 25 books s5 in 15 books s1 us 12 books s2 uk 10 clothing s1 de 11 c... | You can do it like this: (dfs:= df.groupby(['product', 'seller', 'market'], as_index=False)['total_sales'].sum())\ .loc[dfs.groupby('product')['total_sales'].rank(ascending=False)<4]\ .sort_values(['product','total_sales'], ascending=[True, False]) Output: product seller market total_sales 0 books s1 de 35 4 books s3... | 3 | 4 |
78,729,859 | 2024-7-10 | https://stackoverflow.com/questions/78729859/numpythonic-way-to-fill-value-based-on-range-indices-reference-label-encoding-f | I have this tensor dimension: (batch_size, class_id, range_indices) -> (4, 3, 2) int64 [[[1250 1302] [1324 1374] [1458 1572]] [[1911 1955] [1979 2028] [2120 2224]] [[2546 2599] [2624 2668] [2765 2871]] [[3223 3270] [3286 3347] [3434 3539]]] How do I construct dense representation with filled value with this rule? Sinc... | IIUC, you could craft the output array with zeros, repeat, tile: start = data[..., 0].ravel() end = data[..., 1].ravel() slices = [slice(a,b) for a,b in zip(start, end)] n = end-start out = np.zeros(data.max(), dtype='int') out[np.r_[*slices]] = np.repeat(np.tile(np.arange(data.shape[1])+1, data.shape[0]), n) Variant ... | 2 | 1 |
78,729,171 | 2024-7-10 | https://stackoverflow.com/questions/78729171/how-to-have-the-size-of-markers-match-in-a-matplotlib-plot-and-in-its-legend | I have different (X,Y) data series drawn as scatter plots on one figure. Within each series, the marker size is set to different values according to the rank of the data point within the series (i.e. the 1st point in the series is shown with a smaller marker than the 2nd, which itself is shown with a smaller marker tha... | The markersizes in pyplot.scatter use the squared form, proportional to area (as you have already noted). However, those in the legend appear not to. I suggest that you set your marker sizes as the linear form (so that they are OK for the legend): marker_sizes = t+3 and then make the squaring explicit in pyplot.scatte... | 3 | 2 |
78,728,576 | 2024-7-10 | https://stackoverflow.com/questions/78728576/polars-apply-function-to-check-if-a-row-value-is-a-substring-of-another-string | I'm trying to check if string_1 = "this example string" contains a column value as a substring. For example the first value in Col B should be True since "example" is a substring of string_1 string_1 = "this example string" df = pl.from_repr(""" ┌────────┬─────────┬────────────┐ │ Col A ┆ Col B ┆ Col C │ │ --- ┆ --- ┆ ... | It's always better to avoid using python functions and use native polars expressions. pl.lit() to create a dummy column from string_1 str.contains() to check if string contains a column value. ( df .with_columns(pl.lit(string_1).str.contains(pl.col('Col B')).alias('new_col') ) Or you can use name.keep() if you want ... | 3 | 2 |
78,719,135 | 2024-7-8 | https://stackoverflow.com/questions/78719135/how-can-i-create-a-polars-struct-while-eval-ing-a-list | I am trying to create a Polars DataFrame that includes a column of structs based on another DataFrame column. Here's the setup: import polars as pl df = pl.DataFrame( [ pl.Series("start", ["2023-01-01"], dtype=pl.Date).str.to_date(), pl.Series("end", ["2024-01-01"], dtype=pl.Date).str.to_date(), ] ) shape: (1, 2) ┌───... | You shouldn't be passing a dictionary into the struct constructor. Just pass each IntoExpr as a keyword argument - that is, pl.struct(key1=IntoExprA, key2=IntoExprB, ...). In your case, you could replace your struct-ification code with the following: df = df.with_columns( pl.col("date_range") .list.eval( pl.struct( yea... | 3 | 3 |
78,727,228 | 2024-7-9 | https://stackoverflow.com/questions/78727228/replace-removed-function-pyarray-getcastfunc-in-numpy-2 | I'm migrating some python C extension to numpy 2. The extension basically gets a list of 2D numpy arrays and generates a new 2D array by combining them (average, median, etc,). The difficulty is that the input and output arrays are byteswapped. I cannot byteswap the input arrays to machine order (they are too many to f... | I have found a solution for my problem using NpyIter iterators. This type of iterators can be commanded to take care of the buffering and casting that I was doing manually previously. So my example would be something like: PyObject* input_frame_1; // input_frame_1 is initialized over here /* This var will contain the ... | 2 | 0 |
78,704,322 | 2024-7-3 | https://stackoverflow.com/questions/78704322/summing-values-based-on-date-ranges-in-a-dataframe-using-polars | I have a DataFrame (df) that contains columns: ID, Initial Date, Final Date, and Value, and another DataFrame (dates) that contains all the days for each ID from df. On the dates dataframe i want to sum the values if exist on the range of each ID Here is my code import polars as pl from datetime import datetime data = ... | update join_where() was added in Polars 1.7.0 ( dates.join_where( df, pl.col("date") >= pl.col("Initial Date"), pl.col("date") <= pl.col("Final Date"), ).group_by("date") .agg(pl.col("Value").sum()) ) ┌─────────────────────┬───────┐ │ date ┆ Value │ │ --- ┆ --- │ │ datetime[μs] ┆ i64 │ ╞═════════════════════╪═══════╡ ... | 6 | 5 |
78,721,195 | 2024-7-8 | https://stackoverflow.com/questions/78721195/attributeerror-np-string-was-removed-in-the-numpy-2-0-release-use-np-bytes | I m interested in seeing neural network as graph using tensorboard. I have constructed a network in pytorch with following code- import torch BATCH_SIZE = 16 DIM_IN = 1000 HIDDEN_SIZE = 100 DIM_OUT = 10 class TinyModel(torch.nn.Module): def __init__(self): super(TinyModel, self).__init__() self.layer1 = torch.nn.Linear... | Your code seems to be written in numpy < 2.0 compatible way, but it looks like you are running it with numpy >=2. Try downgrading the numpy version to < 2.0. | 6 | 4 |
78,715,358 | 2024-7-6 | https://stackoverflow.com/questions/78715358/how-to-assign-value-to-a-zero-dimensional-torch-tensor | z = torch.tensor(1, dtype= torch.int64) z[:] = 5 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: slice() cannot be applied to a 0-dim tensor. I'm trying to assign a value to a torch tensor but because it has zero dimensions the slice operator doesn't work. How do I assign a new value... | This is actually possible with copy_: z = torch.tensor(1, dtype=torch.int32) z.copy_(3.) >>> tensor(3, dtype=torch.int32) This will also cast it to the dtype of my variable. | 4 | 1 |
78,726,132 | 2024-7-9 | https://stackoverflow.com/questions/78726132/how-to-solve-importerror-dlopen-xxx-so-0x0002-symbol-not-found-in-flat | When I run a function in a python package, it returns: import gala.potential as gp Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/homebrew/lib/python3.11/site-packages/gala/potential/__init__.py", line 1, in <module> from .potential import * File "/opt/homebrew/lib/python3.11/site-pac... | OK so this is a linking problem. The library you are trying to import tries to call a function _gsl_sf_gamma (probably from the GSL library) but cannot find it. The library you are trying to import is programmed in a compiled language (most likely C or C++). In these languages, libraries, work a bit differently from ho... | 3 | 1 |
78,706,017 | 2024-7-4 | https://stackoverflow.com/questions/78706017/change-style-of-datatable-in-shiny-for-python | I would like to set a background color in a Shiny for Python DataTable from palmerpenguins import load_penguins from shiny import render from shiny.express import ui penguins = load_penguins() ui.h2("Palmer Penguins") @render.data_frame def penguins_df(): return render.DataTable( penguins, summary="Viendo filas {start}... | Updated answer, Shiny >= 1.0.0 Shiny now supports basic cell styling. From the Release Notes: @render.data_frame's render.DataGrid and render.DataTable added support for cell styling with the new styles= parameter. This parameter can receive a style info object (or a list of style info objects), or a function that acc... | 2 | 2 |
78,718,554 | 2024-7-7 | https://stackoverflow.com/questions/78718554/training-a-custom-feature-extractor-in-stable-baselines3-starting-from-pre-train | I am using the following custom feature extractor for my StableBaselines3 model: import torch.nn as nn from stable_baselines3 import PPO class Encoder(nn.Module): def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim=2): super(Encoder, self).__init__() self.encoder = nn.Sequential( nn.Linear(input_dim, em... | UPDATED answer Because your CustomFE imports already freezer Encoder (with requires_grad = False) you have that kind of situation where all weights of CustomFE are frozen. Thus by default CustomFE is not trainable. You will need to unfreeze it manually: model = PPO("MlpPolicy", env='FrozenLake8x8', policy_kwargs=polic... | 2 | 1 |
78,719,729 | 2024-7-8 | https://stackoverflow.com/questions/78719729/multivariate-normal-distribution-using-python-scipy-stats-and-integrate-nquad | Let be independent normal random variables with means and unit variances, i.e. I would like to compute the probability Is there any easy way to compute the above probability using scipy.stats.multivariate_normal? If not, how do we do it using scipy.integrate? | Based on the info from one of SO post mentioned in the comments: https://math.stackexchange.com/questions/270745/compute-probability-of-a-particular-ordering-of-normal-random-variables Also same method mentioned on wiki here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Affine_transformation You shoul... | 4 | 7 |
78,716,824 | 2024-7-7 | https://stackoverflow.com/questions/78716824/what-is-the-internal-implementation-of-copy-deepcopy-in-python-and-how-to-ov | When reading Antony Hatchkins' answer to "How to override the copy/deepcopy operations for a Python object?", I am confused about why his implementation of __deepcopy()__ does not check memo first for whether the current object is already copied before copying the current object. This is also pointed out in the comment... | The (reference) implementation for copy.deepcopy is here As you can see, the firsts thing that function does is check for the instance in the memo, so no need to check in your own implementation. Here is a breakdown of how that function works: deepcopy(x, memo=None) checks if x is in the memo. If it is, return the va... | 3 | 3 |
78,717,770 | 2024-7-7 | https://stackoverflow.com/questions/78717770/pandas-read-xml-file-with-designated-data-type | My code: df = pd.read_xml( path_or_buffer=PATH, xpath="//Data", compression="gzip" ) I'm using Pandas read_xml() function to read xml.gz format data. I'm using Pandas 1.3.2 version. When I tried to read the data, Pandas read data wrongly. The data looks like as below. Both colA and colB should be a string. 1st data fi... | Applying a simple xslt transformation to force string type on every value could work (I don't have pandas 1.3.2 to test but works on pandas 2.x). It does not seem possible to obtain a canonical answer given the version contraint. An alternative could be to parse xml doc with lxml and manually populate the dataframe. Th... | 2 | 5 |
78,727,839 | 2024-7-9 | https://stackoverflow.com/questions/78727839/create-config-file-for-python-script-with-variables | I have a config file for a python script that stores multiple different values my config.ini looks like this: [DHR] key1 = "\\path1\..." key2 = "\\path2\..." key3 = "\\path3\file-{today}.xlsx" my .py has a date variable that gets today's date like: today = str(date.today().strftime('%y%m%d')) However when I read the ... | You could provide a filtered locals() dictionary to the parser to interpolate variables. However, the syntax of the ini needs to be changed to configparser's basic interpolation syntax: [DHR] key3 = "\\path3\file-%(today)s.xlsx" from configparser import ConfigParser from datetime import date today = str(date.today().s... | 4 | 1 |
78,722,890 | 2024-7-8 | https://stackoverflow.com/questions/78722890/where-can-i-find-an-exhaustive-list-of-actions-for-spark | I want to know exactly what I can do in spark without triggering the computation of the spark RDD/DataFrame. It's my understanding that only actions trigger the execution of the transformations in order to produce a DataFrame. The problem is that I'm unable to find a comprehensive list of spark actions. Spark documenta... | All the methods annotated in the with @group action are actions. They can be found as a list here in scaladocs. They can also be found in the source where each method is defined, looking like this: * @group action * @since 1.6.0 */ def show(numRows: Int): Unit = show(numRows, truncate = true) Additionally, some other... | 9 | 5 |
78,725,322 | 2024-7-9 | https://stackoverflow.com/questions/78725322/how-to-use-depends-and-path-at-the-same-time-in-fastapi | I have the following endpoint: @router.get('/events/{base_id}') def asd(base_id: common_input_types.event_id) -> None: do_something() And this is common_input_types.event_id: event_id = Annotated[ int, fastapi.Depends(dependency_function), fastapi.Path( example=123, description="Lore", gt=5, le=100, ), ] This does no... | I don't think it's possible to annotate a parameter with Path and Depends at the same time. Depending on the logic you want to implement, you can move this logic to dependency_function: from typing import Annotated import fastapi app = fastapi.FastAPI() router = fastapi.APIRouter(prefix="") async def dependency_functio... | 2 | 2 |
78,728,028 | 2024-7-9 | https://stackoverflow.com/questions/78728028/performing-integral-over-infinity-with-numbers-in-excess-of-101000 | I am attempting to perform on an integral from -infinity to infinity, with an equation containing a term that is raised to the power M. At very high (5000+) values of M, this value of this term can exceed 10^100. I have this python (3.10) program, which works for M = 1000, but nothing much beyond that. import numpy as ... | No, your only problem is that you took the factor 1/2**M outside of the integral. If you put it back inside you will then have (erf_term/2)**M and that will not blow up because the difference of two error functions cannot exceed 2, so the new bracketed factor is less than 1. | 3 | 3 |
78,728,033 | 2024-7-9 | https://stackoverflow.com/questions/78728033/numpythonic-ways-of-converting-sparse-to-dense-based-on-referenced-index | I have this sparse vector val with this Pythonic way: idx = [2, 5, 6] val = [69, 12, 15] _ = np.zeros(idx[-1]+1) for i in idx: _[i] = val[idx.index(i)] print(_) dbg(_) Here is the output: [ 0. 0. 69. 0. 0. 12. .15] (6,) float64 How do I achieve my goal where it's not using for loops, instead using a Numpythonic way? | idx = [2, 5, 6] val = [69, 12, 15] _ = np.zeros(idx[-1]+1) numpy lets you set multiple values at once _[idx] = val | 2 | 2 |
78,727,544 | 2024-7-9 | https://stackoverflow.com/questions/78727544/how-to-make-derivativefx-x-take-an-explicit-value-after-f-is-defined | So I need to make take some derivatives first and later in the code (when the explicit form of f(x) is given) substitute the Derivative(f(x), x) with the explicit form of the derivative import sympy as sp import math x = sp.symbols('x') f = sp.Function('f')('x') df = f.diff(x) f = sp.sin(x) print(df) What I expect to ... | Substitute your known function into the derivative and execute the doit method: import sympy as sp import math x = sp.symbols('x') f = sp.Function('f')('x') df = f.diff(x) f_known = sp.sin(x) df.subs(f, f_known).doit() | 2 | 3 |
78,727,309 | 2024-7-9 | https://stackoverflow.com/questions/78727309/django-error-reverse-for-user-workouts-not-found-user-workouts-is-not-a-va | I'm working on my project for a course and I'm totally stuck right now. I'm creating a website to manage workouts by user and the create workout do not redirect to the user's workouts page when I create the new workout instance. views.py # View to return all user's workouts def user_workouts(request, user_id): user = U... | You specified an app_name = … [Django-doc], so it is: return redirect('myapp:user_workouts') | 3 | 1 |
78,727,326 | 2024-7-9 | https://stackoverflow.com/questions/78727326/how-to-run-a-function-at-startup-before-requests-are-handled-in-django | I want to run some code when my Django server starts-up in order to clean up from the previous end of the server. How can I run some code once and only once at startup before the server processes any requests. I need to access the database during this time. I've read a couple of things online that seem a bit outdated a... | This is often done with the .ready() method [Django-doc] of any of the AppConfig classes [Django-doc] of an installed app. So if you have an app named app_name, you can work with: # app_name/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): # … def ready(self): # my management command # … This wil... | 2 | 3 |
78,726,750 | 2024-7-9 | https://stackoverflow.com/questions/78726750/how-to-install-packages-using-uv-pip-install-without-creating-virtual-environm | I would like to install Python packages in the CI/CD pipeline using the uv package manager. I did not create a virtual environment because I would like to use the virtual machine's global Python interpreter. When I run the uv pip install <package> script, I get the following error: Requirement already satisfied: pip in... | It is possible to install packages into the system Python using the --system option: uv pip install --system <packages> The --system option instructs uv to instead use the first Python found in the system PATH. WARNING: --system is intended for use in continuous integration (CI) environments and should be used with c... | 6 | 5 |
78,726,475 | 2024-7-9 | https://stackoverflow.com/questions/78726475/how-to-ignore-a-specific-breakpoint-interactively | Consider this script: print("before loop") for i in range(100): breakpoint() print("after loop") breakpoint() print("exit") Short of pressing "c" one hundred times, how can you get past the breakpoint within the loop at L3 and proceed to L5? I've tried the ignore command but couldn't work it out: $ python3 example.py ... | You can use the PYTHONBREAKPOINT environment variable to call a custom breakpoint handler that you define in a separate file. For example: $ export PYTHONBREAKPOINT=mybreak.mybreak # mybreak/__init__.py import pdb _counter = 0 def mybreak(*args, **kwargs): global _counter if _counter >= 100: # default behavior pdb.set... | 4 | 2 |
78,726,288 | 2024-7-9 | https://stackoverflow.com/questions/78726288/attribute-auto-calculation-upon-retrieval | I am trying to make a point object in 3D in python, and I have the following code import numpy as np class Point3D: def __init__(self, x, y, z): self.vector = np.matrix([x, y, z]) self.vector.reshape(3, 1) def x(self): return self.vector.item((0, 0)) def y(self): return self.vector.item((0, 1)) def z(self): return self... | What you are wanting to do is property getter and setters. The @property decorator returns a value without having to call the method. I.e. use p.x instead of p.x(). To assign a value to the property, you use the @<propertyname>.setter decorator which implements assigning to the property via p.x = 3. I added a __repr__ ... | 2 | 1 |
78,725,967 | 2024-7-9 | https://stackoverflow.com/questions/78725967/translate-pandas-groupby-plus-resample-to-polars-in-python | I have this code that generates a toy DataFrame (production df is much complex): import polars as pl import numpy as np import pandas as pd def create_timeseries_df(num_rows): date_rng = pd.date_range(start='1/1/2020', end='1/01/2021', freq='T') data = { 'date': np.random.choice(date_rng, num_rows), 'category': np.rand... | You can pass additional columns to group by in a call to group_by_dynamic by passing a list with the named argument group_by=: df_pl = df_pl.group_by_dynamic( "date", every="1w", closed="right", group_by=["category", "subcategory"] ) With this, I get a dataframe that looks similar to the one your pandas code produces:... | 7 | 7 |
78,723,998 | 2024-7-9 | https://stackoverflow.com/questions/78723998/convert-string-to-dataframe-after-extracting-using-beautifulsoup | import requests import pandas as pd from bs4 import BeautifulSoup as bs from io import StringIO url = "https://www.tickertape.in/stocks/oil-and-natural-gas-corporation-ONGC" r = requests.get(url=url)#,headers=headers) soup = bs(r.content,'html5lib') fin = soup.find_all(class_="financials-table-root") for f in fin: str_... | You can use read_html with fixing columns names by remove Unnamed columns names and filter by length of them: url = "https://www.tickertape.in/stocks/oil-and-natural-gas-corporation-ONGC" df = pd.read_html(url)[2] cols = [c for c in df.columns if not c.startswith('Unnamed')] out = df.iloc[:, :len(cols)].set_axis(cols, ... | 2 | 2 |
78,721,505 | 2024-7-8 | https://stackoverflow.com/questions/78721505/choosing-between-yield-and-addfinalizer-in-pytest-fixtures-for-teardown | I've recently started using pytest for testing in Python and created a fixture to manage a collection of items using gRPC. Below is the code snippet for my fixture: import pytest @pytest.fixture(scope="session") def collection(): grpc_page = GrpcPages().collections def create_collection(collection_id=None, **kwargs): d... | The main difference is not the number of addfinalizer or fixtures, there is no difference at all. You can add as many as you want (or just have more than one operation in on of them) @pytest.fixture(scope='session', autouse=True) def fixture_one(): print('fixture_one setup') yield print('fixture_one teardown') @pytest.... | 3 | 6 |
78,708,727 | 2024-7-4 | https://stackoverflow.com/questions/78708727/efficiently-find-matching-string-from-substrings-in-large-lists | I have two lists containing about 5 million items each. List_1 is a list of tuples, with two strings per tuple. List_2, is a long list of strings. I am trying to find a compound string, made from those tuples, in List_2. So if the tuple from List_1 is ("foo", "bar"), and List_2 contains ["flub", "blub", "barstool", "fo... | The problem seems somewhat under-specified, but also over-specified. For example, what do tuples really have to do with it? I'll presume to reframe it like so: you have a list of strings, needles, and another list of strings, haystacks. You want to find all the haystacks that contain a (at least one) needle. First thin... | 2 | 5 |
78,721,341 | 2024-7-8 | https://stackoverflow.com/questions/78721341/efficiently-remove-rows-from-pandas-df-based-on-second-latest-time-in-column | I have a pandas Dataframe that looks similar to this: Index ID time_1 time_2 0 101 2024-06-20 14:32:22 2024-06-20 14:10:31 1 101 2024-06-20 15:21:31 2024-06-20 14:32:22 2 101 2024-06-20 15:21:31 2024-06-20 15:21:31 3 102 2024-06-20 16:26:51 2024-06-20 15:21:31 4 102 2024-06-20 16:26:51 2024-06-20 16:56:2... | You can use .transform() to create the mask. Sorting is not necessary when you can just use .nlargest() and select the second one if it exists. Or if time_1 is already sorted, you can even skip .nlargest() (or sorting) entirely. Then you just need to replace NaT with the smallest possible Timestamp value so that time_2... | 3 | 1 |
78,722,450 | 2024-7-8 | https://stackoverflow.com/questions/78722450/specify-none-as-default-value-for-boolean-function-argument | The prototype for numpy.histogram contains an input argument density of type bool and default value None. If the caller does not supply density, what value does it take on? The closest Q&A that I can find is this. The first answer says "Don't use False as a value for a non-bool field", which doesn't apply here. It also... | This is at best poorly documented. The documentation seems to imply that False and the default None will be treated equivalently, but it should either document that explicitly, or use the more sensible False as the default value. (The third option would be if the function makes a distinction between False and None, but... | 3 | 1 |
78,722,284 | 2024-7-8 | https://stackoverflow.com/questions/78722284/how-to-add-a-colon-after-each-two-characters-in-a-string | I have a list like this: list1 = [ '000c.29e6.8fa5', 'fa16.3e9f.0c8c', 'fa16.3e70.323b' ] I'm going to convert them to mac addresses in format 00:0C:29:E5:8F:A5 in uppercase. How can I do that? I googled but found nothing. I also thought how to do, but still don't have any clues. I just know this: for x in list1: x = ... | Another way, using bytes.fromhex() and bytes.hex(): >>> [":".join(bytes([b]).hex() for b in bytes.fromhex(l.replace(".", ""))) for l in list1] ['00:0c:29:e6:8f:a5', 'fa:16:3e:9f:0c:8c', 'fa:16:3e:70:32:3b'] Naturally, if you need upper-case, slap that on at the end. >>> [":".join(bytes([b]).hex() for b in bytes.fromhe... | 2 | 2 |
78,719,212 | 2024-7-8 | https://stackoverflow.com/questions/78719212/reducing-code-expression-duplication-when-using-polars-with-columns | Consider some Polars code like so: df.with_columns( pl.date_ranges( pl.col("current_start"), pl.col("current_end"), "1mo", closed="left" ).alias("current_tpoints") ).drop("current_start", "current_end").with_columns( pl.date_ranges( pl.col("history_start"), pl.col("history_end"), "1mo", closed="left" ).alias("history_t... | As it seems like you might not need any original columns, you could use select() instead of with_columns(), so you don't need to drop() columns. And you can loop over column names within select() / with_columns(): df.select( pl.date_ranges( pl.col(f"{c}_start"), pl.col(f"{c}_end"), "1mo", closed="left" ).alias(f"{c}_tp... | 2 | 4 |
78,721,860 | 2024-7-8 | https://stackoverflow.com/questions/78721860/how-can-i-change-values-of-a-column-if-the-group-nunique-is-more-than-n | My DataFrame: import pandas as pd df = pd.DataFrame( { 'a': ['a', 'a', 'a', 'b', 'c', 'x', 'j', 'w'], 'b': [1, 1, 1, 2, 2, 3, 3, 3], } ) Expected output is changing column a: a b 0 a 1 1 a 1 2 a 1 3 NaN 2 4 NaN 2 5 NaN 3 6 NaN 3 7 NaN 3 Logic: The groups are based on b. If for a group df.a.nunique() > 1 then df.a ==... | More efficient than groupby, use duplicated with keep=False, and boolean indexing: df.loc[~df[['a', 'b']].duplicated(keep=False), 'a'] = float('nan') If you really want to use groupby.transform: df.loc[df.groupby('b')['a'].transform('nunique')>1, 'a'] = float('nan') Output: a b 0 a 1 1 a 1 2 a 1 3 NaN 2 4 NaN 2 5 Na... | 2 | 1 |
78,721,501 | 2024-7-8 | https://stackoverflow.com/questions/78721501/making-an-image-move-in-matplotlib | I'm trying to have an image rotate and translate in matplotlib according to a predefined pattern. I'm trying to use FuncAnimation and Affine2D to achieve this. My code looks something like this : from matplotlib.animation import FumcAnimation from matplotlib.transforms import Affine2D from matplotlib import pyplot as p... | You're not using the value of the frames (0 or 1) to make the movement and that's not the only issue. So, assuming you want to simultaneously translate the image (to the right) and rotate_deg (relative to the center), you can do something like below : import matplotlib.pyplot as plt import matplotlib.transforms as mtra... | 3 | 0 |
78,721,966 | 2024-7-8 | https://stackoverflow.com/questions/78721966/polars-compute-variance-row-wise | I've the following dataframe df = pl.DataFrame({ "col1": [1, 2, 3], "col2": [4, 5, 6], "col3": [7, 8, 9], "col4": ["a", "v", "b"], }) I'd like to add a column containing the variance for all columns except col4. So far I've found this that could be a workaround the lack of horizontal computations in polars. df = ( (_... | selectors to filter out non-numeric columns. concat_list() to get chosen columns into list. list.var() to calculate variance. import polars.selectors as cs df.with_columns(var = pl.concat_list(cs.numeric()).list.var()) ┌──────┬──────┬──────┬──────┬─────┐ │ col1 ┆ col2 ┆ col3 ┆ col4 ┆ var │ │ --- ┆ --- ┆ --- ┆ --- ┆ -... | 2 | 4 |
78,712,904 | 2024-7-5 | https://stackoverflow.com/questions/78712904/create-a-similar-matrix-object-in-matlab-and-python | For comparison purposes, I want to create an object which would have the same shape and indexing properties in matlab and python (numpy). Let's say that on the matlab side the object would be : arr_matlab = cat(4, ... cat(3, ... [ 1, 2; 3, 4; 5, 6], ... [ 7, 8; 9, 10; 11, 12], ... [ 13, 14; 15, 16; 17, 18], ... [ 20, 2... | This is what you're trying to achieve in Python and MatLab: MatLab arr_matlab = reshape(1:120, [3, 2, 4, 5]); L = size(arr_matlab); disp(L); disp(arr_matlab(1, 2, 1, 1)); Prints 3 2 4 5 4 Python import numpy as np data = np.arange(1, 120 + 1) arr_python = data.reshape((3, 2, 4, 5), order='F') print(arr_python.shape) ... | 2 | 4 |
78,721,135 | 2024-7-8 | https://stackoverflow.com/questions/78721135/is-it-possible-to-dynamically-set-the-label-in-cypher-with-unwind-without-using | Here's my query: def create_entity_nodes(tx, report_id, entities): query = ( "UNWIND $entities AS entity " "MATCH (report:Report {id: $report_id}) " "CREATE (entity.name:entity.type entity), " "(report)-[:OWNS]->(entity.name) " "(entity.name)-[:BELONGS_TO]->(report)" "RETURN report" ) I previously only did it with one... | No, your first query won't work. At the moment, the only way to create labels dynamically is to build the query string as you did with your second query, or by using an apoc function like apoc.create.node. | 2 | 2 |
78,721,181 | 2024-7-8 | https://stackoverflow.com/questions/78721181/replace-subtrings-in-a-list-of-strings-using-dictionary-in-python | I have a list of substrings: ls = ['BLAH a b c A B C D 12 34 56', 'BLAH d A B 12 45 78', 'BLAH a/b A B C 12 45 78', 'BLAH a/ b A 12 45 78', 'BLAH a b c A B C D 12 34 99'] I want to replace the lower case substrings with an identifier: dict2 = {'a b c':'1','d':'2','a/b':'3','a/ b':'4'} I am looping over all the items ... | This way seems to work for me. Here is an online test: https://www.pythonmorsels.com/p/2qmeh/ result = [] for s in ls: for k, v in dict2.items(): s = s.replace(k, v) result.append(s) print(result) | 2 | 5 |
78,720,295 | 2024-7-8 | https://stackoverflow.com/questions/78720295/how-to-efficiently-set-column-values-based-on-multiple-other-columns | I have a dataframe that contains "duplicated" data in all columns but one called source. I match these records one to one per source into groups. Example data for such dataframe: id,str_id,partition_number,source,type,state,quantity,price,m_group,m_status 1,s1_1,111,1,A,1,10,100.0,,0 2,s1_2,111,1,A,1,10,100.0,,0 3,s1_3... | Using dataframe with aggregated duplicate records: list.len() to check length of the list. list.contains() to check if 1 is present. list.set_difference() to get list of non-1 elements. explode() to explode lists back into rows. when/then to conditionally create resulting m_status column. ( df.with_columns( l = pl.co... | 4 | 1 |
78,720,213 | 2024-7-8 | https://stackoverflow.com/questions/78720213/putting-polars-api-extensions-in-dedicated-module-how-to-import-from-target-mo | I want to extend polars API as described in the docs, like this: @pl.api.register_expr_namespace("greetings") class Greetings: def __init__(self, expr: pl.Expr): self._expr = expr def hello(self) -> pl.Expr: return (pl.lit("Hello ") + self._expr).alias("hi there") def goodbye(self) -> pl.Expr: return (pl.lit("Sayōnara ... | You could just import extensions(assuming that the file is relative) in your target.py file to register the greetings namespace. import polars as pl import extensions # noqa: F401 pl.DataFrame(data=["world", "world!", "world!!"]).select( [ pl.all().greetings.hello(), pl.all().greetings.goodbye(), ] ) See also: polars... | 2 | 2 |
78,705,398 | 2024-7-4 | https://stackoverflow.com/questions/78705398/break-the-curve-wherever-there-is-a-significant-change-in-the-curve | Wherever there's a significant change in the curve, I need to break the curve with a break thickness of just 1 pixel (I just want to break the curves into multiple parts). I have attached an image for reference. So after i read the image, i am thinning the curve and wherever there are red dots, i need to split it aroun... | Hough Transform https://en.wikipedia.org/wiki/Hough_transform K-means iterations with different K's - find how many line groups K-means again with the right K Pixel clustering by min distance to lines import math import cv2 as cv import numpy as np import matplotlib.pyplot as plt orig_im = cv.imread("/home... | 3 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.