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,017,670 | 2024-2-18 | https://stackoverflow.com/questions/78017670/is-it-possible-to-use-the-depthsort-argument-in-breadthfirst-layout-in-dash-cyto | I'm plotting a network using Dash-Cytoscape, using the breadthfirst layout, as documented here. I would like to control the order of appearance of elements on the same level. The JS API has the depthSort argument to achieve this, but I couldn't figure out how to pass a callback in Python that the frontend can live with... | Options that expect a JS function are not supported in Python, because it implies passing the function as a string, and thus it would require Cytoscape.js to evaluate arbitrary strings, which is probably something the maintainers don't want for security reasons. That said, Dash supports clientside callbacks (JS) so we ... | 3 | 4 |
78,017,053 | 2024-2-18 | https://stackoverflow.com/questions/78017053/langchain-agents-agent-toolkits-is-not-in-the-subpath-of-site-packages-la | I just upgrade LangChain and OpenAi using below conda install. Then I got below error, any idea how to solve it? Thanks https://anaconda.org/conda-forge/langchain conda install conda-forge::langchain https://anaconda.org/conda-forge/openai conda install conda-forge::openai from langchain.agents.agent_toolkits import cr... | It seems in October 2023, some logic related with agents was moved to a module called "experimental". You first need to install this new library: pip install langchain_experimental and then shift the module from where you import certain classes. PythonREPLTool and create_python_agent needs to be imported from the new... | 2 | 6 |
78,020,832 | 2024-2-19 | https://stackoverflow.com/questions/78020832/pandas-replace-with-value-from-another-row | I have a table: Object Col1 Col2 Col3 Col4 reference 10 14 7 29 Obj1 0 9 1 30 Obj2 1 16 0 17 Obj3 9 21 3 0 Obj4 11 0 4 22 I want to transform it by condition: if any cell (except the cells of the 1st row) is =0, then it must be replaced with an incremented (X+1) value from the 1st row of this column. ... | Use DataFrame.mask: out = df.mask(df == 0, df.iloc[0] + 1, axis=1) print (out) Col1 Col2 Col3 Col4 Object reference 10 14 7 29 Obj1 11 9 1 30 Obj2 1 16 8 17 Obj3 9 21 3 30 Obj4 11 15 4 22 | 2 | 5 |
78,020,461 | 2024-2-19 | https://stackoverflow.com/questions/78020461/comparing-a-numeric-pythons-list-against-a-pandas-dataframe | I have a Pandas's dataframe with 9 columns (called just dataframe), 5 of them called: [['DEG1','DEG2','DEG3','DEG4','DEG5']], it has almost 2000 rows. I have a list from which I build another dataframe with 5 columns called [['deg1','deg2','deg3','deg4','deg5']], this dataframe only has 1 row with the data series that ... | Use: #create sample data - for test rewrite last row by n_serie_list values np.random.seed(56) dataframe = pd.DataFrame(np.random.randint(10, size=(5,9)), columns=['DEG1','DEG2','DEG3','DEG4','DEG5','a','b','c','d']) n_serie_list = [2, 11, 21, 27, 41] dataframe.iloc[-1, :5] = n_serie_list print (dataframe) DEG1 DEG2 DE... | 2 | 1 |
78,019,970 | 2024-2-19 | https://stackoverflow.com/questions/78019970/pythonic-way-to-get-polars-data-frame-absolute-max-values-of-all-relevant-column | I want to create absolute maximum of all Polars data frame columns. Here is a way, but surely could be improved. import numpy as np import polars as pl df = pl.DataFrame({ "name": ["one", "one", "one", "two", "two", "two"], "val1": [1.2, -2.3, 3, -3.3, 2.2, -1.3], "val2": [1,2,3,-4,-3,-2] }) absVals = [] for col in df.... | You can use import numpy as np import polars as pl df = pl.DataFrame({ "name": ["one", "one", "one", "two", "two", "two"], "val1": [1.2, -2.3, 3, -3.3, 2.2, -1.3], "val2": [1,2,3,-4,-3,-2] }) polars.DataFrame.schema schema has the Column name as well as the Column datatype. pl.NUMERIC_DTYPES contains all the numeric d... | 3 | 2 |
78,019,900 | 2024-2-19 | https://stackoverflow.com/questions/78019900/how-can-i-use-list-comprehension-to-count-high-or-low-pair | I am trying to make my code more elegant/less verbose with list comprehension. I have the following so far: a = [47, 67, 22] b = [26, 47, 12] at = 0 bt = 0 for a, b in [c for c in zip(a, b)]: if a>b: at+=1 elif a<b: bt+=1 I've been trying to do something like this to remove the if elif statements: [at+=1 if (a>b) else... | I'm not sure that list comprehension is more elegant (because it can be harder to read for people new to the language). However, you can write something like: a = [47, 67, 22] b = [26, 47, 12] at = sum(1 for x,y in zip(a,b) if x > y) bt = sum(1 for x,y in zip(a,b) if x < y) This uses a generator expression to count al... | 2 | 2 |
78,005,112 | 2024-2-16 | https://stackoverflow.com/questions/78005112/create-dataframe-with-all-unique-combinations-given-a-set-of-constraints | I need to create a dataframe with all the possible unique combinations of n number of original arrays given a couple constraints. I want to be able to do this without filtering down the initial dataframe due to memory constraints. There will be two types of original input arrays. Either they will have boolean values of... | Key to not having to filter the float columns is making a block diagonal matrix. Everything else here is just .join(..., how = 'cross') from scipy.linalg import block_diag import pandas as pd import numpy as np inputs = { "a": [True, False], "b": [True, False], "c": [0.0, 0.1, 0.2], "d": [0.0, 0.1, 0.2, 0.3], } bool_in... | 3 | 2 |
78,018,799 | 2024-2-19 | https://stackoverflow.com/questions/78018799/how-to-transform-multi-columns-to-rows | I have a excel file with multi-columns as below (Sorry but I don't know how to recreate it with pandas): Below is my expected Output: import pandas as pd import numpy as np df = pd.DataFrame({'Code': ['11000000000', '11200100000', '11710000000', '11000000000', '11200100000', '11710000000', '11000000000', '11200100000'... | Create DataFrame with MultiIndex first in index and columns by parameters index_col and header and then use DataFrame.stack with first level and dropna parameter for avoid remove rows with missing values: df = pd.read_excel(file, index_col=[0,1,2], header=[0,1]) #test MultiIndex in columns print (df.columns) MultiIndex... | 2 | 2 |
78,017,555 | 2024-2-18 | https://stackoverflow.com/questions/78017555/numpy-create-a-3d-array-using-other-2-3d-arrays-and-a-1d-array-to-discriminate | I have 2 3D numpy arrays: a = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]) b = a + 100 and 1 1D array: c = np.array([0, 1, 0]) I want to create another 3D array which elements are from a and b based on c, i.e. if c is 0 take from a, if 1 take from b. The result should be... | You just need to up c to the desired dimension: np.where(c[:, None, None]==0, a, b) [[[ 1 2 3] [ 4 5 6]] [[107 108 109] [110 111 112]] [[ 13 14 15] [ 16 17 18]]] | 2 | 3 |
78,016,706 | 2024-2-18 | https://stackoverflow.com/questions/78016706/integration-from-a-set-of-acceleration-data-to-position | I'm trying for a project to integrate acceleration data in order to have an approximation of the position. I used a real simple set of data to start with, with a constant acceleration. from scipy.integrate import cumtrapz t = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7] a = [-9.8, -9... | First of all, scipy.integrate.cumtrapz is left for backward compatibility, you should use the newer scipy.integrate.cumulative_trapezoid function. Secondly, if you read the documentation you'll see that initial is not an initial condition but simply a value prepended onto the array, which would normally be one element ... | 2 | 3 |
78,013,162 | 2024-2-17 | https://stackoverflow.com/questions/78013162/typehint-function-args-tupleargs-with-constraint-on-the-args | We want to type hint a function def f(*args:float)->tuple[float,...]: ... return tuple(args) such that it is specified that the number of elements in the tuple matches the number of args. Of course, the return here is a placeholder for more complicated logic. We would like to use mypy or pylance to check if we always ... | Yes, you can write a no-op decorator to make the signature of f reject attempts at passing a type that you don't want. The following example makes f reject any attempts at passing values which aren't compatible with float. Demo: mypy Playground, Pyright Playground import typing_extensions as t if t.TYPE_CHECKING: impor... | 2 | 2 |
77,992,101 | 2024-2-14 | https://stackoverflow.com/questions/77992101/how-to-get-all-elements-as-rows-for-each-href-in-html-and-add-it-to-a-pandas-dat | I am trying to fetch as rows the different values inside each href element from the following website: https://www.bmv.com.mx/es/mercados/capitales There should be 1 row that matches each field on the provided headers for each different href element on the HTML file. This is one of the portions of the HTML that I am tr... | As mentioned before, the table is loaded and rendered dynamically via JavaScript, something you could not handle with requests because it just get the static response and does not behave like a browser. A solution to mimic a browsers behaviour is given by @thetaco using selenium but you could get your goal also with re... | 5 | 4 |
78,015,392 | 2024-2-18 | https://stackoverflow.com/questions/78015392/vectorize-a-folding-process-in-a-dataframe | Suppose we have a sample dataframe like the one below: df = pd.DataFrame({'A': [np.nan, 0.5, 0.5, 0.5, 0.5], 'B': [np.nan, 3, 4, 1, 2], 'C': [10, np.nan, np.nan, np.nan, np.nan]}) >>> df A B C 0 NaN NaN 10.0 1 0.5 3.0 NaN 2 0.5 4.0 NaN 3 0.5 1.0 NaN 4 0.5 2.0 NaN Col 'D' is calculated with the following operation: >>>... | I'm not aware of pure vectorized pandas/numpy solution, but you can try to use numba to speed up the computation: from numba import njit @njit def calculate(A, B, starting_value=10): out = np.empty_like(A, dtype=np.float64) out[0] = starting_value for i, (a, b) in enumerate(zip(A[1:], B[1:]), 1): out[i] = (out[i - 1] *... | 5 | 3 |
78,014,923 | 2024-2-18 | https://stackoverflow.com/questions/78014923/why-is-this-multi-threaded-code-faster-than-the-sequential-one-if-the-task-is-1 | I have two simple code examples of the same calculation, which creates load on the CPU. The sequential one is significantly slower then the multi-threaded one. If I understand the concept of the GIL correctly, that should not be the case, as just one thread can run at the same time. So the overall time should be the sa... | The reason is that in the sequential code, you have global variables for reading and writing but in the threaded code, the variables are local. Local variables are stored(STORE_FAST) and loaded(LOAD_FAST) much faster because the namespace of the functions are actually an array, instead of the dictionary and Python acce... | 2 | 2 |
78,014,412 | 2024-2-18 | https://stackoverflow.com/questions/78014412/big-o-notation-of-string-permutation-in-python | def permutation(str): #str = string input if len(str) == 0: return [""] result = [] for i, char in enumerate(str): for p in permutation(str[:i] + str[i + 1 :]): result.append(char + p) return result I am confused in asymptotic analysis (time complexity) in this code does it have an O(n!) or O(n*n!) because the recursi... | Let the time complexity of the function be T(n), where n is the length of the input string. For the case where n is not 0, we need to consider the following parts: For the outer loop, it needs to be repeated n times. For the outer loop body, the time complexity of each recursive call is T(n - 1). (I omitted the O(n) ... | 4 | 4 |
78,007,405 | 2024-2-16 | https://stackoverflow.com/questions/78007405/aggregating-over-subsets-of-columns-in-numpy-array | I'm trying to compute the aggregate metrics (e.g. mean, median, sum) of column subsets in a numpy array. Take this array for example: 1 6 3 4 2 3 4 5 1 4 5 6 3 5 6 7 I have a set of clusters, which are lists of column indices like this: clusters = [[0, 1], [2], [3]] Both the array and the list of cluster indices can ... | A start would be to sum the columns in numpy and then only sum up the results: n = 10**4 arr = np.random.rand(n,n) clusters = [[random.randint(0,n-1) for _ in range(random.randint(0,n))] for _ in range(n//100)] %%timeit arr_sumed = arr.sum(0) [arr_sumed[c_indices].sum() for c_indices in clusters] 38.6 ms ± 1.08 ms pe... | 2 | 3 |
78,011,941 | 2024-2-17 | https://stackoverflow.com/questions/78011941/django-application-to-manage-a-small-inventory | I have created a very small Django application to manage a very small Inventory. My models.py code is: class Inventory(models.Model): account = models.ForeignKey( "accounts.Account", on_delete=models.DO_NOTHING, null=False, blank=False ) class InventoryProduct(models.Model): inventory = models.ForeignKey("Inventory", o... | 1. Tracking Transfers Between Inventories To keep track of where the products are coming from, you might consider adding a transferred_from field as well. This will allow you to create a direct link between the source and destination inventories for each transfer. class Transaction(models.Model): # Existing fields... t... | 2 | 2 |
78,010,688 | 2024-2-17 | https://stackoverflow.com/questions/78010688/return-all-rows-above-last-row-until-condition-is-met-in-python-dataframe | I have a data frame that oscillates between negative and positive values. What I'm looking to do is find the value of the last row, and return a dataframe of all rows above it until the sign changes form negative to positive or vice versa. An example of problem would be something like this import numpy as np import pan... | Example Code If you generate a DataFrame randomly, you must provide a seed. I will generate a new DataFrame as an example because you did not provide a seed. import pandas as pd df = pd.DataFrame([1, 2, 3, -4, 0, 1, 2] , columns=list('v')) df: v 0 1 1 2 2 3 3 -4 4 0 5 1 6 2 Code s = df['v'].mask(df['v'].eq(0)).ffil... | 2 | 1 |
78,009,548 | 2024-2-16 | https://stackoverflow.com/questions/78009548/selenium-urllib-error-httperror-http-error-404-not-found | Traceback (most recent call last): File "C:\Users\nenuk\OneDrive\Desktop\Creator\32.py", line 556, in <module> driver = uc.Chrome(options=opts) File "C:\Users\nenuk\AppData\Local\Programs\Python\Python312\Lib\site-packages\undetected_chromedriver\__init__.py", line 258, in __init__ self.patcher.auto() File "C:\Users\ne... | def fetch_package(self): """ Downloads ChromeDriver from source :return: path to downloaded file """ zip_name = f"chromedriver_{self.platform_name}.zip" if self.is_old_chromedriver: download_url = "%s/%s/%s" % (self.url_repo, self.version_full.vstring, zip_name) else: zip_name = zip_name.replace("_", "-", 1) #download... | 2 | 10 |
78,000,777 | 2024-2-15 | https://stackoverflow.com/questions/78000777/improve-scipy-integrate-quad-vec-performance-for-fitting-integral-equation-work | I am using quad_vec in a function that contains an integral not solvable with analytic methods. I need to fit this equation to data points. However, even the evaluation with fixed values takes multiple seconds, the total fit time grows to 7 min. Is there a way to accelerate the computation? I know quad_vec has the work... | There are certainly some code optimizations in the comments that can speed things up, so I'll complement that by focusing on the integration. If you can use a GPU, you can get two to three orders of magnitude speedup there. One of the simplest things that you can do to improve the speed without sacrificing too much acc... | 4 | 3 |
78,008,970 | 2024-2-16 | https://stackoverflow.com/questions/78008970/flyte-wont-run-in-parallel | I'm new to flyte, trying to do quite simple things at the moment. So I'm trying to to run multiple independant tasks in parallel, which, if I understand the documentation, is exactly the purpose of map_task. However, so far I've been unable to make flyte actually run them in parallel. Any help would be greatly apprecia... | Could you give more context please? How are you trying to run it? Is this running in remote (like on a live Flyte backend) or is this a local run? Local runs will not actually do parallel just yet. (Making flytekit execute local runs in parallel is part of a broader project that we have plans for some day, but no defin... | 2 | 2 |
78,008,394 | 2024-2-16 | https://stackoverflow.com/questions/78008394/how-do-i-get-the-line-numbers-of-a-saxonc-xpath-match | I'm building a report that will show the line numbers of XML elements that match a set of XPaths. I need to support XPath 2.0. Sending the XML to a separate web based processor written in Java or C# is a valid solution, but one I'm avoiding because my entire team works in Python, I want my tool to still work offline, a... | I am afraid I can't currently tell there is a way for SaxonC HE, for PE/EE you should be able to use the Saxon XPath extension function saxon:line-number e.g. from saxoncee import PySaxonProcessor with PySaxonProcessor(license=True) as saxon_proc: print(saxon_proc.version) doc_builder = saxon_proc.new_document_builder(... | 2 | 3 |
77,994,344 | 2024-2-14 | https://stackoverflow.com/questions/77994344/how-to-validate-object-attribute-added-like-that-myobj-newattribute-123 | In my code (python) I have a class defined as follows: class Properties: def __init__(self,**kwargs): self.otherproperty = kwargs.get("otherproperty") self.channel = kwargs.get("channel") if self.channel not in "A": print("bad channel input - it should be A") pass In the rest of my code, in various places I calculate ... | You can define a custom setter for the channel property with Python descriptors: class Properties: def __init__(self, **kwargs): self.otherproperty = kwargs.get("otherproperty") self._channel = None # Private attribute for channel @property def channel(self): return self._channel @channel.setter def channel(self, value... | 2 | 3 |
78,000,334 | 2024-2-15 | https://stackoverflow.com/questions/78000334/my-tkinter-app-wont-change-the-file-it-is-loading | I am writing a tkinter app in python that is a flash card quiz. It needs to be able to read from a txt file one folder ahead from the python file. In the cide you can change which file is the file loaded but this is not working even if you choose the same file. When i tried to change the file in filehandling() it broke... | Code: This code is working fine for me, although I commented out temp_list.append(temp[i+1].capitalize()) as its causing IndexOutOfRange error: from customtkinter import * from CTkMessagebox import CTkMessagebox import glob import os information = [] file_name_old = 'keywords.txt' file_name = './Text/'+file_name_old ap... | 2 | 2 |
78,003,276 | 2024-2-15 | https://stackoverflow.com/questions/78003276/how-to-generate-uniformly-distributed-subintervals-of-an-interval | I have a non-empty integer interval [a; b). I want to generate a random non-empty integer subinterval [c; d) (where a <= c and d <= b). The [c; d) interval must be uniformly distributed in the sense that every point in [a; b) must be equally likely to end up in [c; d). I tried generating uniformly distributed c from [a... | If you divide the range [a,b) into N sections, and then select one of those sections at random, then the chance of selecting each point is uniform -- 1/N. It doesn't matter how you divide the range. Here's a solution along those lines that uses a pretty uniform selection of division points. from random import randint a... | 2 | 2 |
78,003,100 | 2024-2-15 | https://stackoverflow.com/questions/78003100/running-pip-install-in-virtual-environment-tries-to-install-packages-in-default | I am trying to install modules for python on my raspberry pi 5 in a virtual environment but it just says that the environment is externally managed. I started with activating the virtual environment and trying to install the package I needed but it just told me the environment was externally managed. clock@system-time:... | sudo runs a new root shell which has no idea about your current shell's settings (including which virtual environment is active). Absolutely don't use sudo if you want to install things into the currently active user-owned virtual environment. Anyway, the entire purpose of having a virtual environment is that it's comp... | 2 | 3 |
77,996,886 | 2024-2-14 | https://stackoverflow.com/questions/77996886/voxelization-issue-with-open3d-incomplete-filling-along-some-triangle-faces | I'm currently using Open3D in Python to voxelize meshes, and I've come across a peculiar behavior during the process. When voxelizing a box mesh, it appears that the resulting voxels only align along the lines of the triangles instead of filling the entire surface area of the triangle faces, particularly noticeable on ... | After encountering an issue with Open3D's voxelization process, I discovered that the problem had been raised and addressed on GitHub in this thread. The issue was resolved in Open3D version v0.18.0. However, when attempting to update the package using pip, I encountered difficulties as pip couldn't find the correct co... | 2 | 2 |
77,996,739 | 2024-2-14 | https://stackoverflow.com/questions/77996739/how-to-build-a-3d-matrix-from-1d-time-series-in-numpy | Suppose I have four (N,) vectors A, B, C, and D: import numpy as np N = 100 A = 1*np.ones(N) # => array([1,1,1,...]) B = 2*np.ones(N) # => array([2,2,2,...]) C = 3*np.ones(N) # => array([3,3,3,...]) D = 4*np.ones(N) # => array([4,4,4,...]) In my application, these are each an element of a matrix and the matrix varies ... | Concatenate as a 3D intermediate with dstack, then you'll be in the ideal order to perform a simple reshape: np.dstack([A, B, C, D]).reshape(N, 2, 2) Output: array([[[1., 2.], [3., 4.]], [[1., 2.], [3., 4.]], [[1., 2.], [3., 4.]], ..., [[3., 4.], [3., 4.]]]) Intermediate: np.dstack([A,B,C,D]).shape # (1, 100, 4) | 3 | 3 |
77,996,844 | 2024-2-14 | https://stackoverflow.com/questions/77996844/how-to-explode-a-pandas-dataframe-that-has-nulls-in-some-rows-but-populated-in | So I have many dataframes coming in that need to be exploded. they look something like this: df = pd.DataFrame({'A': [1, [11,22], [111,222]], 'B': [2, [33,44], float('nan')], 'C': [3, [55,66], [333,444]], 'D': [4, [77,88], float('nan')] }) +-----------+---------+-----------+---------+ | A | B | C | D | +-----------+--... | One option could be to explode each column separately and deduplicate the index before concat: def explode_dedup(s): s = s.explode() return s.set_axis( pd.MultiIndex.from_arrays([s.index, s.groupby(level=0).cumcount()]) ) out = pd.concat({c: explode_dedup(df[c]) for c in df}, axis=1) Output: A B C D 0 0 1 2 3 4 1 0 1... | 2 | 1 |
77,996,196 | 2024-2-14 | https://stackoverflow.com/questions/77996196/how-to-duplicate-rows-based-on-the-number-of-weeks-between-two-dates | My input is this dataframe : df = pd.DataFrame( { 'ID': ['ID001', 'ID002', 'ID003'], 'DATE': ['24/12/2023', '01/02/2024', '12/02/2024'], } ) df['DATE'] = pd.to_datetime(df['DATE'], dayfirst=True) print(df) ID DATE 0 ID001 2023-12-24 1 ID002 2024-02-01 2 ID003 2024-02-12 I'm trying to duplicate the rows for each id N t... | I would use periods for that and Index.repeat: # compute exact difference in weeks n_weeks = (df['DATE'].dt.to_period('W') .rsub(pd.Timestamp('now').to_period('W')) .apply(lambda x: x.n) ) # repeat rows, add incrementing days, convert to week number out = (df.loc[df.index.repeat(n_weeks+1)] .assign(WEEK=lambda d: df['D... | 3 | 2 |
77,996,089 | 2024-2-14 | https://stackoverflow.com/questions/77996089/polars-to-dicts-is-the-order-of-the-list-of-dictionaries-guaranteed | I am leveraging the function .to_dicts() in my testing the resulting list of dictionaries has the same order as the dataframe. df = pl.DataFrame(data={ "name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35], "city": ["New York", "London", "Paris"], }).sort(by=['name'], descending=True) data = df.to_dicts() for record... | TLDR. Yes. This can be seen by inspecting this underlying rust function, which maps over the indices of the DataFrame in order. | 4 | 2 |
77,995,796 | 2024-2-14 | https://stackoverflow.com/questions/77995796/mocking-directly-imported-function | I am trying to write unit tests for my python project using pytest. I have a module from another repo called sql_services. Within sql_services there is a function called read_sql that I am trying to mock. So far, I have only been able to mock the function if I import the module like import sql_services and invoke sql_... | You just patch the correct name: @mock.patch("entry.read_sql") def test_read_sql(mock_read_sql): mock_read_sql.return_value = pd.DataFrame() df = sql_services.read_sql("SELECT * FROM schema.table") assert df.empty] entry.foo is using the global variable entry.read_sql to access the function you want to mock, not the g... | 2 | 2 |
77,994,983 | 2024-2-14 | https://stackoverflow.com/questions/77994983/difference-between-and-expression-api | What is the difference between using square brackets [ ] and using Expression APIs like select, filter, etc. when trying to access data from a polars Dataframe? Which one to use when? a polars dataframe df = pl.DataFrame( { "a": ["a", "b", "a", "b", "b", "c"], "b": [2, 1, 1, 3, 2, 1], } ) | Usually, it is advised to use the polars expression API as most of the methods are part of polars lazy API. The API defers the evaluation of many operations, such as selection, filtering, and mutation, until the result is actually needed. This allows for the query optimizations that makes polars as efficient as it is. ... | 5 | 2 |
77,995,211 | 2024-2-14 | https://stackoverflow.com/questions/77995211/polars-manipulation-on-columns-by-dtype-creating-multiple-new-columns | data = {"col1": ['2020/01/01', '2020/02/01'], "col2": ['2020/01/01', '2020/02/01']} df = pl.DataFrame(data, schema={"col1": pl.String, "col2": pl.String}) df = df.with_columns( pl.col('col1').str.to_datetime(), pl.col('col2').str.to_datetime() ) df.with_columns( pl.col(pl.DATETIME_DTYPES).dt.year() ) With the given co... | For this, you can use the methods in the pl.Expr.name namespace. The most flexible method would be pl.Expr.name.map, but there is also pl.Expr.name.prefix, pl.Expr.name.suffix, etc. df.with_columns( pl.col(pl.DATETIME_DTYPES).dt.year().name.map(lambda s: s + "_year") ) Output. shape: (2, 4) ┌─────────────────────┬────... | 3 | 2 |
77,994,817 | 2024-2-14 | https://stackoverflow.com/questions/77994817/how-to-reshape-a-polars-dataframe | I am new to polars, but have worked quite a bit with pandas and numpy. Let's say I have a dataframe df like: Column 1 Column 2 Column 3 Column 4 Column 5 Column 6 A 1 W B 2 X C 3 Y D 4 Z I would like to do something like df.reshape((-1,3)) (in numpy) in order to obtain: Column 1 Column 2 Column 3 A 1... | I don't think polars has a specialised reshape function for the scenario outlined above. However, you could combine pl.concat to concatenate dataframe fragments created using pl.DataFrame.select. pl.concat([ df.select("Column 1", "Column 2", "Column 3"), df.select( pl.col("Column 4").alias("Column 1"), pl.col("Column 5... | 4 | 3 |
77,992,562 | 2024-2-14 | https://stackoverflow.com/questions/77992562/how-to-group-by-and-find-new-or-disappearing-items | I am trying to assess in a sales database whether the # of advertisements has changed. The example dataframe I am using is as such: df = pd.DataFrame({"offer-id": [1,1,2,2,3,4,5], "date": ["2024-02-10","2024-02-11","2024-02-10","2024-02-11","2024-02-11","2024-02-11","2024-02-10"], "price": [30,10,30,30,20,25,20]}) And... | You could aggregate as a set: offers = df.groupby('date', sort=True)['offer-id'].agg(set) date 2024-02-10 {1, 2, 5} 2024-02-11 {1, 2, 3, 4} Name: offer-id, dtype: object Then getting the diff will give you the new items: offers.diff() date 2024-02-10 NaN 2024-02-11 {3, 4} Name: offer-id, dtype: object Or the sold ite... | 2 | 3 |
77,992,176 | 2024-2-14 | https://stackoverflow.com/questions/77992176/pandas-idxmax-top-n-values | I have this code: import pandas as pd df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48], 'co2_emissions': [37.2, 19.66, 1712]}, index=['Pork', 'Wheat Products', 'Beef']) df['Max'] = df.idxmax(axis=1, skipna=True, numeric_only=True) df I need to find the n largest values. Here there is a technique using apply/la... | Your error is due to passing the skipna and numeric_only parameters to apply. You can fix it with: (df.select_dtypes('number') .apply(lambda s: s.dropna().abs().nlargest(2) .index.tolist(), axis=1) ) Output: Pork [co2_emissions, consumption] Wheat Products [consumption, co2_emissions] Beef [co2_emissions, consumption]... | 2 | 1 |
77,976,508 | 2024-2-11 | https://stackoverflow.com/questions/77976508/how-to-send-parallel-request-to-google-gemini | I have 107 images and I want to extract text from them, and I am using Gemini API, and this is my code till now: # Gemini Model model = genai.GenerativeModel('gemini-pro-vision', safety_settings=safety_settings) # Code images_to_process = [os.path.join(image_dir, image_name) for image_name in os.listdir(image_dir)] # l... | 2024-10 update: I've added a Cookbook Quickstart on asynchronous requests to show how this works. The advice below is still correct. In synchronous Python you can use something like a ThreadPoolExecutor to make your requests in separate threads. The Gemini Python SDK has an async API though, which can be a bit more na... | 9 | 7 |
77,983,609 | 2024-2-12 | https://stackoverflow.com/questions/77983609/merge-some-columns-in-a-polars-dataframe-and-duplicate-the-others | I have a similar problem to how to select all columns from a list in a polars dataframe, but slightly different: import polars as pl import numpy as np import string rng = np.random.default_rng(42) nr = 3 letters = list(string.ascii_letters) uppercase = list(string.ascii_uppercase) words, groups = [], [] for i in range... | You can extend this answer to your previous question by @jqurious to include index, such as words and groups, as follows: ( df .unpivot(index=["words", "groups"]) .with_columns(pl.col("variable").str.replace("_.*", "")) .with_columns(index = pl.int_range(pl.len()).over("variable")) .pivot(on="variable", index=["index",... | 3 | 3 |
77,969,964 | 2024-2-9 | https://stackoverflow.com/questions/77969964/deprecation-warning-with-groupby-apply | I have a python script that reads in data from a csv file The code runs fine, but everytime it runs I get this Deprecation message: DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated, and in a future version of pandas the grouping columns will be excluded from the o... | About include_groups parameter The include_groups parameter of DataFrameGroupBy.apply is new in pandas version 2.2.0. It is basically a transition period (2.2.0 -> 3.0) parameter added to help communicating a changing behavior (with warnings) and to tackle pandas Issue 7155. In most cases you should be able to just set... | 43 | 68 |
77,974,525 | 2024-2-10 | https://stackoverflow.com/questions/77974525/what-is-the-right-way-to-await-cancelling-an-asyncio-task | The docs for cancel make it sound like you should usually propagate CancelledError exceptions: Therefore, unlike Future.cancel(), Task.cancel() does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged. Should the coroutine nevertheless d... | You have a cleanup problem. The with statement is generally used to solve cleanup. Use asyncio.TaskGroup: async with asyncio.TaskGroup() as tg: tg.create_task(some_coro(...)).cancel() | 6 | 2 |
77,970,277 | 2024-2-9 | https://stackoverflow.com/questions/77970277/setting-resources-dynamically-on-snakemake | Context I am running a snakemake (v.7.32.4) pipeline using slurm task manager. I have set resources (time and memory for each rule) dynamically based on file size and # of tries, like this: rule index: resources: mem_mb = lambda wildcards, input, attempt: ( 200 * attempt ), runtime = lambda wildcards, input, attempt: (... | 1) Is it possible to set resources dinamically outside of snakefile? Depends on the snakemake version. For v8.14.0, yes. For version 7.32.4, sort of. See both scenarios below. Snakemake version 7.34.4 You can call a function on snakefile and declare the function elsewhere, as proposed by @SultanOrazbayev: Snakefile: fr... | 3 | 1 |
77,989,391 | 2024-2-13 | https://stackoverflow.com/questions/77989391/how-do-i-extract-data-from-a-document-using-the-openai-api | I want to extract key terms from rental agreements. To do this, I want to send the PDF of the contract to an AI service that must return some key terms in JSON format. What are some of the different libraries and companies that can do this? So far, I've explored the OpenAI API, but it isn't as straightforward as I woul... | Note: The code below works with the OpenAI Assistants API v1. In April 2024, the OpenAI Assistants API v2 was released. See the migration guide. What you want to use is the Assistants API. As of today, there are 3 tools available: Code Interpreter Knowledge Retrieval Function calling You need to use the Knowledge Re... | 2 | 2 |
77,973,380 | 2024-2-10 | https://stackoverflow.com/questions/77973380/how-to-validate-email-uniqueness-with-pydantic-and-fastapi | i'm trying to validate input email from request body and i have build custom field validator at model. here is code of RegisterModel: from pydantic import BaseModel, EmailStr, Field, field_validator from repository.repository_user import UserRepository from pprint import pprint class RegisterModel(BaseModel): name:str ... | As mentioned in the comments by @Chiheb Nexus, Do not call the Depends function directly. Instead, use the Annotated dependency which is more graceful. For example, the config/db.py file should look like this: # config/db.py from typing import Annotated from fastapi import Depends from pymongo import MongoClient from p... | 2 | 1 |
77,989,609 | 2024-2-13 | https://stackoverflow.com/questions/77989609/how-to-enable-cors-in-fastapi-for-local-html-file-loaded-via-a-file-url | I am trying to enable CORS in FastAPI on my localhost with credentials enabled. According to the docs we must explicitly set allow_origins in this case: from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware, Response app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=['http://loc... | Since you haven't provided the actual CORS error in your question, it should be specified here for future readers visiting this post. When sending a JavaScript HTTP request to a server, in this case a FastAPI backend, through a local HTML file that has been loaded into the browser via a file:/// URL—e.g., by dragging-d... | 3 | 3 |
77,982,766 | 2024-2-12 | https://stackoverflow.com/questions/77982766/delete-word-that-follows-a-specific-word | I have e-mails and transcripts in German from conversations with customers. They include personal identifiable information that I need to remove. So it is a data anonymisation task. The text would be "Hello Mr. Smith", "Dear Mr Smith", "Hello Lisa" etc. followed by the conversation. I need to keep the conversation for ... | Version 2a You could approach this by setting up lists of salutations and of honorifics (Mr, Mrs, Dr etc), and if any word in your data matched one of these working through the first few words you could remove it. This approach makes it easy to quickly add new salutations and honorifics as you spot them in the transcri... | 2 | 2 |
77,990,385 | 2024-2-13 | https://stackoverflow.com/questions/77990385/complex-c-lifetime-issue-in-python-bindings-between-c-and-numpy | I'm looking for advice on how to handle a complex lifetime issue between C++ and numpy / Python. Sorry for the wall of text, but I wanted to provide as much context as possible. I developed cvnp, a library that offers casts between bindings between cv::Mat and py::array objects, so that the memory is shared between the... | Well, the solution was inspired by cv_numpy.cpp in OpenCV source code, and was implemented thanks to the help of Dustin Spicuzza. It uses a custom MatAllocator that uses a numpy array as the data pointer, and will refer to this data instead of allocating. // Translated from cv2_numpy.cpp in OpenCV source code class Cv... | 2 | 0 |
77,989,093 | 2024-2-13 | https://stackoverflow.com/questions/77989093/isinstance-and-not-vs-for-checking-x | I want an if-statement to check if x is an empty tuple. Is there any significant advantage of writing the if-statement as if isinstance(x, tuple) and not x: vs if x == (): given the latter is shorter to write and simpler to read? | More often than not, you rely on object interfaces rather than specific types, so just if not x is sufficient and this is the usual Pythonic expression (see comments by @СергейКох and @MarkRansom). The advantage of the first case is that tuple subclasses will be accepted, which is usually what is expected in a duck-typ... | 2 | 3 |
77,953,389 | 2024-2-7 | https://stackoverflow.com/questions/77953389/problem-importing-dsplot-library-in-pycharm | I am exploring tree plots with the following library and code: from dsplot.graph import Graph graph = Graph( {0: [1, 4, 5], 1: [3, 4], 2: [1], 3: [2, 4], 4: [], 5: []}, directed=True ) graph.plot() When I run the code, I get the following error: from dsplot.graph import Graph ModuleNotFoundError: No module named 'dspl... | It looks like you have not installed pygraphviz. Install pygraphviz Try downloading it from their official website and make sure its added to your path by clicking "Add Graphviz to the System PATH for the current user". In your terminal, run dot -V and if it outputs your version of pygraphviz, you should be all set to ... | 6 | 4 |
77,987,278 | 2024-2-13 | https://stackoverflow.com/questions/77987278/feature-selection-using-backward-feature-selection-in-scikit-learn-and-pca | i have calculated the scores of all the columns in my DF,which has 312 columns and 650 rows, using PCA with following code: all_pca=PCA(random_state=4) all_pca.fit(tt) all_pca2=all_pca.transform(tt) plt.plot(np.cumsum(all_pca.explained_variance_ratio_) * 100) plt.xlabel('Number of components') plt.grid(which='both', li... | As you can see, 100 columns describe 95.2% of the variance in my Dataframe. The graph tells you that 100 PCA components capture 95% of the variance. These 100 components do not correspond to 100 individual features. Each PCA component is made by combining all features together, which gives you that one component. Whe... | 2 | 1 |
77,991,049 | 2024-2-13 | https://stackoverflow.com/questions/77991049/is-there-a-way-to-print-a-formatted-dictionary-to-a-python-log-file | I've got a logging handler setup that prints to stream and file. I'm working with a few dictionaries and modifying dictionaries. Is there a way to format a dictionary for the log file so that it shows up as one block rather than a line? I've gone through a bunch of simpler formatting attempts and read through How to in... | Not sure if it's exactly what you're looking for, but I leveraged the pprint module to pretty-print dictionaries storing configurations for various things in an app I'm working on. The helper function and usage is below: import pprint import logging # set up pretty printer pp = pprint.PrettyPrinter(indent=2, sort_dicts... | 2 | 2 |
77,990,896 | 2024-2-13 | https://stackoverflow.com/questions/77990896/importerror-dependencies-for-instructorembedding-not-found-while-it-is-install | I already installed InstructorEmbedding, but it keeps giving me the error, in jupyter notebook environment using Python 3.12 (I also tried in 3.11). Kernel restarting didn't help. import torch from langchain.embeddings import HuggingFaceInstructEmbeddings DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" embedd... | I think you would also need to install sentence-transformers. Try installing it via: pip install -U sentence-transformers==2.2.2 and then run your code. Please make sure you install the version 2.2.2 otherwise you'll end up with this error: TypeError: INSTRUCTOR._load_sbert_model() got an unexpected keyword argument '... | 2 | 9 |
77,988,322 | 2024-2-13 | https://stackoverflow.com/questions/77988322/setting-part-of-title-as-bold-and-normal-in-matplotlib | I want to create an axis title that has part of it in bold font. This is an example of my current code: # Features to plot features = ['Overall Rating', 'Shooting Rating', 'Creativity Rating', 'Passing Rating', 'Dribbling Rating', 'Defending Rating', 'Pressing Rating', 'Aerial Rating'] # Loop through each feature and c... | You can use LaTeX** to achieve this, quite easily using this kind of expression: $\\bf{bold text}$". In this case, the "bold text" will be displayed as bold. So in your case, add this: ax.set_title(f'{feature}\n$\\bf{{{int(player_value)}}}$', color='#100097', loc='right') **: about LaTeX, it seems MathText is what is ... | 4 | 3 |
77,986,775 | 2024-2-13 | https://stackoverflow.com/questions/77986775/pydantic-fastapi-how-to-set-up-a-case-insensitive-model-with-suggested-values | Using FastAPI I have set up a POST endpoint that takes a command, I want this command to be case insensitive, while still having suggested values (i.e. within the SwaggerUI docs) For this, I have set up an endpoint with a Command class as a schema for the POST body parameters: @router.post("/command", status_code=HTTPS... | Specify the type as either a literal or some string and keep the validation: class Command(BaseModel): action: Literal["jump", "walk", "sleep"] | str @field_validator('action') @classmethod def validate_command(cls, v: str) -> str: """ Checks if command is valid and converts it to lower. """ if v.lower() not in {'jump'... | 2 | 1 |
77,957,072 | 2024-2-7 | https://stackoverflow.com/questions/77957072/how-to-determine-final-state-of-sequential-entries-in-a-pandas-dataframe-using-v | I have a pandas DataFrame with columns representing various attributes of data entries, including a timestamp "dh_processamento_rubrica", a unique identifier "inivalid_iderubrica", and an operation type "operacao". The operations include "inclusao" (insertion), "alteracao" (modification), and "exclusao" (deletion). For... | This is indeed challenging, since the series of operations is important, which makes it hard to use vectorised operations. An extra challenge is that unique IDs are mutable. Luckily I think it is still possible to write a vectorised solution. The below solution relies on the fact that an alteracao operation that change... | 2 | 2 |
77,985,422 | 2024-2-13 | https://stackoverflow.com/questions/77985422/is-regex-in-python-different-with-regex-in-other-system-like-postgresql | I have this code to parsing street and house number in Python import re def parse_street(address): pattern = r'^(.*?)(?i)\b no\b' match = re.match(pattern, address) if match: return match.group(1).strip() else: return None def parse_housenumber(address): pattern = r'(?i)\bno\.?\s*([\dA-Z]+)' match = re.search(pattern, ... | Yes, most regex engines' syntax is different, to a lesser or greater degree. This is why the regex tag requires another tag specifying the engine, tool or a programming language to which the regex question pertains. From PostgreSQL docs (emphasis mine): An ARE can begin with embedded options: a sequence (?xyz) (where ... | 2 | 4 |
77,984,267 | 2024-2-12 | https://stackoverflow.com/questions/77984267/expanding-rows-in-pandas-dataframe-based-on-time-intervals-accounting-for-optio | I have a Pandas DataFrame representing timesheets with start and end times, as well as optional rest and meal break intervals. My goal is to expand a single row into multiple rows with correct intervals. It's worth noting that: A timesheet might not have any breaks. A timesheet might have only a rest break, only a mea... | Here is updated version that computes the category by checking the column names for "Start Time"/"End Time": rows = [] for index, row in df.iterrows(): id_value = row["Id"] start_time = pd.to_datetime(row["Start Time"]) end_time = pd.to_datetime(row["End Time"]) # Collect all times times = {(start_time, "Start Time"), ... | 3 | 1 |
77,974,285 | 2024-2-10 | https://stackoverflow.com/questions/77974285/allowing-a-specific-set-of-undefined-values-in-enums | Given an enum like this: class Result(IntEnum): A = 0 B = 1 C = 3 I'd like to be able to create new enum members dynamically, but only if the value is within a given range. For example, given: class Result(IntEnum, valid_range=(4, 10)): A = 0 B = 1 C = 3 I'd expect the following behaviour: Result(10) would be ok, re... | It is possible, but requires Python 3.9 or better, and does use one currently undocumented data structure (_value2member_map_): from enum import IntEnum class RangedEnum(IntEnum): def __repr__(self): if self._name_: return f"<{self.__class__.__name__}.{self._name_}: {self._value_}>" else: return f"<{self.__class__.__na... | 2 | 2 |
77,982,938 | 2024-2-12 | https://stackoverflow.com/questions/77982938/polars-idiomatic-way-of-aggregating-n-consecutive-rows-of-a-data-frame | I'm new to Polars, and I ended up writing this code to compute some aggregating expression over segments of n rows: import polars as pl df = pl.DataFrame({"a": [1, 1, 3, 8, 62, 535, 4213]}) ( df.with_columns(index=pl.int_range(pl.len(), dtype=pl.Int32)) .group_by_dynamic(index_column="index", every="3i") .agg(pl.col("a... | IMO your solution using group_by_dynamic already follows best practices when it comes to the aggregation. However, you can simplify the creation of the index column quite a bit using pl.DataFrame.with_row_index. As the result is unsigned (and group_by_dyanmic only allows for a signed integer index column), you'll need ... | 3 | 4 |
77,973,107 | 2024-2-10 | https://stackoverflow.com/questions/77973107/how-can-i-read-more-than-4096-bytes-from-stdin-copy-pasted-to-a-terminal-on-lin | I have this code: import sys binfile = "data.hex" print("Paste ascii encoded data.") line = sys.stdin.readline() b = bytes.fromhex(line) with open(binfile, "wb") as fp: fp.write(b) Problem is that never more than 4096 bytes are read in the sys.stdin.readline() call. How can I make that buffer larger? I tried to supply... | This truncate-long-lines-to-4096-bytes behavior is caused by the terminal (TTY) code in the Linux kernel. (Actually, as part of the truncation, the last byte of the 4096 bytes is also replaced with a newline byte.) By the time the (Python) process reads from the TTY as its stdin, the line has already been truncated. Th... | 2 | 4 |
77,982,303 | 2024-2-12 | https://stackoverflow.com/questions/77982303/select-all-integer-columns-except-a-few-in-python-polars | Consider I have a dataframe: import polars as pl import polars.selectors as cs df = pl.DataFrame( { 'p': [1, 2, 1, 3, 1, 2], 'x': list(range(6, 0, -1)), 'y': list(range(2, 8)), 'z': [3, 4, 5, 6, 7, None], "q" : list('abcdef') } ) df shape: (6, 5) p x y z q i64 i64 i64 i64 str 1 6 2 3 "a" 2 5 3 4 "b" 1 4 4 5 "c" 3 3 5 ... | You can use polars' column selectors to create a selector for all integers columns. Then, you can use pl.Expr.exclude to exclude column p and z from the selection. import polars.selectors as cs df.select(cs.integer().exclude("p", "z")) | 3 | 4 |
77,982,046 | 2024-2-12 | https://stackoverflow.com/questions/77982046/how-to-select-all-columns-from-a-list-in-a-polars-dataframe | I have a dataframe import polars as pl import numpy as np df = pl.DataFrame( { "nrs": [1, 2, 3, None, 5], "names": ["foo", "ham", "spam", "egg", None], "random": np.random.rand(5), "groups": ["A", "A", "B", "C", "B"], } ) I want to select only the columns in list: mylist = ['nrs', 'random'] This seems to work: import... | It's actually simpler than that: df.select(['nrs', 'random']) ┌──────┬──────────┐ │ nrs ┆ random │ │ --- ┆ --- │ │ i64 ┆ f64 │ ╞══════╪══════════╡ │ 1 ┆ 0.662732 │ │ 2 ┆ 0.437345 │ │ 3 ┆ 0.43857 │ │ null ┆ 0.701177 │ │ 5 ┆ 0.390494 │ └──────┴──────────┘ selectors are in general for more complicated selections - like a... | 5 | 4 |
77,980,972 | 2024-2-12 | https://stackoverflow.com/questions/77980972/merge-groups-of-columns-in-a-polars-dataframe-to-single-columns | I have a polars dataframe with columns a_0, a_1, a_2, b_0, b_1, b_2. I want to convert it to a longer and thinner dataframe (3 x rows, but just 2 columns a and b), so that a contains a_0[0], a_1[0], a_2[0], a_0[1], a_1[1], a_2[1],... and the same for b. How can I do that? | You can use concat_list() to join the columns you want together and then use explode() to convert them into rows. Let's take simple data frame as an example: df = pl.DataFrame( data=[[x for x in range(6)]], schema=[f"a_{i}" for i in range(3)] + [f"b_{i}" for i in range(3)] ) ┌─────┬─────┬─────┬─────┬─────┬─────┐ │ a_0 ... | 6 | 2 |
77,978,595 | 2024-2-11 | https://stackoverflow.com/questions/77978595/tkinter-and-animation-funcanimation-accumulating-delay-and-freeze-gui | I am working on a Tkinter project where I am plotting live data from different sensors. I am using Tkinter to create the GUI and matplotlib animation.FuncAnimation to create live plots that update every given time (i.e. 1 second). The code is written in python 3. This work fine as long as the total number of point is s... | Most of the examples matplotlib animation suggests creating the plot axes during intialization of animation instead of creating inside animate function, as your above part of code shows. So a possible way can be create scatter object and hold it in a variable which is intialized once. it actually returns matplotlib col... | 2 | 1 |
77,965,487 | 2024-2-9 | https://stackoverflow.com/questions/77965487/error-when-using-lid-usage-from-the-swmm-api-package-in-python | I am trying to extract individual LID settings for each subcatchment in SWMM using LID_USAGE from the swmm_api package. I have followed the example at https://markuspichler.gitlab.io/swmm_api/examples/how_to_add_LIDs.html, however, an error occurs. I wonder how to fix the code? I have attached the swmm model for your r... | This message from the error says what the issue is: TypeError: __init__() takes from 8 to 12 positional arguments but 17 were given You are providing information that the program does not know how to parse, because it is only designed for 8-12 parameters. Why are you inputting 5 extra parameters- what are they for? Yo... | 2 | 1 |
77,978,208 | 2024-2-11 | https://stackoverflow.com/questions/77978208/how-to-count-rows-above-the-current-one-based-on-conditions-in-polars | Let's have a polars df: df = pl.DataFrame( { 'date': ['2022-01-01', '2022-01-02', '2022-01-07', '2022-01-17', '2022-03-02', '2022-06-05', '2022-06-07', '2022-07-02'], 'col1': [4, 4, 2, 2, 2, 3, 2, 1], 'col2': [1, 2, 3, 4, 1, 3, 3, 4], 'col3': [2, 3, 4, 4, 3, 2, 2, 1] } ) date col1 col2 col3 2022-01-01 1 1 2 2... | You can also use a struct to put all the conditional logic inside .cumulative_eval() cols = "col1", "col2", "col3" df.with_columns(ge = pl.struct(cols).cumulative_eval( pl.all_horizontal( pl.element().struct[col] >= pl.element().struct[col].last() for col in cols ) .sum() - 1 # subtract 1 as we compare each row against... | 6 | 3 |
77,978,201 | 2024-2-11 | https://stackoverflow.com/questions/77978201/how-to-let-a-discord-bot-run-a-slash-command-created-by-itself | I am currently searching for a solution to my problem: I want to know if it is possible to let a Discord bot run a slash command which was created by the same Discord bot. This is my current code of the bot: import discord from discord import app_commands class aclient(discord.Client): def __init__(self): super().__ini... | I want to know if it is possible to let a Discord Bot run a Slash Command which was created by the same Discord Bot. No. Regardless of who’s command it is, bots cannot execute them. Application commands (slash commands) are user initiated hence you not being able to find any documentation on it. If you’re looking to ... | 2 | 2 |
77,978,204 | 2024-2-11 | https://stackoverflow.com/questions/77978204/speeding-up-a-rolling-sum-calculation | I'm doing some work with a fairly large amount of (horse racing!) data for a project, calculating rolling sums of values for various different combinations of data - thus I need to streamline it as much as possible. Essentially I am: calculating the rolling calculation of a points field over time calculating this for ... | Here is a little faster way: df.merge(df.set_index('RaceDate') .groupby(['Horse', 'Trainer'])['Points'] .rolling('180D') .mean() .rename('HorseRaceCount90d_1'), right_index=True, left_on=['Horse', 'Trainer', 'RaceDate']) Your way: 18.5 s ± 727 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) This way: 1.18 s ±... | 3 | 4 |
77,976,619 | 2024-2-11 | https://stackoverflow.com/questions/77976619/window-must-be-an-integer-0-or-greater-issue-with-30d-style-rolling-calculat | I've had a look and can't seem to find a solution to this issue. I'm wanting to calculate the rolling sum of the previous 30 days' worth of data at each date in the dataframe - by subgroup - for a set of data that isn't daily - it's spaced fairly irregularly. I've been attempting to use ChatGPT which is getting in a tw... | The issue if that you need to specify which column to use as Date but don't have access to the Date with groupby.transform. You could use groupby.apply: # Calculate cumulative sum by group within the previous 30 days from each day df['RollingSum_Last30Days'] = (df.groupby('Group', group_keys=False) .apply(lambda x: x.r... | 2 | 1 |
77,975,111 | 2024-2-10 | https://stackoverflow.com/questions/77975111/retrieve-aws-secrets-using-boto3 | I want to retrieve AWS secrets using python boto3 and I came across this sample code: aws-doc-sdk-examples/python/example_code/secretsmanager/get_secret_value.py at main · awsdocs/aws-doc-sdk-examples · GitHub Secrets Manager examples using SDK for Python (Boto3) - AWS SDK Code Examples But it is confusing. I don't s... | Per the documentation, each of the example folders has one or more main runner scripts. For the Secrets Manager examples, you would run either: python scenario_get_secret.py, or python scenario_get_batch_secrets.py Each of these 'runner' scripts imports the relevant Python code e.g. get_secret_value.py. The code is s... | 5 | 3 |
77,973,200 | 2024-2-10 | https://stackoverflow.com/questions/77973200/fixing-the-way-how-to-sort-element-in-a-list-using-python-sorted-method | I have this list containing the following images with these the name structure "number.image" The list stores the elements of a local folder based on a path. [1.image, 2.image, 3.image, 4.image, 5.image, 6.image, 7.image, 8.image, 9.image, 10.image, 11.image, 12.image, 13.image] applying the python build-in sorted()... | If you want to use the inbuilt sorted function and not install a third-party library such as natsort, you can use a lambda for the key argument that interprets the stem of the file as an integer: >>> from pathlib import Path >>> filenames = [ ... '1.image', ... '10.image', ... '11.image', ... '12.image', ... '13.image'... | 2 | 1 |
77,974,379 | 2024-2-10 | https://stackoverflow.com/questions/77974379/how-to-find-max-value-in-list-datatype-column-in-polars-dataframe | I am using a Polar data frame for the first time. I am trying to match input values with data in the Postgres table. Sharing some sample code which is part of the actual code. I have a column called "Score" of type list[i32]. As a next step, I am trying to find the maximum value in that list. I am getting errors. impor... | you can use list.max() function. Simple example: df = pl.DataFrame( { "a": [[1, 8, 3],[6,2,7],[8,10,11]], "b": [4, 5, None], } ) ┌─────────────┬──────┐ │ a ┆ b │ │ --- ┆ --- │ │ list[i64] ┆ i64 │ ╞═════════════╪══════╡ │ [1, 8, 3] ┆ 4 │ │ [6, 2, 7] ┆ 5 │ │ [8, 10, 11] ┆ null │ └─────────────┴──────┘ df.with_columns( pl... | 2 | 2 |
77,973,237 | 2024-2-10 | https://stackoverflow.com/questions/77973237/deleting-disabled-when-saving-changes-in-formset | I'm creating a table with a formset from a queryset of existing objects. Few fields in the table should change, and other fields should be displayed, but not changed. For displaying non-editable fields, I use the widget with 'disabled' in the form. GET request does everything right. But the POST request does not save c... | Setting disabled will only render the field non-editable, so people can still forge a POST request that would alter the field. You should set the field to .disabled = True, this will not only skip the fields, but also prevent people from forging a POST request that somehow would change these fields, like: class OrderCl... | 2 | 2 |
77,972,662 | 2024-2-10 | https://stackoverflow.com/questions/77972662/different-results-in-chi-square-test | I am trying to calculate the Chi-Square result for a simply data table I have two groups, let's call them PG and KG. PG has in category 1 19 values and in category 2 11 values. KG has in category 1 0 values and in category 2 30 values. The python code would be from scipy.stats import chi2_contingency observed = [[0, 30... | There's parameter correction=, which is in default mode set to True: correction bool, optional If True, and the degrees of freedom is 1, apply Yates’ correction for continuity. The effect of the correction is to adjust each observed value by 0.5 towards the corresponding expected value. from scipy.stats import chi2_c... | 3 | 2 |
77,968,626 | 2024-2-9 | https://stackoverflow.com/questions/77968626/dynamic-optimization-in-gekko | I need to optimize this function in gekko and something is wrong. Black function(x2) is how teoretical it should look like. m = GEKKO() m.options.IMODE = 6 m.time = np.linspace(0, 1, 100) x = m.Var(lb=1, ub=3) x2 = m.Var(lb=1, ub=3) J = m.Var(0) t = m.Param(value=m.time) m.Equation(J.dt() == 24*x*t + 2*x.dt()**2 -4*t)... | Here is a solution to the problem that aligns with the known solution: from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt m = GEKKO(remote=True) n = 101 m.time = np.linspace(0,1,n) x = m.Var(1,lb=1,ub=3) t = m.Param(value=m.time) p = np.zeros(n); p[-1]=1 final = m.Param(p) m.Equation(final*(x-3... | 2 | 1 |
77,971,552 | 2024-2-10 | https://stackoverflow.com/questions/77971552/how-to-write-a-python-function-that-splits-and-selects-first-element-in-each-pan | I have a dataframe df with double entries separated by a , in some columns. I want to write a function to extract only the entry before the , for columns with double entries. Example: 20.15,20.15 split to 20.15 See the dataframe import pandas as pd # initialize data of lists. data = {'Name': ['Tom', 'nick', 'krish', 'j... | You can create the DataFrame and then edit the columns that have a comma. Note that this will only work if you're sure only the columns with duplicated data have commas in their values. # Create DataFrame df = pd.DataFrame(data) for col in df.columns: if df[col].dtype == "object": df[col] = df[col].astype(str).str.spli... | 2 | 3 |
77,970,330 | 2024-2-9 | https://stackoverflow.com/questions/77970330/in-multilevel-columns-pandas-dataframe-reorder-the-specific-lower-level-of-cate | I got a multilevel dataframe with the multivel columns, df.columns is ultiIndex([( 'county', ''), ( 'month', ''), ( 'Gender', 'Declined to self-identify'), ( 'Gender', 'Female'), ( 'Gender', 'Male'), ( 'Gender', 'Non-Binary / Gender expansive'), ( 'age', '0-4'), ( 'age', '11-13'), ( 'age', '15-18'), ( 'age', '19-24'), ... | Example Code let's make sample input import pandas as pd import numpy as np a = [('county', ''), ('month', ''), ('Gender', 'Declined to self-identify'), ('Gender', 'Female'), ('Gender', 'Male'), ('Gender', 'Non-Binary / Gender expansive'), ('age', '0-4'), ('age', '11-13'), ('age', '15-18'), ('age', '19-24'), ('age', '2... | 2 | 2 |
77,969,654 | 2024-2-9 | https://stackoverflow.com/questions/77969654/error-while-finding-similarity-between-polars-dataframe-column-and-string-variab | I need to find a similarity between the column in the polar data frame and the input value.I am using jaro_winkler_metric . I am getting errors while doing it. We don't want to use UDF functions as it slows the process. import polars as pl import jaro def test_polars(): name='savah' data = {"first_name": ['sarah', 'pur... | The error lies within this snippet: jaro.jaro_winkler_metric(pl.col("first_name"), name) You pass a polars expression to jaro_winkler_metric and I doubt the function such inputs, but expects a string instead. Instead you could try using: df = ( df .with_columns( pl.col("first_name").map_elements(lambda first_name: jar... | 2 | 2 |
77,969,653 | 2024-2-9 | https://stackoverflow.com/questions/77969653/python-docx-twips-object-is-not-callable | I have a simple script to generate a document using python docx. I can generate the document fine, but when I try to change anythig related to the document sections I get the error: ERROR - Error while processing: 'Twips' object is not callable from docx import Document from docx.shared import Inches from docx.secti... | Seems it's not correct usage: section.page_width(Inches(5)) section.page_height(Inches(5)) Instead try: section.page_width = Inches(5) section.page_height = Inches(5) | 2 | 2 |
77,969,526 | 2024-2-9 | https://stackoverflow.com/questions/77969526/optional-parameters-fastapi | please help me. In the function I set the optional parameter param as a boolean value, but the docs (swagger) do not display the data type for param. How to fix it? I'm using python 3.12.1 from fastapi import FastAPI from datetime import date app=FastAPI() @app.get ("/sales") def sales( date_from: date, date_to: date, ... | set the optional parameter "param" as a boolean value, but the docs do not display the data type Well, it's not a bool, is it? You decided to make it a bool | None instead. (Sometimes pronounced Optional[bool], same thing.) Let's fix that: param: bool = False, | 2 | 2 |
77,968,612 | 2024-2-9 | https://stackoverflow.com/questions/77968612/polars-smart-way-to-avoid-window-expression-not-allowed-in-aggregation | I have the following code which works. import numpy as np import polars as pl data = { "date": ["2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-05", "2021-01-06", "2021-01-07", "2021-01-08", "2021-01-09", "2021-01-10", "2021-01-11", "2021-01-12", "2021-01-13", "2021-01-14", "2021-01-15", "2021-01-16", ... | over() applies to the whole expression, so your code actually works if you remove over on MA_G / MA_L columns: # Calculate Returns R = pl.col("close").pct_change().over("company") # Calculate Gains and Losses G = pl.when(R > 0).then(R).otherwise(0).alias("gain") L = pl.when(R < 0).then(R).otherwise(0).alias("loss") # C... | 2 | 1 |
77,968,009 | 2024-2-9 | https://stackoverflow.com/questions/77968009/how-to-add-spine-arrows-and-offset-the-spine | I can do either one of these separately, but not together. I think the question comes down to: after offsetting spines in a Matplotlib figure, how does one find the spine bounds in a coordinate system that can be used to plot arrowheads on the ends of the spines? The arrows are (obviously) not aligned with the spines.... | In set_position(('outward', spine_offset)) the offset is measured in points (1/72 of an inch, similar to how fonts are measured, e.g. a 12 point font). using a distance in "axes coordinates" Instead of 'outward', you can also use 'axes' coordinates: 0 at the bottom (left), 1 at the top (right). As usually the plot isn'... | 2 | 3 |
77,967,334 | 2024-2-9 | https://stackoverflow.com/questions/77967334/getting-min-max-column-name-in-polars | In polars I can get the horizontal max (maximum value of a set of columns for reach row) like this: df = pl.DataFrame( { "a": [1, 8, 3], "b": [4, 5, None], } ) df.with_columns(max = pl.max_horizontal("a", "b")) ┌─────┬──────┬─────┐ │ a ┆ b ┆ max │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪══════╪═════╡ │ 1 ┆ 4 ┆ 4... | You can concatenate the elements into a list using pl.concat_list, get the index of the largest element using pl.Expr.list.arg_max, and replace the index with the column name using pl.Expr.replace. mapping = {0: "a", 1: "b"} ( df .with_columns( pl.concat_list(["a", "b"]).list.arg_max().replace(mapping).alias("max_col")... | 6 | 3 |
77,967,238 | 2024-2-9 | https://stackoverflow.com/questions/77967238/syntax-warning-for-escaped-period-in-triple-quoted-shell-rule | I get the following warning: SyntaxWarning: invalid escape sequence '\.' when the following shell block is present in a rule: """ curl {params.ua} -L {params.url} \ | gzip -dc \ | sd '^.*gene_id "([A-Z0-9\.]+).*"; transcript_id "([A-Z0-9\.]+)".*;.*' '$2\t$1' \ | uniq | gzip > {output} """ The warning gives me a line... | It's possible to specify that this is a raw string: r""" ... \. ... """ | 2 | 1 |
77,965,251 | 2024-2-8 | https://stackoverflow.com/questions/77965251/passing-a-numpy-array-to-c-function-through-ctypes-gives-wrong-results-if-the-nu | Consider this simple C source code which computes the mean of an array of int, stores it in a structure and returns an error code: #include <stdio.h> enum errors { NO_ERRORS, EMPTY_ARRAY }; struct Result { double mean; }; enum errors calculateMean(struct Result *result, int *array, int length) { if (length == 0) { retu... | According to [NumPy]: Scalars - class numpy.int_ (emphasis is mine): Signed integer type, compatible with Python int and C long. So, you'll have to use that in all the places (and be consistent), otherwise you'll get Undefined Behavior. In your case (Little Endian Nix OS (and Python build)), the memory layout is (rep... | 2 | 1 |
77,965,769 | 2024-2-9 | https://stackoverflow.com/questions/77965769/remove-top-and-right-spine-in-geoaxessubplot | I'm trying to remove the top and right spine of a plot, and initially tried # Create a figure and axis with PlateCarree projection fig, ax = plt.subplots(figsize=(11, 6), subplot_kw={'projection': ccrs.PlateCarree()}) ax.coastlines() # Reintroduce spines ax.spines['top'].set_visible(True) ax.spines['right'].set_visible... | I think the modern equivalent of outline_patch is spines['geo']: # Create a figure and axis with PlateCarree projection fig, ax = plt.subplots(figsize=(11, 6), subplot_kw={'projection': ccrs.PlateCarree()}) ax.coastlines() ax.spines['geo'].set_visible(False) ax.spines['left'].set_visible(True) ax.spines['bottom'].set_v... | 2 | 2 |
77,966,444 | 2024-2-9 | https://stackoverflow.com/questions/77966444/how-to-use-python-pattern-matching-to-match-class-types | How can we use Python's structural pattern matching (introduced in 3.10) to match the type of a variable without invoking the constructor / in a case where a new instantiation of the class is not easily possible? The following code fails: from pydantic import BaseModel # instantiation requires 'name' to be defined clas... | To expand on what I said in comments: match introduces a value, but case introduces a pattern to match against. It is not an expression that is evaluated. In case the pattern represents a class, the stuff in the parentheses is not passed to a constructor, but is matched against attributes of the match value. Here is an... | 3 | 4 |
77,965,457 | 2024-2-9 | https://stackoverflow.com/questions/77965457/taking-specific-value-from-the-csv-file-using-pandas-dataframe | Let's say I want a last specific value from the CSV file. THis is my code. When I run this code, it gives me the value saying "2 Ana" What can I do here to just get the value 'Ana'? import pandas as pd import csv CSV_file = pd.read_csv('appl.csv') name = CSV_file['Name'] v_val = name.iloc[-1:] print(v_val) THe CSV fil... | Remove the : from the .iloc: name = CSV_file["Name"].iloc[-1] print(name) Prints: Ana Or use .iat: name = CSV_file["Name"].iat[-1] | 2 | 3 |
77,965,378 | 2024-2-8 | https://stackoverflow.com/questions/77965378/is-there-a-way-to-delete-several-items-at-once-in-a-dictionary | I'm working with Python 3.11. I have a dictionary whose keys are datetime objects and whose values are strings. dates = {datetime.datetime(2022, 1, 1): "a", datetime.datetime(2022, 5, 4): "b", datetime.datetime(2022, 9, 25): "c", datetime.datetime(2023, 5, 17): "d", datetime.datetime(2023, 12, 15): "e", datetime.dateti... | You could form a new Dictionary using a comprehension; order does not matter: dates2 = {k:v for k, v in dates.items() if k > now} which gives {datetime.datetime(2024, 3, 17, 0, 0): 'f', datetime.datetime(2024, 4, 3, 0, 0): 'g'} | 2 | 3 |
77,958,391 | 2024-2-7 | https://stackoverflow.com/questions/77958391/max-element-in-specific-structure | I have array of length n, from which I build such sequence b that: b[0] = 0 b[1] = b[0] + a[0] b[2] = b[1] + a[0] b[3] = b[2] + a[1] b[4] = b[3] + a[0] b[5] = b[4] + a[1] b[6] = b[5] + a[2] b[7] = b[6] + a[0] b[8] = b[7] + a[1] b[9] = b[8] + a[2] b[10] = b[9] + a[3] #etc. a can contain non-positive values. I need to f... | O(n) time and O(1) space. Consider this (outer loop) round: b[4] = b[3] + a[0] = b[3] + a[0] b[5] = b[4] + a[1] = b[3] + a[0] + a[1] b[6] = b[5] + a[2] = b[3] + a[0] + a[1] + a[2] You don't need all of these. It's enough to know: The maximum of them. Which is b[3] + max(prefix sums of a[:3]). The last of them, b[6] =... | 4 | 8 |
77,964,570 | 2024-2-8 | https://stackoverflow.com/questions/77964570/random-random-vs-numpy-random | I read here the following: "The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator." However, the first link for a Python module "random" has a URL that points to Numpy's random.random documentation, not to some general Python... | Is this link wrong? Yes. In context, I think they mean this random. There are three pieces of evidence for this. It says it's in the stdlib, and NumPy is not in the stdlib. It is an optional library for Python. It's talking about a module, and np.random.random() is not a module - it's a function inside a module. L... | 2 | 5 |
77,962,295 | 2024-2-8 | https://stackoverflow.com/questions/77962295/issue-with-memoization-in-recursive-function-for-finding-combinations-summing-to | I need to write the following function: Write a function that takes in a target (int) and a list of ints. The function should return a list of any combination of elements that add up to the target, if there is no combination that adds up to target return None. This is my initial solution using recursion: def how_sum(... | There are two issues I see with this code. First your claim about the correct solution to this input: print(how_sum(8, [2, 3, 5])) # None seems incorrect. Given the explanation, either [3, 5] or [2, 2, 2, 2] are valid answers. Similarly for: print(how_sum(7, [5, 3, 4, 7])) # [4, 3] where [7] is also a valid result. ... | 2 | 2 |
77,962,687 | 2024-2-8 | https://stackoverflow.com/questions/77962687/integration-in-python-midpoint-calculation | I came across this integral approximation function in a book. It seems efficient and provides accurate results with fewer subintervals ((n)). def approximate_integral(a, b, n, f): delta_x = (b - a) / n total_sum = 0 for i in range(1, n + 1): midpoint = 0.5 * (2 * a + delta_x * (2 * i - 1)) total_sum += f(midpoint) retu... | I found that the midpoint in my function accounted for an extra interval. After I reduced the ith iteration by 1, it worked as the formula in the book. midpoint = a + (dx/2) + ((i-1) * dx) | 2 | 1 |
77,961,619 | 2024-2-8 | https://stackoverflow.com/questions/77961619/why-does-resnet101-have-less-accuracy-than-resnet50-in-classification-of-sport-c | I trained two different type of ResNet model from torchvision.models which is ResNet50 with DEFAULT weight and ResNet101 with DEFAULT weight too but the results of training is really weird, the train accuracy and test accuracy of ResNet50 model is 89 and 85 respectively and for ResNet101 is 34, 28 ! what is wrong? I fr... | shouldn't this be better? because has more layers(depth) More layers means the model is more complex and has more capacity, but that doesn't mean it will perform better. Deeper models can struggle to converge, resulting in both a lower train and validation score compared to a simpler one. I think this is what's happe... | 2 | 6 |
77,955,224 | 2024-2-7 | https://stackoverflow.com/questions/77955224/winerror-193-1-is-not-a-valid-win32-application-az-bicep | When I try to run az bicep version I'm getting this error The command failed with an unexpected error. Here is the traceback: [WinError 193] %1 is not a valid Win32 application Traceback (most recent call last): File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\knack/cli.py", line 233, in invok... | The most likely cause of your error is that the bicep executable installed by Azure CLI is corrupted. See Issue #2364 on their repository. As described in this comment you can clean up the %USERPROFILE\.azure\bin directory and run az bicep install to get it working. | 2 | 5 |
77,959,301 | 2024-2-8 | https://stackoverflow.com/questions/77959301/how-can-i-move-a-button-before-a-box-that-the-button-uses-or-changes-in-gradio | Example: I have the following Gradio UI: import gradio as gr def dummy(a): return 'hello', {'hell': 'o'} with gr.Blocks() as demo: txt = gr.Textbox(value="test", label="Query", lines=1) answer = gr.Textbox(value="", label="Answer") answerjson = gr.JSON() btn = gr.Button(value="Submit") btn.click(dummy, inputs=[txt], ou... | You can add the components of clear button after initialization. This way, you are able to decouple the component creation order: import gradio as gr def dummy(a): return "hello", {"hell": "o"} with gr.Blocks() as demo: txt = gr.Textbox(value="test", label="Query", lines=1) answer = gr.Textbox(value="", label="Answer")... | 2 | 1 |
77,958,666 | 2024-2-8 | https://stackoverflow.com/questions/77958666/how-to-achieve-polars-previous-pivot-functionality-pre-0-20-7 | Previous to Polars version 0.20.7, the pivot() method, if given multiple values for the columns argument, would apply the aggregation logic against each column in columns individually based on the index column, rather than against a collective set of columns. Before: df = pl.DataFrame( { "foo": ["one", "one", "two", "t... | I see a couple of ways you could do it: First, you can use melt() for your DataFrame first and then pivot: df.melt(["foo", "baz"]) ─────┬─────┬──────────┬───────┐ │ foo ┆ baz ┆ variable ┆ value │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ str ┆ str │ ╞═════╪═════╪══════════╪═══════╡ │ one ┆ 1 ┆ bar ┆ y │ │ one ┆ 2 ┆ bar ┆... | 3 | 4 |
77,958,924 | 2024-2-8 | https://stackoverflow.com/questions/77958924/ckeditor-update-notification | Want to remove "This CKEditor 4.22.1 version is not secure. Consider upgrading to the latest one, 4.24.0-lts." from appearing in my Django admin's RichTextUploadingField. Currently using Django CKEditor 6.7.0m all settings are in settings.py only. Configs: CKEDITOR_CONFIGS = { "default": { "skin": "moono", "toolbar": "... | apparently the check of the version of the editor is a new configuration option, described here Class Config (CKEDITOR.config) | CKEditor 4 API docs 2 . It was added in CKEditor version 4.22.0; XWiki upgraded to CKEditor 4.22.1 in this ticket Loading... 4 . From what I tested and from what I understand from the ckedito... | 2 | 4 |
77,959,276 | 2024-2-8 | https://stackoverflow.com/questions/77959276/python-requests-get-gives-response-in-different-encoding | Following codes gives different results each time, sometimes in correct human readable ASCII, but other times in some other non-ASCII encoding format. HEADERS = ({'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36', 'Accept-Language': 'en... | The page.headers dictionary contains 'Content-Encoding': 'br'. This indicates Brotli compression and is not supported by default from requests (as of version 2.31.0 anyway). Per the requests documentation: When either the brotli or brotlicffi package is installed, requests also decodes Brotli-encoded responses. # Not... | 2 | 1 |
77,957,242 | 2024-2-7 | https://stackoverflow.com/questions/77957242/how-to-arbitrarily-sort-the-radial-plot-values-in-altair | I'm building a radial chart in python but can't order the values of the plot based on the 'categoria' values. I already tried to sort the df and force through domain and sort in the altair code but can't get the desired result. What I'm doing wrong? Here's a sample of my current dataframe: index da_tipo_servicio_sa... | Try using the order encoding and set order='categoria'. | 2 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.