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 |
|---|---|---|---|---|---|---|
77,899,043 | 2024-1-29 | https://stackoverflow.com/questions/77899043/how-to-catch-dateparseerror-in-pandas | I am running a script that uses pd.to_datetime() on inputs that are sometime not able to be parsed. For example if I try to run pd.to_datetime('yesterday') it results to an error DateParseError: Unknown datetime string format, unable to parse: yesterday, at position 0 I 'd like to catch this exception and process it fu... | You can import it from pandas._libs.tslibs.parsing: from pandas._libs.tslibs.parsing import DateParseError try: pd.to_datetime('yesterday') except DateParseError: print('exception caught') | 5 | 6 |
77,897,621 | 2024-1-29 | https://stackoverflow.com/questions/77897621/map-each-row-into-a-list-and-collect-all | I have a dataframe: df = pl.DataFrame( { "t_left": [0.0, 1.0, 2.0, 3.0], "t_right": [1.0, 2.0, 3.0, 4.0], "counts": [1, 2, 3, 4], } ) And I want to map each row into a list, and then collect all values (to be passed into e.g. matplotlib.hist) I can do it by hand like: times = [] for t_left, t_right, counts in df.rows(... | As you need the final result as one big list, you don't really need to work with lists, you can just explode() your dataframe into multiple rows so then you can run vectorized operations on it: so, taking your example data: df = pl.DataFrame( { "t_left": [0.0, 1.0, 2.0, 3.0], "t_right": [1.0, 2.0, 3.0, 4.0], "counts": ... | 3 | 5 |
77,898,544 | 2024-1-29 | https://stackoverflow.com/questions/77898544/how-to-keep-substring-until-character-is-found-in-polars-dataframe | I am working with a Polars DataFrame that contains a column with values like this: shape: (3, 2) ┌──────────────┬──────────────┐ │ A │ B │ │ --- │ --- │ │ str │ str │ ├──────────────┼──────────────┤ │ A|B:0d:cs │ C:2ew2 │ ├──────────────┼──────────────┤ │ A:1ds0 │ E|F:91we23 │ ├──────────────┼──────────────┤ │ QW|P:3dw... | you can use str.split() and list.first(): df.select(pl.all().str.split(':').list.first()) ┌─────────┬───────┐ │ integer ┆ float │ │ --- ┆ --- │ │ str ┆ str │ ╞═════════╪═══════╡ │ A|B ┆ C │ │ A ┆ E|F │ │ QW|P ┆ A|Z │ └─────────┴───────┘ | 2 | 1 |
77,885,145 | 2024-1-26 | https://stackoverflow.com/questions/77885145/how-can-i-suppress-ruff-linting-on-a-block-of-code | I would like to disable/suppress the ruff linter (or certain linting rules) on a block of code. I know that I can do this for single lines (by using # noqa: <rule_code> at the end of the line) or for entire files/folder (#ruff: noqa <rule_code> at the top of the file). However, I would like to disable the linter ruff o... | Not currently possible (as of 29 Jan 2024). See here for updates on the issue | 11 | 8 |
77,895,517 | 2024-1-28 | https://stackoverflow.com/questions/77895517/how-to-url-encode-special-character-in-python | I am trying to do an url encoding on the following string the following string 'https://bla/ble:bli~' using the urllib standard library on Python 3.10. Problem is that the ~ character is not encoded to %7E as per url encoding. Is there a way around it? I have tried from urllib.parse import quote input_string = 'https:/... | '~' character is not required to be encoded. (Though its encoded formate is %7E). The tilde is one of the allowed characters in url. So you can use any of the followings: from urllib.parse import quote input_string = 'https://bla/ble:bli~' url_encoded = quote(input_string) or you can use request module as well import ... | 2 | 5 |
77,895,351 | 2024-1-28 | https://stackoverflow.com/questions/77895351/how-can-i-fix-the-metaclass-conflict-in-django-rest-framework-serializer | I've written the following code in django and DRF: class ServiceModelMetaClass(serializers.SerializerMetaclass, type): SERVICE_MODELS = { "email": EmailSubscriber, "push": PushSubscriber } def __call__(cls, *args, **kwargs): service = kwargs.get("data", {}).get("service") cls.Meta.subscriber_model = cls.SERVICE_MODELS.... | The problem is not the metaclass, or at least it is not the primary problem. The main problem is the many=True for your IntegerField. I looked it up, and apparently a field can not have many=True, only a Serializer can. Indeed, if we inspect the source code, we see [GitHub]: def __new__(cls, *args, **kwargs): # We ove... | 2 | 2 |
77,895,186 | 2024-1-28 | https://stackoverflow.com/questions/77895186/re-split-on-an-empty-string | I'm curious about the result of this Python code that does a split on an empty string '': import re x = re.split(r'\W*', '') y = re.split(r'(\W*)', '') Since the string is an empty string, I expect the result for x = re.split(r'\W*', '') is an empty list and that for y = re.split(r'(\W*)', '') is ['']. The actual resu... | Note that the regular expression \W* can match an empty string. Thus, while it's not useful, it's true that the empty string can be split in half to produce an empty string: '' = '' + '' + '' The '' that precedes the regular expression The '' that matches the regular expression The '' that follows the regular express... | 2 | 4 |
77,889,718 | 2024-1-27 | https://stackoverflow.com/questions/77889718/rolling-window-of-next-rows-in-polars | I want to create a new column that contains the max, min and average of the next X elements. After searching for a while the only solution I was able to find was: df = df.with_columns( pl.col("price").shift(-20).rolling_max(window_size=20).alias('max'), pl.col("price").shift(-20).rolling_min(window_size=20).alias('min'... | @RomanPekar's solution works well for the creation of few columns. However, when working with multiple columns it could be preferable to use a full forward-looking rolling context using pl.DataFrame.group_by_dynamic as follows. Data. df = pl.DataFrame({ "price": [1, 2, 6, 1, 3, 5, 8, 7], }) Usage of pl.DataFrame.group... | 4 | 2 |
77,893,484 | 2024-1-28 | https://stackoverflow.com/questions/77893484/italicizing-letters-and-numbers-in-matplotlib | I am attempting to italicize text in my plot: import matplotlib.pyplot as plt plt.plot([1,2,3],[1,1,1], label = '$\it{ABC123}$') plt.legend() plt.show() as shown by Styling part of label in legend in matplotlib but this only italicized ABC, not 123, which was also noticed, but left unsolved, by Matplotlib italic font ... | You can use the font_manager: import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager font = font_manager.FontProperties(style='italic') plt.plot([1,2,3],[1,1,1], label = 'ABC123') plt.legend(prop=font) plt.show() To use it for x/y ticks or labels, you must use the fontproperties argument: plt.... | 2 | 3 |
77,888,435 | 2024-1-26 | https://stackoverflow.com/questions/77888435/python-method-overriding-more-specific-arguments-in-derived-than-base-class | Let's say I want to create an abstract base class called Document. I want the type checker to guarantee that all its subclasses implement a class method called from_paragraphs, which constructs a document from a sequence of Paragraph objects. However, a LegalDocument should only be constructable from LegalParagraph obj... | Turns out this can be solved using generics: from abc import ABC, abstractmethod from typing import Generic, Sequence, TypeVar ParagraphType = TypeVar("ParagraphType", bound="Paragraph") class Document(ABC, Generic[ParagraphType]): @classmethod @abstractmethod def from_paragraphs(cls, paragraphs: Sequence[ParagraphType... | 7 | 1 |
77,892,148 | 2024-1-27 | https://stackoverflow.com/questions/77892148/python-concurrent-futures-wait-job-submission-order-not-preserved | Does python's concurrent.futures.wait() preserve the order of job submission? I submitted two jobs to ThreadPoolExecutor as follows: import concurrent.futures import time, random def mult(n): time.sleep(random.randrange(1,5)) return f"mult: {n * 2}" def divide(n): time.sleep(random.randrange(1,5)) return f"divide: {n /... | According to the doc that the function wait(): Returns a named 2-tuple of sets. By definition, sets are unordered. That means you cannot guarantee the order. Since you already have mult_future and divide_future, you can use them to guarantee the order. There is no need to call wait either. import concurrent.futures i... | 2 | 2 |
77,891,453 | 2024-1-27 | https://stackoverflow.com/questions/77891453/regex-string-parsing-pattern-starts-with-but-can-end-with | I am attempting to parse strings using Regex. The strings look like: Stack;O&verflow;i%s;the;best! I want to parse it to: Stack&verflow%sbest! So when we see a ; remove everything up until we see one of the following characters: [;,)%&@] (or replace with empty space ""). I am using re package in Python: string = re.s... | Alright in my answer I assume you have a typo in your expected output. Remove everything starting with ; up to (;,)%&@) and so Stack ;O &verflow ;i %s ;the ;best! would become Stack&verflow%s;best! for the regex you want to start with ; then anything after 0 or more times .* (if you require a character change to .+) fo... | 2 | 2 |
77,890,197 | 2024-1-27 | https://stackoverflow.com/questions/77890197/fill-nulls-in-python-polars-lazyframe-by-groups-conditional-on-the-number-of-un | I have a large (~300M rows x 44 cols) dataframe and I need to fill in null values in certain ways depending on the characteristics of each group. For example, say we have lf = pl.LazyFrame( {'group':(1,1,1,2,2,2,3,3,3), 'val':('yes', None, 'no', '2', '2', '2', 'answer', None, 'answer') } ) ┌───────┬────────┐ │ group ┆... | You can add: .drop_nulls() .unique() with maintain_order=True when/then/otherwise to implement the conditional count/len logic unique = pl.col("val").drop_nulls().unique(maintain_order=True) df.with_columns( pl.when(unique.len().over("group") == 1) .then(pl.col("val").fill_null(unique.first().over("group"))) .otherwi... | 3 | 2 |
77,890,493 | 2024-1-27 | https://stackoverflow.com/questions/77890493/using-numba-for-scipy-fsolve-but-get-error | I want use numba for scipy.fsolve: from scipy.optimize import fsolve from numba import njit @njit def FUN12(): XGUESS=[8.0,7.0] X =[0.0,0.0] try: X = fsolve(FCN3, XGUESS) except: print("error") return X @njit def FCN3(X): F=[0.0,0.0] F[0]=4.*pow(X[0],2)-3.*pow(X[1],1)-7 F[1] = 5.*X[0] -2. * pow(X[1] , 2)+8 return F FUN... | Numba compatible code is only some subset of Python and Numpy functions. You should not run fsolve inside numba function. You should remove njit decorator from FUN12 function. You can keep it for FCN3. from scipy.optimize import fsolve from numba import njit # @njit remove this line, def FUN12(): XGUESS=[8.0,7.0] X =[0... | 2 | 1 |
77,889,046 | 2024-1-26 | https://stackoverflow.com/questions/77889046/polars-read-csv-vs-polars-read-csv-batched-vs-polars-scan-csv | What is the difference between polars.read_csv vs polars.read_csv_batched vs polars.scan_csv ? polars.read_csv looks equivalent to pandas.read_csv as they have the same name. Which one to use in which scenario and how they are similar/different to pandas.read_csv? | polars.read_csv_batched is pretty equivalent to pandas.read_csv(iterator=True). polars.scan_csv doesn't do anything until you perform an operation on the dataframe like dask.dataframe.read_csv (lazy loading). Scenarios: I use pandas.read_csv when my data is messy or complex in structure and the data is not too lar... | 4 | 1 |
77,888,782 | 2024-1-26 | https://stackoverflow.com/questions/77888782/wide-to-long-amid-merge | Hi I am trying to merge two dataset in the following way: df1=pd.DataFrame({'company name':['A','B','C'], 'analyst 1 name':['Tom','Mike',np.nan], 'analyst 2 name':[np.nan,'Alice',np.nan], 'analyst 3 name':['Jane','Steve','Alex']}) df2=pd.DataFrame({'company name':['A','B','C'], 'score 1':[3,5,np.nan], 'score 2':[np.nan... | Try: x = ( df1.set_index("company name") .stack(dropna=False) .reset_index(name="name") .drop(columns="company name") ) y = df2.set_index("company name").stack(dropna=False).reset_index(name="score") print( pd.concat([x, y], axis=1)[["company name", "name", "score"]] .dropna(subset=["name", "score"], how="all") .reset_... | 4 | 3 |
77,884,985 | 2024-1-26 | https://stackoverflow.com/questions/77884985/sql-injection-in-duckdb-queries-on-pandas-dataframes | In a project I am working with duckdb to perform some queries on dataframes. For one of the queries, I have some user-input that I need to add to the query. That is why I am wondering if SQL-Injection is possible in this case. Is there a way a user could harm the application or the system through the input? And if so, ... | The method duckdb.execute(query, parameters) only seems to work on databases with a real sql-connection and not on dataframes. It seems it's possible: >>> duckdb.execute("""SELECT * FROM df_data WHERE id=?""", (user_input,)).df() id student 0 3 student_b | 2 | 3 |
77,886,016 | 2024-1-26 | https://stackoverflow.com/questions/77886016/label-a-list-following-the-unique-elements-appearing-in-it | Given a list of strings such as: foo = \['A', 'A', 'B', 'A', 'B', 'C', 'C', 'A', 'B', 'C', 'A'\] How can we label them such that the output would be: output = \['A1', 'A2', 'B1', 'A3', 'B2', 'C1', 'C2', 'A4', 'B2', 'C3', 'A5'\] (keeping the order of the original list) In the following case there are only 3 unique var... | Using pure python, take advantage of a dictionary to count the values: foo = ['A', 'A', 'B', 'A', 'B', 'C', 'C', 'A', 'B', 'C', 'A'] d = {} out = [] for val in foo: d[val] = d.get(val, 0)+1 out.append(f'{val}{d[val]}') If you can use pandas: import pandas as pd s = pd.Series(foo) out = s.add(s.groupby(s).cumcount().ad... | 2 | 3 |
77,883,233 | 2024-1-25 | https://stackoverflow.com/questions/77883233/cannot-import-langchain-vectorstores-faiss-only-langchain-community-vectorstore | I am in the process of building a RAG like the one in this Video. However, I cannot import FAISS like this. from langchain.vectorstores import FAISS LangChainDeprecationWarning: Importing vector stores from langchain is deprecated. Importing from langchain will no longer be supported as of langchain==0.2.0. Please impo... | The solution was for me to importing the FAISS class directly from the langchain.vectorstores.faiss module and then using the from_documents method. from langchain_community.vectorstores.faiss import FAISS I had importing the faiss module itself, rather than the FAISS class from the langchain.vectorstores.faiss module... | 4 | 2 |
77,882,709 | 2024-1-25 | https://stackoverflow.com/questions/77882709/update-all-values-within-each-subgroup-in-pandas-dataframe | I have a pandas dataframe which has 4 columns of note, ID, DATE, PRIMARY_INDICATOR, PHONE Each ID can have multiple rows in the table. The rows are guaranteed to be sorted in descending date order within each ID subgroup. for example: >>> df.head(10) ID DATE PRIMARY_INDICATOR PHONE 0 123 20230125 1 8071234 1 123 202301... | It can be done without groupby: idx = (df.loc[df['PRIMARY_INDICATOR'].eq(1)] .duplicated('ID') .loc[lambda x: x].index) df.loc[idx, 'PRIMARY_INDICATOR'] = 0 Output: >>> df ID DATE PRIMARY_INDICATOR PHONE 0 123 20230125 1 8071234 1 123 20230124 0 8079999 2 999 20230125 1 8074312 3 999 20230120 0 9087654 4 999 20230119 ... | 2 | 2 |
77,882,214 | 2024-1-25 | https://stackoverflow.com/questions/77882214/airflow-dag-not-able-to-parse-ds | I have an Airflow DAG and I use {{ ds }} to get the logical date. As per Airflow documentation template {{ ds }} return logical date in format YYYY-MM-DD in string format. So I am using following code to manipulate the dates (datetime.strptime('{{ dag_run.logical_date|ds }}', '%Y-%m-%d') - timedelta(3)).strftime('%Y-%m... | Firstly I thought the problem could be de lack of spaces before and after the "|" operand, but I´ve tested and works fine. In this case, the main problem is that you´re not using the Jinja template where it is effectively parsed. Due to this, the error is that you don´t have a date to format, but a string as it is. tas... | 2 | 2 |
77,881,942 | 2024-1-25 | https://stackoverflow.com/questions/77881942/whats-the-polars-equivalent-to-the-pandas-iloc-method | I'm looking for the recommended way to select an individual row of a polars.DataFrame by row number: something largely equivalent to pandas.DataFrame's .iloc[[n]] method for a given integer n. For polars imported as pl and a polars DataFrame df, my current approach would be: # for example n = 3 # create row index, filt... | This is a very good sheet by: @Liam Brannigan Credit to them. https://www.rhosignal.com/posts/polars-pandas-cheatsheet/ A glimse from the sheet: You can find other information related to Filtering Rows using iloc and its equivalent in polars in the sheet. | 10 | 21 |
77,880,757 | 2024-1-25 | https://stackoverflow.com/questions/77880757/polars-filter-dataframe-with-multilple-conditions | I've got this pandas code: df['date_col'] = pd.to_datetime(df['date_col'], format='%Y-%m-%d') row['date_col'] = pd.to_datetime(row['date_col'], format='%Y-%m-%d') df = df[(df['groupby_col'] == row['groupby_col']) & (row['date_col'] - df['date_col'] <= timedelta(days = 10)) & (row['date_col'] - df['date_col'] > timedelt... | It's a bit hard to understand your example without test data. But if I try to create some sample data import polars as pl import datetime df = pl.DataFrame({ "date_col": ['2023-01-01','2023-01-02', '2023-01-03'], "groupby_col": [1,2,3], }) row = pl.DataFrame({ "date_col": ['2023-01-07','2023-01-08', '2023-01-25'], "gro... | 4 | 2 |
77,873,328 | 2024-1-24 | https://stackoverflow.com/questions/77873328/how-can-i-substitute-a-variable-in-format-command-of-python | My code finds an unknown (0<alpha<1), its precision depends on another parameter (dm). Finally, alpha is determined with e.g. 20 digits but depending on dm, alpha should be kept until definite (which is known during execution=njj) digit. At the end, I need to substitute njj in format command as following: njj= 8 ;alpha... | this is quite a good question. i find that this works nicely: njj= 8 alpha= 0.0004258819580078126 # I need this alpha= 0.00042588 print(f'{alpha:.{njj}f}') which gives this: 0.00042588 but also, you could do this: print(round(alpha, njj)) update: As per the comments below from @Mark, the round() function produces a ... | 3 | 1 |
77,878,672 | 2024-1-25 | https://stackoverflow.com/questions/77878672/how-can-i-get-the-seed-of-a-numpy-generator | I am using rng = np.random.default_rng(seed=None) for testing purposes following documentation. My program is a scientific code, so it is good to have some random values to test it, but if I found a problem with the code's result, I would like to get the seed back and try again to find the problem. Is there any way to ... | Use __getstate__, __setstate__ and forget about seed... it's just a parameter for default_rng! # old instance rng = np.random.default_rng(seed=None) s_old = rng.__getstate__() # new instance rng = np.random.default_rng(seed=123123) # seed=anything, also None s_new = rng.__getstate__() print(s_old == s_new) #False # upd... | 4 | 2 |
77,875,969 | 2024-1-24 | https://stackoverflow.com/questions/77875969/azure-machine-learning-pin-python-version-on-notebook | Looking for a way to use Python 3.10 on a compute resource associated to Azure ML Studio It appears 3.10 is available with ML Studio and we select 3.10 with SDK2 from the kernel selection dropdown but when running a "python --version" on the terminal, it says v 3.8.5. Is there a way to get Azure ML Studio to use a diff... | That is because of the selected conda environment. There will be multiple environments created when you create a compute instance. To see, run the conda command below: %%sh conda info --env This lists the environments present. However, if you run this in a notebook, you cannot see which environment you are in. So, exe... | 3 | 5 |
77,878,728 | 2024-1-25 | https://stackoverflow.com/questions/77878728/polars-dataframe-overlapping-groups | I am currently converting code from pandas to polars as I really like the api. This question is a more generally question to a previous question of mine (see here) I have the following dataframe # Dummy data df = pl.DataFrame({ "Buy_Signal": [1, 0, 1, 0, 1, 0, 0], "Returns": [0.01, 0.02, 0.03, 0.02, 0.01, 0.00, -0.01],... | For completeness, here is an alternative solution that doesnt rely on experimental functionality. ( df .with_columns( pl.col("Buy_Signal").cum_sum().alias("group") ) .with_columns( pl.int_ranges(pl.col("group").min(), pl.col("group")+1) ) .explode("group") .sort("group") ) Output. shape: (15, 3) ┌────────────┬────────... | 2 | 2 |
77,876,224 | 2024-1-24 | https://stackoverflow.com/questions/77876224/calculating-inverse-laplace-transform-using-python-or-matlab | I'm trying to simulate simple closed-loop system with PID controller in Python or MATLAB. In both cases I have problems with calculating time domain response of the system using inverse Laplace transform. To ilustrate the problem better, I'm following the names on the picture below: Depending on the transfer function ... | NOTE: I can't share my code, but I can give you the steps to reproduce it (which requires a little bit of work). The advantage of this procedure, which uses sympy's inverse_laplace_transform, is that you don't have to deal with Pade approximation of time delays. The main disadvantage is that you need to spend some time... | 3 | 1 |
77,873,084 | 2024-1-24 | https://stackoverflow.com/questions/77873084/calling-constructors-of-both-parents-in-multiple-inheritance-in-python-general | I'm trying to figure out the multiple inheritance in Python, but all articles I find are limited to simple cases. Let's consider the following example: class Vehicle: def __init__(self, name: str) -> None: self.name = name print(f'Creating a Vehicle: {name}') def __del__(self): print(f'Deleting a Vehicle: {self.name}')... | Thanks to the comments and the following article, I understood it. https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ Regarding the constructors' arguments, they should be named. In this way, every level strips what it needs and passes it to the next one using super() Every class calls super().__init... | 5 | 1 |
77,876,253 | 2024-1-24 | https://stackoverflow.com/questions/77876253/sort-imports-alphabetically-with-ruff | Trying ruff for the first time and I'm not being able to sort imports alphabetically, using default settings. According to docs ruff should be very similar to isort. Here is a short example with unsorted imports import os import collections Run ruff command $ ruff format file.py 1 file left unchanged But if I run iso... | According to https://github.com/astral-sh/ruff/issues/8926#issuecomment-1834048218: In Ruff, import sorting and re-categorization is part of the linter, not the formatter. The formatter will re-format imports, but it won't rearrange or regroup them, because the formatter maintains the invariant that it doesn't modify ... | 10 | 18 |
77,874,908 | 2024-1-24 | https://stackoverflow.com/questions/77874908/polars-valueerror-could-not-convert-value-unknown-as-a-literal-when-taking | ┌───────┬─────┐ │ group ┆ var │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═══════╪═════╡ │ 1 ┆ x │ │ 1 ┆ x │ │ 2 ┆ x │ │ 2 ┆ y │ │ 3 ┆ y │ │ 3 ┆ y │ └───────┴─────┘ Suppose the above dataframe is called df and I want to get the percentage of variables named 'x' by group. The following gives me ValueError: could not convert value '... | As mentioned in the documentation, pl.mean() is just a syntactic sugar for pl.col(columns).mean(). Your code doesn't work because pl.mean() expects *columns: str (column names) as input, not Expr. But you can use pl.col(columns).mean() instead: df = df.group_by('group', maintain_order=True).agg( (pl.col('var') == 'x').... | 3 | 3 |
77,874,255 | 2024-1-24 | https://stackoverflow.com/questions/77874255/pyinstaller-modulenotfound-error-urllib3-packages-six-moves | I'm trying to package a script using pyinstaller to run as a windows service. When trying to run it I get the ModuleNotFoundError: No module named 'urllib3.packages.six.moves' error. I'm using the command pyinstaller.exe --onefile --runtime-tmpdir=. --hidden-import win32timezone --hidden-import urllib3 laps_service.py ... | In the end this was some kind of dependency conflict - I uninstalled urllib3 and requests, and then reinstalled requests - this triggered a reinstall of some urllib3 stuff. I don't quite know why, so here's the traceback for posterity: pip install requests Collecting requests Using cached requests-2.31.0-py3-none-any.w... | 2 | 1 |
77,873,044 | 2024-1-24 | https://stackoverflow.com/questions/77873044/how-do-i-get-all-possible-orderings-of-9-zeros-and-9-ones-using-python | I want to end up with a list with 48 620 nested lists, containing 9 zeros and 9 ones in different orders. from itertools import permutations print(list(permutations('000000000111111111', r=18))) I assume the code above works, but every 0 and 1 is treated like an individual symbol, so for every ordering I get tons of r... | Where 18 is the length of the list you want to generate and 9 is how many of them should be 0: for x in itertools.combinations(range(18),9): print(tuple(('0' if i in x else '1' for i in range(18)))) The idea here is to use combinations to choose the set of locations that will be 0 for each of (in your example's case) ... | 2 | 5 |
77,871,144 | 2024-1-24 | https://stackoverflow.com/questions/77871144/typecheckerror-argument-config-file-none-did-not-match-any-element-in-the-u | I am getting an error when I tried to implement pandas profiling. Please find the code that I've tried, the error I got and the versions of the packages I used. Code: import pandas as pd from pandas_profiling import ProfileReport df = pd.read_csv("data.csv") profile = ProfileReport(df) profile Error: -----------------... | This is a known issue: Install ydata-profiling with pip pip install ydata-profiling Just add import and use the existing code as is. import pandas as pd from ydata_profiling import ProfileReport df = pd.read_csv('file.csv') profile_report = ProfileReport(df) Link to document : https://pypi.org/project/pandas-profilin... | 3 | 2 |
77,847,983 | 2024-1-19 | https://stackoverflow.com/questions/77847983/processing-requests-in-fastapi-sequentially-while-staying-responsive | My server exposes an API for a resource-intensive rendering work. The job it does involves a GPU and as such the server can handle only a single request at a time. Clients should submit a job and receive 201 - ACCEPTED - as a response immediately after. The processing can take up to a minute and there can be a few doze... | As you may have figured out already, the main issue in your example is that you run a synchronous blocking operation within an async def endpoint, which blocks the event loop (of the main thread), and hence, the entire server. As explained in this answer, if one has to use an async def endpoint, they could run such CPU... | 11 | 13 |
77,861,518 | 2024-1-22 | https://stackoverflow.com/questions/77861518/polars-compute-row-wise-quantile-over-dataframe | I have some polars DataFrames over which I want to compute some row-wise statistics. For some there is a .list.func function which exists (eg list.mean), however, for those which don't have a dedicated function I believe I must use list.eval. For the following example data: df = pl.DataFrame({ 'a': [1,10,1,.1,.1, np.NA... | I would unpivot and join here. It should be faster than .list.eval plus it let's you more easily add other row wise aggregations. Note I've added q2,q3,q4 to the agg ( (_df:=df.with_row_index('i')) .join( _df .unpivot(index='i') .group_by('i') .agg( pl.col('value').quantile(x).alias(q) for q,x in {'q1':0.25,'q2':0.50, ... | 3 | 1 |
77,852,033 | 2024-1-20 | https://stackoverflow.com/questions/77852033/enable-ruff-rules-only-on-specific-files | I work on a large project and I'd slowly like to enfore pydocstyle using ruff. However, many files will fail on e.g. D103 "undocumented public function". I'd like to start with enforcing it on a few specific files, so I'd like to write something like select = ["D"] [tool.ruff.ignore-except-per-file] # this config does ... | You can invert the file selection in the (extend-)per-file-ignores section to ignore for example D103 on all files except the ones that do match the pattern. from the Ruff documentation for the per-file-ignores: A list of mappings from file pattern to rule codes or prefixes to exclude, when considering any matching fi... | 6 | 3 |
77,869,420 | 2024-1-23 | https://stackoverflow.com/questions/77869420/how-to-connect-fastapi-jinja2-and-keycloak | I work for a company and I have a Python FastAPI project. This is something like a multi-page website, where each endpoint is a page of the site. This was done using Jinja2 - TemplateResponse(). I know that this is not the best solution for similar projects, such as Flask or Django, but there is no way to change it. I ... | Finally, my solution: import jwt import time import json import uvicorn import requests from fastapi import FastAPI, Request from fastapi.responses import RedirectResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.templating import Jinja2Templates from fastapi.security.utils import get_authorizati... | 3 | 0 |
77,842,145 | 2024-1-18 | https://stackoverflow.com/questions/77842145/attributeerror-httpxbinaryresponsecontent-object-has-no-attribute-with-strea | I am using openai to convert text into audio , how ever this error always pops up : AttributeError: 'HttpxBinaryResponseContent' object has no attribute 'with_streaming_response' I have tried the stream_to_field() function but it neither works def audio(prompt): speech_file_path=Path('C:\\Users\\beni7\\Downloads\\proye... | .with_streaming_response is a method on speech. You can try the following: def audio(prompt): speech_file_path="<file path>" with client.audio.speech.with_streaming_response.create( model="tts-1", voice="alloy", input=prompt, ) as response: response.stream_to_file(speech_file_path) | 2 | 5 |
77,860,398 | 2024-1-22 | https://stackoverflow.com/questions/77860398/how-to-zip-multiple-csv-files-into-archive-and-return-it-in-fastapi | I'm attempting to compose a response to enable the download of reports. I retrieve the relevant data through a database query and aim to store it in memory to avoid generating unnecessary files on the server. My current challenge involves saving the CSV file within a zip file. Regrettably, I've spent several hours on t... | Here's a working example on how to create multiple csv files, then compress them into a zip file, and finally, return the zip file to the user. This answer makes use of code and concepts previously discussed in the following answers: this, this and this. Thus, I would suggest having a look at those answers for more det... | 4 | 2 |
77,841,985 | 2024-1-18 | https://stackoverflow.com/questions/77841985/python-requests-giving-me-missing-metadata-when-trying-to-upload-attachment | I am trying to upload an attachment via an API. I can make it work in the software's Swagger environment with this: curl -X 'POST' \ 'https://demo.citywidesolutions.com/v4_server/external/v1/maintenance/service_requests/9/attached_files' \ -H 'accept: */*' \ -H 'Content-Type: multipart/form-data' \ -H 'Authorization: B... | You could try explicitly setting the file type in your code; you do so in the curl method, but not in the Python script. Also, the requests library is able to handle 'Content-Type', so typically you don't need to set it. And the description parameter may be expected as a tuple. Here are all those changes; I have not te... | 2 | 1 |
77,848,276 | 2024-1-19 | https://stackoverflow.com/questions/77848276/linear-regression-output-are-nonsensical | I have a dataset and am trying to fill in the missing values by utilizing a 2d regression to get the slope of the surrounding curves to approximate the missing value. I am not sure if this is the right approach here, but am open to listen to other ideas. However, here's my example: local_window = pd.DataFrame({102.5: {... | I made some modifications to your predict function: def predict_nan_local(local_window, degree=2): # Only proceed if there are NaNs to fill if not local_window.isnull().values.any(): return local_window # Create a meshgrid of x and y values x = local_window.columns.values y = local_window.index.values X, Y = np.meshgri... | 3 | 2 |
77,833,712 | 2024-1-17 | https://stackoverflow.com/questions/77833712/odoo-16-custom-website-pagination-problem | I paginated the search result. For the first, query set gives me perfect result , but the pagination set all pages, and I get all data from database by clicking on any page number. Here is my code: This is the controller which I added : class MyCustomWeb(http.Controller): @http.route(['/customer', '/customer/page/<int... | Since you have not supplied a domain, customer_obj.sudo().search_count([]) will return the whole amount of records in the model. Alternatively, you can use len(customer_obj) or provide a domain inside the search_count as well. total = len(customer_obj) pager = request.website.pager( url='/customer', total=total, page=p... | 5 | 4 |
77,867,589 | 2024-1-23 | https://stackoverflow.com/questions/77867589/how-do-you-replace-set-tight-layout-with-set-layout-engine | When I call fig.set_tight_layout(True) on a Matplotlib figure, I receive this deprecation warning: The set_tight_layout function will be deprecated in a future version. Use set_layout_engine instead. How do I call set_layout_engine so as to match the current behavior as closely as possible? Environment: OS: Mac Python... | From: https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.set_layout_engine fig.set_layout_engine("tight") | 2 | 1 |
77,864,704 | 2024-1-23 | https://stackoverflow.com/questions/77864704/annotated-transformer-why-x-dropoutsublayerlayernormx | Please clarify if the Annotated Transformer Encoder LayerNorm implementation is correct. Transformer paper says the output of the sub layer is LayerNorm(x + Dropout(SubLayer(x))). LayerNorm should be applied after the DropOut(SubLayer(x)) as per the paper: However, the Annotated Transformer implementation does x + D... | Original paper applied Dropout to the Sub-Layer (Multi Head Attention) before Residual Connection and Layer Normalization. This is called Post Normalization. dropout to the output of each sub-layer, before it is added to the sub-layer input (x) and (layer) normalized. However, recent approach is Pre Normalization whe... | 3 | 5 |
77,869,443 | 2024-1-23 | https://stackoverflow.com/questions/77869443/create-custom-model-class-with-python | I have an example class as follows: class MLP(nn.Module): # Declare a layer with model parameters. Here, we declare two fully # connected layers def __init__(self): # Call the constructor of the `MLP` parent class `Module` to perform # the necessary initialization. In this way, other function arguments # can also be sp... | You have a capital X in the forward method, while the function expects lowercase x. You must have a tensor with shape (2, 20) assigned to variable capital X. | 2 | 2 |
77,864,142 | 2024-1-23 | https://stackoverflow.com/questions/77864142/pass-socketio-server-instance-to-fastapi-routers-as-dependency | I'm using python-socketio and trying to pass the server instance to my app routers as dependency: main.py file: import socketio import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from src.api.rest.api_v1.route_builder import build_routes app = FastAPI() app.add_middleware( COR... | You need to create function, where just return AsyncServer object. Then use this function as a dependency in your endpoint functions. It's better to create this dependency in separate file to avoid import errors. dependencies.py import socketio sio = socketio.AsyncServer(cors_allowed_origins="*", async_mode="asgi") def... | 2 | 1 |
77,868,799 | 2024-1-23 | https://stackoverflow.com/questions/77868799/polars-dataframe-add-columns-conditional-on-other-column-yielding-different-len | I have the following dataframe in polars. df = pl.DataFrame({ "Buy_Signal": [1, 0, 1, 0, 0], "Returns": np.random.normal(0, 0.1, 5), }) Ultimately, I want to do aggregations on column Returns conditional on different intervals - which are given by column Buy_Signal. In the above case the length is from each 1 to the e... | It's pretty similar to what you were thinking... ( df .with_columns( Holdings = pl.col('Buy_Signal').cum_sum() ) .with_columns( pl.when(pl.col("Holdings")>=x) .then(pl.col("Returns")).alias(f"Port_{x}") for x in range(1,df['Buy_Signal'].sum()+1) ) ) shape: (5, 5) ┌────────────┬───────────┬──────────┬───────────┬───────... | 2 | 3 |
77,854,397 | 2024-1-21 | https://stackoverflow.com/questions/77854397/pandas-resample-signal-series-with-its-corresponding-label | I have this table with these columns: Seconds, Amplitude, Labels, Metadata. Basically, it's an ECG signal. You can download the csv here: https://tmpfiles.org/3951223/question.csv As you see, the second timestep is 0.004. How to resample that with the desired new timestep, such as 0.002, without destructing another col... | This is a straightforward application of resample(), but you have to make some aggregation decisions. from io import StringIO import pandas as pd content = ''' index seconds amplitude label_encoding bound_or_peak 0 0.0 0.035 0 0 1 0.004 0.06 0 0 2 0.008 0.065 0 0 3 0.012 0.075 0 0 4 0.016 0.085 0 0 5 0.02 0.075 0 0 6 0... | 2 | 1 |
77,866,314 | 2024-1-23 | https://stackoverflow.com/questions/77866314/converting-sklearn-model-to-core-ml-model-for-ios | I have created sklearn model for predicting ESG Scores. But for imputation reasons my input features matrix X were converted to np.ndarray. I found on apple developers website how to convert them, but there is optional kwargs input_features and output_features. import coremltools coreml_model = coremltools.converters.s... | There is dedicated method called ct.converters.sklearn.convert for this goal. Here is a full example of the conversion: from sklearn.linear_model import LinearRegression import numpy as np import coremltools as ct # Load data X = np.random.rand(10,5).astype(np.ndarray) y = np.random.rand(10).astype(np.ndarray) # Train ... | 3 | 1 |
77,866,543 | 2024-1-23 | https://stackoverflow.com/questions/77866543/create-pydantic-computed-field-with-invalid-syntax-name | I have to model a pydantic class from a JSON object which contains some invalid syntax keys. As an example: example = { "$type": "Menu", "name": "lunch", "children": [ {"$type": "Pasta", "title": "carbonara"}, {"$type": "Meat", "is_vegetable": false}, ] } My pydantic classes at the moment looks like: class Pasta(BaseM... | This very much looks like you would rather apply a discriminated union pattern. See the following example: from pydantic import BaseModel, Field from typing import Literal, Annotated example = { "$type": "Menu", "name": "lunch", "children": [ {"$type": "Pasta", "title": "carbonara"}, {"$type": "Meat", "is_vegetable": F... | 2 | 0 |
77,866,553 | 2024-1-23 | https://stackoverflow.com/questions/77866553/write-selected-columns-from-pandas-to-excel-with-xlsxwriter-efficiently | I’m trying to write some of the columns of a pandas dataframe to an Excel file, but it’s taking too long. I’m currently using xlsxwriter to write all of the data to the file, which is much faster. How can I write only some of the columns to the file without sacrificing performance? My code for writing selected columns ... | You can use the write_column method for col_num, col_name in enumerate(selected_columns): col_data = df[col_name].tolist() worksheet.write_column(1, col_num, col_data) You can take a look and learn more about here: https://xlsxwriter.readthedocs.io/worksheet.html | 2 | 1 |
77,866,010 | 2024-1-23 | https://stackoverflow.com/questions/77866010/typevar-in-a-nested-type-specification | Let's say I have a type defined with TypeVar, like so: T = TypeVar('T') MyType = Union[list[T], tuple[T]] def func(a: MyType[int]): pass I also want to have an optional version of it: MyTypeOpt = Optional[MyType] def opt_func(a: MyTypeOpt[int] = None): pass But this is not to mypy's liking and I'm getting an error: B... | I think you are missing the type parameter for your generic type MyType. mypy is also complaining about that. from typing import Optional, Sequence, Tuple, Union from typing_extensions import TypeVar T = TypeVar('T') MyType = Union[Sequence[T], Tuple[T]] MyTypeOpt = Optional[MyType[T]] # <--------- def func(a: MyType[i... | 2 | 3 |
77,865,964 | 2024-1-23 | https://stackoverflow.com/questions/77865964/merge-resulted-column-from-pandas-dataframe-based-on-condition | I have two dataframes as below df1 = pd.DataFrame( { "names": ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf'], "Debit": [0, 5000, 0, 5000, 3000, 0, 700], "Credit": [1000, 0, 2000, 0, 0, 8000, 0], } ) and df2 = pd.DataFrame( { "names": ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot'], "db_hea... | You can merge, then post-process the output with pop and where: out = df1.merge(df2, on='names', how='inner') out['head'] = out.pop('db_head').where(out['Debit'].ne(0), out.pop('cr_head')) Output: names Debit Credit head 0 alpha 0 1000 2 1 bravo 5000 0 1 2 charlie 0 2000 2 3 delta 5000 0 1 4 echo 3000 0 1 5 foxtrot 0... | 2 | 2 |
77,864,140 | 2024-1-23 | https://stackoverflow.com/questions/77864140/delete-2-column-headers-and-shift-the-whole-column-row-to-left-in-dataframe | Delete 2 column headers and shift the whole column row to left in dataframe. Below is my dataframe. trash1 trash2 name age 0 john 54 1 mike 34 2 suz 56 3 tin 78 4 yan 31 i need the final df as below name age 0 john 54 1 mike 34 2 suz 56 3 tin 78 4 yan 31 I tried all the commands but its deleting the whole column. P... | You can slice with iloc and rename with set_axis: N = 2 out = (df.iloc[:, :-N] .set_axis(df.columns[N:], axis=1) ) Output: name age 0 john 54 1 mike 34 2 suz 56 3 tin 78 4 yan 31 Timing of answers for a generalized number of columns: Overall manually setting the name is reliably the fastest since the data is fully u... | 2 | 2 |
77,864,953 | 2024-1-23 | https://stackoverflow.com/questions/77864953/how-to-add-a-column-or-change-data-in-each-group-after-using-group-by-in-pandas | I am now using Pandas to handle some data. After I used group by in pandas, the simplified DataFrame's format is [MMSI(Vessel_ID), BaseTime, Location, Speed, Course,...]. I use for MMSI, group in grouped_df: print(MMSI) print(group) to print the data. For example, one group of data is: MMSI BaseDateTime LAT LON SOG C... | Don't use a loop, directly go with groupby.shift: s = pd.to_datetime(df['BaseDateTime']) df['Time-diff'] = (s.groupby(df['MMSI']).shift(-1) .sub(s).dt.total_seconds().div(3600) ) Or groupby.diff: s = pd.to_datetime(df['BaseDateTime']) df['Time-diff'] = (s.groupby(df['MMSI']).diff(-1) .mul(-1).dt.total_seconds().div(36... | 3 | 2 |
77,862,489 | 2024-1-22 | https://stackoverflow.com/questions/77862489/why-does-adding-the-decorator-lru-cachefrom-functools-break-this-function | The function is a part of the solution to the following problem: "Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list must not contain the sa... | You violated the decorator’s contract. You’re mutating elements of the returned list. The decorator should only be applied to Pure functions. You defined a Public API that returns a list of lists. Switch to returning an immutable tuple of tuples. Then your approach will be compatible with the LRU decorator. | 3 | 2 |
77,861,284 | 2024-1-22 | https://stackoverflow.com/questions/77861284/regex-algorithm-in-python-to-extract-comments-from-class-attributes | Given the code for a class definition, I am trying to extract all attributes and their comments ("" empty string if no comments). class Player(Schema): score = fields.Float() """ Total points from killing zombies and finding treasures """ name = fields.String() age = fields.Int() backpack = fields.Nested( PlayerBackpac... | I might use ast, e.g.: import ast code_block = '''class Player(Schema): score = fields.Float() """ Total points from killing zombies and finding treasures """ name = fields.String() age = fields.Int() backpack = fields.Nested( PlayerBackpackInventoryItem, missing=[PlayerBackpackInventoryItem.from_name("knife")], ) """ ... | 2 | 2 |
77,861,508 | 2024-1-22 | https://stackoverflow.com/questions/77861508/python-break-a-timer-repeat-after-time-went-zero-on-raspberry-pi | i am programming a pythonscript with guizero. there is a PushButton and its command runs a function. This function ist build after a PomodoraTimer Tutorial i found on youtube. As far, it works, but i want it to stop, after the alarm is running. The Code is the following: #UserInterface, GPIO-Steuerung und Timer-Steueru... | Damn, after hours of trying i posted this - and few seconds later I found a solution! I had to add the following line insted of the '#exit()' statement i also worked with: time.cancel(reduceTime) | 3 | 1 |
77,847,952 | 2024-1-19 | https://stackoverflow.com/questions/77847952/find-a-substring-of-4-consecutive-digits-and-a-substring-of-3-consecutive-digits | I have strings of the type: 1432_ott_457_blusp 312_fooob_bork_1234 broz_901_6453 kkhas_1781_LET_GROK_234 1781_234_kkhas etc. In other words, each string contains multiple substrings delimited by _. The total number of substrings is variable. I look for a substring containing 4 digits, and another one containing 3 digi... | If you want to stick with regular expressions, you're almost there: import re input = """1432_ott_457_blusp 312_fooob_bork_1234 broz_901_6453 kkhas_1781_LET_GROK_234 1781_234_kkhas""" for s in input.splitlines(): print(re.findall(r'\d{3,4}', s)) This doesn't take advantage of the underscore delimiter rule so if you ha... | 2 | 5 |
77,858,217 | 2024-1-22 | https://stackoverflow.com/questions/77858217/3d-antenna-radiation-plot-in-spherical-coorinates-problem | I want to plot 3D antenna radiation pattern from CSV file, after data loading i have got: Theta Phi Dir 0 0.000 0.0 8.272 1 5.000 0.0 8.221 2 10.000 0.0 8.064 3 15.000 0.0 7.804 4 20.000 0.0 7.444 ... ... ... ... 2659 160.000 355.0 -13.240 2660 165.000 355.0 -12.330 2661 170.000 355.0 -11.460 2662 175.000 355.0 -10.87... | I think that you are just getting row/column order muddled up (multiple times). Theta changes fastest in your input. Note that you will also get a small gap in your plot unless your input data file includes the full-circle value for phi=360 degrees at the end. I don't have your data, so I had to generate my own (see th... | 2 | 1 |
77,860,036 | 2024-1-22 | https://stackoverflow.com/questions/77860036/why-reading-a-compressed-tar-file-in-reverse-order-is-100x-slower | First, let's generate a compressed tar archive: from io import BytesIO from tarfile import TarInfo import tarfile with tarfile.open('foo.tgz', mode='w:gz') as archive: for file_name in range(1000): file_info = TarInfo(str(file_name)) file_info.size = 100_000 archive.addfile(file_info, fileobj=BytesIO(b'a' * 100_000)) ... | A tar file is strictly sequential. You end up reading the beginning of the file 1000 times, rewinding between them, reading the second member 999 times, etc etc. Remember, the "tape archive" format was designed at a time when unidirectional tape reels on big spindles was the hardware they used. Having an index would on... | 3 | 7 |
77,859,431 | 2024-1-22 | https://stackoverflow.com/questions/77859431/how-to-get-the-index-of-function-parameter-list-comprehension | Gurobipy can apparently read the index of a list comprehension formulated within the parentheses of a function. How does this work? Shouldn't this formulation pass a generator object to the function? How do you read the index from that? md = gp.Model() md.addConstrs(True for i in [1,2,5,3]) The output contains the in... | I am not sure if I understand your question correctly, but if you are wondering how you can retrieve the iterator from generator expression, then that's by accessing <generator>.gi_frame.f_locals. The gi_frame contains the frame object corresponds to the generator expression and it has f_locals attribute which denotes ... | 5 | 6 |
77,844,870 | 2024-1-19 | https://stackoverflow.com/questions/77844870/google-gemini-api-response | I am using the Gemini API, and need some help. When I ran my code that I got from the docs it returned: <google.generativeai.types.generation_types.GenerateContentResponse> . Here is my code import pathlib import textwrap import google.generativeai as genai from IPython.display import display from IPython.display impor... | That's a google object of the response you are getting. You need to mention as response.text to get the actual text. Like this: print(response.text) | 2 | 3 |
77,838,537 | 2024-1-18 | https://stackoverflow.com/questions/77838537/consistently-compiling-c-code-with-fpic-for-a-rust-ffi-crate | My rust project uses a FFI to the C lib SuperLU, which is called superlu-sys. My rust code produces Python bindings with PyO3. As soon as the python bindings have a function calling SuperLU I get the following linker error on building: relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when m... | I switched the buid.rs script to using the cmake rust crate instead of invoking make as a subprocess. | 5 | 0 |
77,855,706 | 2024-1-21 | https://stackoverflow.com/questions/77855706/how-can-i-merge-two-dataframes-based-on-range-of-dates | I have two DataFrames: df1 and df2 import pandas as pd df1 = pd.DataFrame( { 'a': ['2024-01-01 04:00:00', '2023-02-02 20:00:00'], 'id':['a_1', 'a_2'] } ) df2 = pd.DataFrame( { 'a': [ '2024-01-01 4:00:00', '2024-01-01 05:00:00', '2024-01-01 06:00:00', '2024-01-01 07:00:00', '2024-01-01 08:00:00', '2024-01-01 09:00:00', ... | If I understand correctly, you need a merge_asof with tolerance: df1['a'] = pd.to_datetime(df1['a']) df2['a'] = pd.to_datetime(df2['a']) out = (pd.merge_asof(df2.reset_index().sort_values(by='a'), df1.sort_values(by='a'), on='a', tolerance=pd.Timedelta(hours=3) ) .set_index('index').reindex(df2.index) ) Output: a id ... | 3 | 2 |
77,851,866 | 2024-1-20 | https://stackoverflow.com/questions/77851866/custom-legend-for-the-plot-with-lines-changing-colour | I want to plot two error bars plots with lines changing colour, one going from pink to blue, and another from blue to pink. I did not find a way to do this with plt.errorbar(), but managed to find a workaround solution using LineCollection. I am plotting error bar plots with a dashed line, and then adding two lines tha... | this can be done by slightly adjusting the answer I posted to a similar question concerning custom legend handles for multi-color points (https://stackoverflow.com/a/67870930/9703451) The idea is to use a custom handler that will draw the legend-patch... this should do the job: # define an object that will be used by t... | 3 | 2 |
77,855,094 | 2024-1-21 | https://stackoverflow.com/questions/77855094/how-to-get-the-session-id-of-windows-using-ctypes-in-python | I am attempting to retrieve the session ID of the current user session on Windows using ctypes in Python. My goal is to accomplish this without relying on external libraries. Here is the code I have so far: import ctypes from ctypes import wintypes def get_current_session_id(): WTS_CURRENT_SERVER_HANDLE = ctypes.wintyp... | PROBLEM SOLVED: import ctypes from ctypes import wintypes def get_current_session_id(): ProcessIdToSessionId = ctypes.windll.kernel32.ProcessIdToSessionId ProcessIdToSessionId.argtypes = [wintypes.DWORD, wintypes.PDWORD] ProcessIdToSessionId.restype = wintypes.BOOL process_id = wintypes.DWORD(ctypes.windll.kernel32.Get... | 2 | 0 |
77,854,931 | 2024-1-21 | https://stackoverflow.com/questions/77854931/how-improve-updating-multiple-columns-of-a-pandas-dataframe-when-the-columns | I have a DataFrame that has columns as datetime objects, and I would like to update specific values for a specific index based on a list of days. Here is an MRE that works: import pandas as pd start, stop = "2023-12-01", "2023-12-31" dates: pd.Index = pd.date_range(start, stop, freq="D") december = pd.DataFrame(columns... | Just do that using the day attribute and isin: december.loc['ft', december.columns.day.isin([4, 6, 11, 12, 27, 28])] = 'X' If you also only want to target december (or a list of months): december.loc['ft', (december.columns.day.isin([4, 6, 11, 12, 27, 28]) &december.columns.month.isin([12]) )] = 'X' Output: 2023-12-... | 2 | 2 |
77,851,097 | 2024-1-20 | https://stackoverflow.com/questions/77851097/waterfall-plot-with-treeexplainer | Using TreeExplainer in SHAP, I could not plot the Waterfall Plot. Error Message: ---> 17 shap.plots.waterfall(shap_values[0], max_display=14) TypeError: The waterfall plot requires an `Explanation` object as the `shap_values` argument. Since my model is tree based, I use TreeExplainer (because of using xgb.XGBClassifi... | Instead of feeding shap values as numpy.ndarray try an Explanation object: import xgboost as xgb import shap from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.metrics import accuracy_score, confusion_matrix, classification_report from sklearn.model_selection import GridSearchCV data = { 'a... | 2 | 2 |
77,854,185 | 2024-1-21 | https://stackoverflow.com/questions/77854185/how-to-create-one-dictonary-using-3-lists | I am new to Python and need help creating one dictionary file using three lists. example: list 1 = ["private", "private"] list 2 = ["10.1.1.1", "10.11.11.11"] list3 = [ "sfc", "gfc"] my code: dict = {} for s in range(len(list1)): dict[list1[s]] = {list2[s]: list3[s]} print(dict) I am getting output as {'private': {'1... | list1 = ["private", "private"] list2 = ["10.1.1.1", "10.11.11.11"] list3 = ["sfc", "gfc"] my_dict = {} for s in range(len(list1)): if list1[s] not in my_dict: my_dict[list1[s]] = [] my_dict[list1[s]].append({list2[s]: list3[s]}) print(my_dict) Output: {'private': [{'10.1.1.1': 'sfc'}, {'10.11.11.11': 'gfc'}]} It chec... | 2 | 2 |
77,854,089 | 2024-1-21 | https://stackoverflow.com/questions/77854089/how-to-unify-the-response-format-in-fastapi-while-preserving-pydantic-data-model | In FastAPI, I am using SQLAlchemy and Pydantic to return data. @router.get("/1", response_model=User) def read_user(db: Session = Depends(get_db)): db_user = user_module.get_user(db, user_id="1") if db_user is None: raise HTTPException(status_code=404, detail="User not found") return db_user This approach helps me sta... | from pydantic import BaseModel, Field from typing import Generic, TypeVar, Type, Optional from fastapi import Depends, HTTPException, APIRouter from sqlalchemy.orm import Session T = TypeVar('T') class GenericResponse(BaseModel, Generic[T]): code: int = Field(default=0, example=0) msg: str = Field(default="success", ex... | 3 | 2 |
77,852,109 | 2024-1-20 | https://stackoverflow.com/questions/77852109/using-ruff-linter-with-python-in-vs-code | I have installed the Ruff extension and enabled it in VS Code, but it doesn't seem to be underlining my code at all and providing suggestions like my previous linters did. I did a clean install of VS Code, so most of the Python/Ruff extension settings are default. Is there an additional step I need to take to get it to... | Take another look at the ruff documentation. You must enable or disable your desired linter rules and/or your formatting rules. For example, if you create a ruff.toml configuration in the root of your project with [lint] select = ["ALL"] the output looks more like what you expect. | 10 | 7 |
77,843,567 | 2024-1-19 | https://stackoverflow.com/questions/77843567/discord-py-interaction-already-acknowledged | The code runs fine up until I click the button and It gives an error (included at top). The script still runs with the error but I need to fix it for hosting purposes. Thanks! class CollabButton(discord.ui.View): def __init__(self): super().__init__(timeout=None) self.add_item( discord.ui.Button(label='Accept', style=d... | This problem is happening because you are not filtering the desired interactions in the on_interaction event. As a result, interactions that are handled in other components are also being received by this event. It is highly recommended that you define a custom_id for the component you want to handle in this event and ... | 4 | 1 |
77,851,213 | 2024-1-20 | https://stackoverflow.com/questions/77851213/error-when-specifying-cmap-in-plt-matshow | I get an error every time when I try to define the cmap while calling sns.color_palette(). I think it has something to do with the definition of the color palette but I am not sure: colors = ["#1d4877", "#1b8a5a", "#fbb021", "#f68838", "#ee3e32"] sns.set_palette(colors) And when I try to set it: plt.matshow(num1.corr(... | Just use matplotib's ListedColormap from matplotlib.colors import ListedColormap colors = ["#1d4877", "#1b8a5a", "#fbb021", "#f68838", "#ee3e32"] plt.matshow(np.arange(12).reshape(3, 4), cmap=ListedColormap(colors)) Note however, that this cmap is not suitable if you have continuous data. Output: | 2 | 2 |
77,847,798 | 2024-1-19 | https://stackoverflow.com/questions/77847798/how-to-find-an-optimal-shape-with-sections-missing | Given an n by n matrix of integers, I want to find a part of the matrix that has the maximum sum with some restrictions. In the version I can solve, I am allowed to draw two lines and remove everything below and/or to the right. These can be one horizontal line and one diagonal line at 45 degrees (going up and right). ... | Here is a solution that will handle any number of alternating include/exclude regions. (But always in that order.) def optimize_exclude(matrix, blocks=5): """Finds the optimal exclusion pattern for a matrix. matrix is an nxm array of arrays. blocks is the number of include/exclude blocks. We start with an include block... | 2 | 2 |
77,848,941 | 2024-1-19 | https://stackoverflow.com/questions/77848941/how-to-use-numpy-frombuffer-to-read-a-file-sent-using-fastapi | I'm trying to read data from a text file sent to my API built using fastapi. The files template is always the same and consists of three columns of numbers as shown in the picture below: I tried solving the problem with the following code using numpy: @app.post("/uploadfile/") async def create_upload_file(file: Upload... | Why the error frombuffer is to read raw, "binary" data. So if you are trying to read float64, for examples, it just read packets of 64 bits (as the internal representation of float64) and fills a numpy array of float64 with it. For example np.frombuffer(b'\x00\x01\x02\x03', dtype=np.uint8) # → array([0,1,2,3], dtype=ui... | 3 | 2 |
77,849,025 | 2024-1-19 | https://stackoverflow.com/questions/77849025/avoiding-deprecationwarning-when-extracting-indices-to-subset-vectors | General idea: I want to take a slice of a 3D surface plot of a function of two variables f(x,y) at a given x = some value. The problem is that I have to know the index where x assumes this value after creating x as a vector with np.linspace, for instance. Finding this index turns out to be doable thanks to another post... | Break down the resulting value you get from np.where: >>> np.where(x == find_nearest(x,0)) (array([1000]),) Then dereference the first element: >>> np.where(x == find_nearest(x,0))[0] array([1000]) Ok, same thing. Get first element: >>> np.where(x == find_nearest(x,0))[0][0] 1000 | 2 | 2 |
77,848,932 | 2024-1-19 | https://stackoverflow.com/questions/77848932/simplify-dataframe-by-combining-data-from-various-columns-together-for-same-inst | I have a dataframe after concatenting several dataframes df1 = instance scan comp sort 0 A 23:15:12 NaN NaN 1 B 23:17:12 NaN NaN 2 C 23:16:12 NaN NaN 0 A NaN 23:19:32 NaN 1 B NaN 23:19:32 NaN 2 C NaN 23:43:23 NaN 0 A NaN NaN 23:45:32 1 B NaN NaN 23:45:26 2 C NaN NaN 23:45:12 I need to simplify above and have all the c... | You can use groupby_first: df2 = df1.groupby('instance', as_index=False).first() print(df2) # Output instance scan comp sort 0 A 23:15:12 23:19:32 23:45:32 1 B 23:17:12 23:19:32 23:45:26 2 C 23:16:12 23:43:23 23:45:12 From the documentation, the function returns: First non-null of values within each group. Maybe I'm... | 2 | 4 |
77,848,288 | 2024-1-19 | https://stackoverflow.com/questions/77848288/how-to-permute-values-in-a-single-row-of-a-pandas-dataframe | I have some messy data that requires me to split it up as a combination of values. This is sort of what it looks like: import pandas as pd data = {"Name":["name1", "name2"], "A": [[1, 2, 3], [1]], "B": [["a", "b"], ["a"]]} df = pd.DataFrame(data) And I would like to permute the two columns with list data so that the r... | You can explode the two columns successively: df.explode('A').explode('B', ignore_index=True) Output: Name A B 0 name1 1 a 1 name1 1 b 2 name1 2 a 3 name1 2 b 4 name1 3 a 5 name1 3 b 6 name2 1 a If you have more than two columns, you could use functools.reduce: from functools import reduce df = pd.DataFrame({'Name':... | 2 | 2 |
77,843,012 | 2024-1-18 | https://stackoverflow.com/questions/77843012/animating-circles-on-a-matplotlib-plot-for-orbit-simulation-in-python | Intro to the task I am working on a simulating the orbit of moon Phobos around the planet Mars. I have completed the task of using numerical integration to update the velocity and position of both bodies. My final task is to produce an animated plot of the orbit of Phobos, with Mars centred at its initial position. Cod... | ok... with the full code it was a lot easier to see where things go wrong :-) The main problems are: your circles are extremely small! you set an enormous x-extent but keep the y-extent to 0-1 (since your axis does not preserve the aspect-ratio (e.g. ax.set_aspect("equal")) this means your circles look like lines... y... | 2 | 3 |
77,845,596 | 2024-1-19 | https://stackoverflow.com/questions/77845596/i-want-to-check-that-a-certain-list-follows-a-pattern-in-python | I'm building a program that needs to have and input from the user where the user introduces a sequence of numbers separated with commas, example: 1,2,3,4. The sequence can be any amount of numbers, have any number in it and have spaces in between, the only thing that has to be followed is that there's a number then a c... | You can use regular expression re to match the string whether it follows your pattern or not. For example, if your requirement is: Any string where there is a single comma , between digits, can have multiple spaces in between and the string should end with a number or space (I am assuming you don't want to end with a c... | 2 | 2 |
77,844,459 | 2024-1-19 | https://stackoverflow.com/questions/77844459/interpolate-points-over-a-surface | I have a function f(x,y) that I know for certain values of X and Y. Then, I have a new function x,y= g(t) that produces a new series of points X and Y. for those points, using the pre-calculated data I need interpolate. import numpy as np import timeit import matplotlib.pyplot as plt def f(X,Y): return np.sin(X)+np.cos... | I recently shared a solution to a comparable question that is applicable to your case as well. In brief, scipy.interpolate provides a range of 2D interpolation options. In this instance, I utilized RegularGridInterpolator or CloughTocher2DInterpolator, but you also have the option to employ another methods within scipy... | 3 | 1 |
77,841,192 | 2024-1-18 | https://stackoverflow.com/questions/77841192/replacing-values-from-a-given-column-with-the-modified-values-from-a-different-c | I need to update the values of a column (X) in correspondance with certain values ('v') of another column Y with values from another column (Z) times some numbers and then cast the obtained column to int: In pandas the code is as follow: df.loc[df["Y"] == "v", "X"] = ( df.loc[df["Y"] == "v", "Z"] * 1.341 * 15).astype(i... | First, we create a dataframe to operate on. I inferred the context and types from your pandas example. import polars as pl df = pl.DataFrame({ "X": [1, 1, 1, 1, 1], "Y": ["w", "w", "v", "w", "v"], "Z": [1, 2, 3, 4, 5], }) Output. shape: (5, 3) ┌─────┬─────┬─────┐ │ X ┆ Y ┆ Z │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ i64 │ ╞... | 2 | 3 |
77,842,223 | 2024-1-18 | https://stackoverflow.com/questions/77842223/pivoting-based-on-multiple-columns-and-rearrange-data-in-python-dataframe | have a python dataframe. df1 Load Instance_name counter_name counter_value 0 A bytes_read 0 0 A bytes_written 90 0 B bytes_read 100 0 B bytes_Written 90 1 A bytes_read 10 1 A bytes_written 940 1 B bytes_read 1100 1 B bytes_written 910 To simplify view, I need something like below ex. transform counter_name column fiel... | Try this: df.set_index(['Load', 'Instance_name', 'counter_name'])['counter_value'].unstack() Output: counter_name Load Instance_name bytes_Written bytes_read bytes_written 0 0 A NaN 0.0 90.0 1 0 B 90.0 100.0 NaN 2 1 A NaN 10.0 940.0 3 1 B NaN 1100.0 910.0 Note typo in input dataframe bytes_Written and bytes_written. | 2 | 3 |
77,838,888 | 2024-1-18 | https://stackoverflow.com/questions/77838888/overriding-nested-values-in-polyfactory-with-pydantic-models | Is it possible to provide values for complex types generated by polyfactory? I use pydantic for models and pydantic ModelFactory. I noticed that build method supports kwargs that can provide values for constructed model, but I didn't figure if it's possible to provide values for nested fields. For example, if I have mo... | just add another Factory for 'b' example code: from pydantic_factories import ModelFactory from datetime import date, datetime from typing import List, Union, Dict from pydantic import BaseModel, UUID4 class B(BaseModel): k1: int k2: int class Person(BaseModel): id: UUID4 name: str hobbies: List[str] age: Union[float... | 4 | 3 |
77,836,174 | 2024-1-17 | https://stackoverflow.com/questions/77836174/how-can-i-add-a-progress-bar-status-when-creating-a-vector-store-with-langchain | Creating a vector store with the Python library langchain may take a while. How can I add a progress bar? Example of code where a vector store is created with langchain: import pprint from langchain_community.vectorstores import FAISS from langchain_community.embeddings import HuggingFaceEmbeddings from langchain.docs... | Langchain does not natively support any progress bar for this at the moment with release of 1.0.0 I also had similar case, so instead of sending all the documents, I send independent document for ingestion and tracked progress at my end. This was helpful for me. You can do the ingestion in the following way with tqdm(... | 6 | 7 |
77,838,069 | 2024-1-18 | https://stackoverflow.com/questions/77838069/unexpected-method-call-order-in-python-multiple-inheritance | I have a child class named USA and it has two parent classes, A and B. Both parents have a method named change_to_4 and in B.__init__ I call the method, but instead of using the method that I defined in B it uses the A definition of the change_to_4 method. class A: def __init__(self) -> None: self.a = 1 super().__init_... | When the interpreter looks up an attribute of an instance, in this case self.change_to_4 on an instance of USA, it first tries to find 'change_to_4' in self.__dict__, and failing to find it there, the interpreter then follows the method resolution order of USA (USA, A, B, object as shown in the output) to find the chan... | 2 | 3 |
77,835,491 | 2024-1-17 | https://stackoverflow.com/questions/77835491/mypy-type-narrowing-with-recursive-generic-types | Let's say I make a generic class whose objects only contain one value (of type T). T = TypeVar('T') class Contains(Generic[T]): val: T def __init__(self, val: T): self.val = val Note that self.val can itself be a Contains object, so a recursive structure is possible. I want to define a function that will reduce such a... | The problem is that static type checkers are typically unable to infer dynamic type changes from assignments such as: x = x.val As a workaround you can make flatten a recursive function instead to avoid an assignment to x: from typing import TypeVar, Generic, TypeAlias T = TypeVar('T') class Contains(Generic[T]): val:... | 2 | 2 |
77,834,580 | 2024-1-17 | https://stackoverflow.com/questions/77834580/pyside-qt-align-text-in-vertical-center-for-qpushbutton | How can I vertically align the text in a large font QPushButton? For example this Python code creates a button where the text is not vertically aligned. I have tried everything I can think of to solve it but I can't get it working. from PySide2 import QtCore, QtGui, QtWidgets button = QtWidgets.QPushButton("+") # "a" o... | For example this Python code creates a button where the text is not vertically aligned. In reality, the text is vertically aligned: you are not considering how text is normally rendered. Brief sum of vertical font elements When dealing with text drawing, the font metrics (see typeface anatomy) should always be consid... | 2 | 4 |
77,835,940 | 2024-1-17 | https://stackoverflow.com/questions/77835940/is-there-a-way-to-add-only-specific-elements-of-two-numpy-arrays-together | I am attempting to add together specific elements of two numpy arrays. For example consider these two arrays: f1 = np.array([ [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]] ]) f2 = np.array([ [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], ... | You can index the desired position before computing the sum: (f1[...,0]+f2[...,0])/2 Output: array([[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]]) | 2 | 4 |
77,834,081 | 2024-1-17 | https://stackoverflow.com/questions/77834081/pil-not-working-on-python-3-12-even-though-its-installed-and-up-to-date-and | I've upgraded from Python 3.8 32 bit to 3.12 64 bit because of memory limitations. However, the module PIL isn't being recognised, with this error: Traceback (most recent call last): File "C:\Users\rhann\Desktop\Scripts\langton's ant.py", line 2, in <module> from PIL import Image ModuleNotFoundError: No module named 'P... | Each version of Python (and each virtualenv) has a separate set of installed packages -- so just running pip3 will install a package for one Python 3.x environment (usually, but not always, the same one that python3 will start an interpreter for), not every Python 3.x environment. As an alternative to invoking pip3 via... | 3 | 5 |
77,833,699 | 2024-1-17 | https://stackoverflow.com/questions/77833699/invoking-function-after-keyboardinterrupt | Is is possible to invoke a function in a KeyboardInterrupt after pressing CTRL+C? I have following code: try: #other code except KeyboardInterrupt: GPIO.cleanup() finally: print(summary.getSummary()) I have also tried putting the print(summary.getSummary) before the GPIO.cleanup() inside the exception, but the program... | Catching KeyboardInterrupt should work as expected: import time try: while True: print("Sleeping") time.sleep(1) except KeyboardInterrupt as ki: print("\nCaught KeyboardInterrupt") finally: print("Finally here") prints: ^C Sleeping Caught KeyboardInterrupt Finally here It is possible that the code in the try block is... | 2 | 2 |
77,831,595 | 2024-1-17 | https://stackoverflow.com/questions/77831595/ax-set-facecolor-between-angles-in-a-polar-plot | Say I have a standard matplotlib polar plot: import matplotlib.pyplot as plt import numpy as np r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax. Plot(theta, r) ax.set_rmax(2) ax.set_rticks([0.5, 1, 1.5, 2]) # Less radial ticks ax.set_rlabel_position(-22.5) #... | You can use axvspan(...) to color between two angles (in radians). import matplotlib.pyplot as plt import numpy as np r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.plot(theta, r) ax.set_rmax(2) ax.set_rticks([0.5, 1, 1.5, 2]) # Less radial ticks ax.set_rla... | 2 | 2 |
77,832,241 | 2024-1-17 | https://stackoverflow.com/questions/77832241/polars-dataframe-sorting-based-on-absolute-value-of-a-column | I would like to sort a polars dataframe based on absolute value of a column in either ascending or descending order. It is easy to do in Pandas, or using sorted function in python. Let's say I want to sort based on val column in the below dataframe. import numpy as np np.random.seed(42) import polars as pl df = pl.Data... | You want to sort based on the absolute value of 'val'? Expressions are your friend, no need for temporary columns: In [33]: df.sort(pl.col('val').abs()) Out[33]: shape: (6, 3) ┌──────┬─────┬─────┐ │ name ┆ id ┆ val │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ╞══════╪═════╪═════╡ │ two ┆ B ┆ 0 │ │ two ┆ C ┆ -3 │ │ one ┆ C... | 2 | 5 |
77,831,751 | 2024-1-17 | https://stackoverflow.com/questions/77831751/how-can-i-merge-two-dataframes-keeping-overlapping-values-and-nan-for-other-val | I've got two dataframes, one of which is a timestamp, and the other also has timestamps, but has gaps in it. The two dataframes have some overlap in timestamps, and some not. MWE: This code creates the first dataframe: daterange = pd.date_range(start='1/1/2023 09:30:00', end='1/3/2023 09:35:00', freq = 'min') daterange... | Do you missed to convert timestamp of your second dataframe to datetime64? seconddf['timestamp'] = pd.to_datetime(seconddf['timestamp']) out = firstdf.merge(seconddf, on='timestamp', how='left') Output: >>> out timestamp value 0 2023-01-01 09:30:00 3.0 1 2023-01-01 09:31:00 NaN 2 2023-01-01 09:32:00 5.0 3 2023-01-01 0... | 2 | 3 |
77,829,681 | 2024-1-17 | https://stackoverflow.com/questions/77829681/scikit-learn-and-scipy-yield-diverging-cosine-distances-after-removing-featur | When we take an N x M matrix with N observations and M features, a common task is to compute pairwise distances between the N observations, resulting in an N x N distance matrix. The popular Python libraries scipy and scikit-learn both provide methods for performing this task and we expect them to yield the same result... | There are a few diagnostics you can try in this situation. One diagnostic you can try is to plot the places where the two methods of computing distance disagree. # Modified version of test_equivalence() that returns boolean matrix of disagreements def test_equivalence(arr: np.array, metric="cosine"): scipy_result = squ... | 2 | 2 |
77,792,905 | 2024-1-10 | https://stackoverflow.com/questions/77792905/pyside2-load-svg-from-variable-rather-than-from-file | I want to display an svg file using PySide. But I would prefer not having to create a file.svg and then load it using QSvgWidget Rather I just have the file contents of the file.svg contents already stored in a variable as a string. How would I go about directly loading the SVG from the variable rather than form the fi... | You need to convert the string to a QByteArray. From the QSvgWidget.load documentation: PySide6.QtSvgWidgets.QSvgWidget.load(contents) PARAMETERS: contents – PySide6.QtCore.QByteArray Here's a full demo: from PySide6.QtWidgets import QApplication from PySide6.QtSvgWidgets import QSvgWidget from PySide6.QtCore import ... | 2 | 2 |
77,823,218 | 2024-1-16 | https://stackoverflow.com/questions/77823218/how-to-know-if-virtual-environment-is-working-in-vs-code | I’ve read through VS Code’s documentation on creating a virtual environment and I’ve used the venv command to do so, but how do I know if my current Python files are working using that Virtual Environment? In the folder I’m saving my .py files in, I see the .venv folder which was created. Is that it or is there more to... | You want to check if you are in the venv or not: Type which python into VS Code's integrated terminal. If you are using the venv, it will show the path to the python executable inside the venv. For example, for me, the .venv folder is located in /Users/lion/example_folder, but for you the path would be different. If t... | 3 | 3 |
77,807,142 | 2024-1-12 | https://stackoverflow.com/questions/77807142/attributeerror-calling-operator-bpy-ops-import-scene-obj-error-could-not-be | I am trying to write a python script that will convert triangular-mesh objects to quad-mesh objects. For example, image (a) will be my input (.obj/.stl) file and image (b) will be the output. I am a noob with mesh-algorithms or how they work all together. So, far this is the script I have written: import bpy inp = 'mu... | Turns out bpy.ops.import_scene.obj was removed at bpy==4 which is the latest blender-api for python, hence the error. In bpy>4 you have to use bpy.ops.wm.obj_import(filepath='') I just downgraded to bpy==3.60 to import object directly in the current scene. pip install bpy==3.6.0 I also modified my script to take input... | 10 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.