id
stringlengths
16
145
text
stringlengths
1
179k
title
stringclasses
1 value
pydantic/pydantic_2_6.txt
: Union[Annotated[Cat, Tag('cat')], Annotated[Dog, Tag('dog')]] = Field( discriminator=Discriminator(pet_discriminator) ) print(repr(Model.model_validate({'pet': {'pet_type': 'cat', 'age': 12}}))) #> Model(pet=Cat(pet_type='cat', age=12)) print(repr(Model.model_validate({'...
pydantic/73572_10_0.txt
Collaborate outside of code Explore
pydantic/models8_85_0.txt
` pydantic.root_model.RootModel ` Pydantic models can be defined with a "custom root type" by subclassing ` pydantic.RootModel ` .
pydantic/models8_99_0.txt
Here ` a ` , ` b ` and ` c ` are all required. However, this use of ` b: int = ... ` does not work properly with mypy , and as of v1.0 should be avoided in most cases. Note
pydantic/64910_47_0.txt
Parse zero-length timedeltas as ` timedelta(seconds=0.0) ` . ### Python, Pydantic & OS Version
pydantic/datetime6_13_0.txt
* ` timedelta ` ; an existing ` timedelta ` object * ` int ` or ` float ` ; assumed to be seconds * ` str ` ; the following formats are accepted:
pydantic/models8_118_0.txt
To be included in the signature, a field's alias or name must be a valid Python identifier. Pydantic will prioritize a field's alias over its name when generating the signature, but may use the field name if the alias is not a valid Python identifier. If a field's alias and name are both not valid identifiers (which...
pydantic/models8_37_0.txt
When using attributes to parse models, model instances will be created from both top-level attributes and deeper-nested attributes as appropriate. Here is an example demonstrating the principle:
pydantic/datetime6_19_0.txt
like ` datetime ` , with the constraint that the value must lack timezone info Made with Material for MkDocs
pydantic/64910_59_0.txt
Copy link Member
pydantic/pydantic_1_12.txt
__base__=FooModel, ) print(BarModel) #> <class '__main__.BarModel'> print(BarModel.model_fields.keys()) #> dict_keys(['foo', 'bar', 'apple', 'banana']) You can also add validators by passing a dict to the ` __validators__ ` argument. from pydantic import ValidationError, cre...
pydantic/64910_53_0.txt
Member ###
pydantic/models8_72_0.txt
from typing import Generic from typing_extensions import TypeVar from pydantic import BaseModel TBound = TypeVar('TBound', bound=BaseModel) TNoBound = TypeVar('TNoBound') class IntValue(BaseModel): value: int class ItemBound(BaseModel, Gen...
pydantic/64910_18_0.txt
* Topics * Trending * Collections * Pricing
pydantic/models8_94_0.txt
Pydantic models can be used alongside Python's Abstract Base Classes (ABCs). import abc from pydantic import BaseModel class FooBarModel(BaseModel, abc.ABC): a: str b: int @abc.abstractmethod def my_abstract_method(self): pass
pydantic/pydantic_2_3.txt
rname') user = User(name='johndoe') # (1)! 1. VSCode will show a warning here. To "trick" VSCode into preferring the field name, you can use the ` str ` function to wrap the alias value. With this approach, though, a warning is shown when instantiating a model using the alias for the field: ...
pydantic/73572_31_0.txt
New issue Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
pydantic/73572_45_0.txt
### Python, Pydantic & OS Version pydantic version: 2.3.0 pydantic-core version: 2.6.3 pydantic-core build: profile=release pgo=false install path: /Users/jd/Projects/[REDACTED]/.venv/lib/python3.9/site-packages/pydantic python version: 3...
pydantic/64910_12_0.txt
For * Enterprise * Teams * Startups * Education
pydantic/pydantic_1_11.txt
rt BaseModel, SerializeAsAny class ErrorDetails(BaseModel): foo: str ErrorDataT = TypeVar('ErrorDataT', default=ErrorDetails) class Error(BaseModel, Generic[ErrorDataT]): message: str details: Optional[ErrorDataT] class MyErrorDetails(Error...
pydantic/pydantic_1_1.txt
* [ pydantic_core ](../../api/pydantic_core/) * [ pydantic_core.core_schema ](../../api/pydantic_core_schema/) * [ Pydantic Settings ](../../api/pydantic_settings/) * Pydantic Extra Types Pydantic Extra Types * [ Color ](../../api/pydantic_extra_types_color/) * [ Country ](../../...
pydantic/73572_9_0.txt
Plan and track work * Discussions
pydantic/pydantic_4_9.txt
raise TypeError('RestrictCharacters can only be applied to strings') return core_schema.no_info_after_validator_function( self.validate, schema, ) def validate(self, value: str) -> str: if any(c not in self.alphabet for c in v...
pydantic/models8_126_0.txt
If you want this to raise an error, you can achieve this via ` model_config ` : from pydantic import BaseModel, ConfigDict, ValidationError class Model(BaseModel): x: int model_config = ConfigDict(extra='forbid') try: Model(x=1, y='a') except V...
pydantic/models8_83_0.txt
To pickle a dynamically created model: * the model must be defined globally * it must provide ` __module__ `
pydantic/models8_59_0.txt
Pydantic's generics also integrate properly with type checkers, so you get all the type checking you would expect if you were to declare a distinct type for each parametrization. Note
pydantic/64910_23_0.txt
Cancel Submit feedback # Saved searches
pydantic/64910_45_0.txt
from pydantic import BaseModel from datetime import timedelta class MyModel(BaseModel): delta: timedelta = timedelta(seconds=0.0) m = MyModel() print(m.model_dump_json()) # {"delta":"P"} MyModel.model_validate_json(m.model_dump_json()) Above code...
pydantic/models8_38_0.txt
from typing import List from pydantic import BaseModel, ConfigDict class PetCls: def __init__(self, *, name: str, species: str): self.name = name self.species = species class PersonCls: def __init__(self, *, name: str, age: float...
pydantic/models8_52_0.txt
The ` _fields_set ` keyword argument to ` model_construct() ` is optional, but allows you to be more precise about which fields were originally set and which weren't. If it's omitted ` model_fields_set ` will just be the keys of the data provided. For example, in the example above, if ` _fields_set ` was not provide...
pydantic/pydantic_4_6.txt
h it's not being checked upon parsing, you can use variadic arguments to [ ` Field ` ](../../api/fields/#pydantic.fields.Field) with the raw schema attribute name: from pydantic import BaseModel, Field, PositiveInt try: # this won't work since `PositiveInt` takes precedence over the ...
pydantic/pydantic_1_14.txt
to required and nullable fields. ## Fields with non-hashable default values ¶ A common source of bugs in python is to use a mutable object as a default value for a function or method argument, as the same instance ends up being reused in each call. The ` dataclasses ` module actually raises an error in this case,...
pydantic/models8_50_0.txt
In Pydantic V2, the performance gap between ` BaseModel.__init__ ` and ` BaseModel.model_construct ` has been narrowed considerably. For simple models, calling ` BaseModel.__init__ ` may even be faster. If you are using ` model_construct() ` for performance reasons, you may want to profile your use case before assumin...
pydantic/datetime6_10_0.txt
* ` date ` ; an existing ` date ` object * ` int ` or ` float ` ; handled the same as described for ` datetime ` above * ` str ` ; the following formats are accepted:
pandas_user_guide/pandas_user_guide_6_3.txt
reference/api/pandas.DataFrame.sparse.to_coo.html#pandas.DataFrame.sparse.to_coo "pandas.DataFrame.sparse.to_coo") method: In [43]: sdf.sparse.to_coo() Out[43]: <1000x5 sparse matrix of type '<class 'numpy.float64'>' with 517 stored elements in COOrdinate format> [ ` Series.sparse.to_...
pandas_user_guide/pandas_user_guide_5_29.txt
* Assigning to the ` index ` or ` columns ` attributes. * For homogeneous data, directly modifying the values via the ` values ` attribute or advanced indexing. To be clear, no pandas method has the side effect of modifying your data; almost every method returns a new object, leaving the original object untou...
pandas_user_guide/pandas_user_guide_2_18.txt
e next day In [209]: pd.Timestamp("2014-08-01 16:30") + bh Out[209]: Timestamp('2014-08-04 09:30:00') # Adding 2 business hours In [210]: pd.Timestamp("2014-08-01 10:00") + pd.offsets.BusinessHour(2) Out[210]: Timestamp('2014-08-01 12:00:00') # Subtracting 3 business hours In [211]...
pandas_user_guide/pandas_user_guide_24_4.txt
./reference/api/pandas.DataFrame.map.html) . ## Table Styles # Table styles are flexible enough to control all individual parts of the table, including column headers and indexes. However, they can be unwieldy to type for individual data cells or for any kind of conditional formatting, so we recommend that table s...
pandas_user_guide/pandas_user_guide_24_19.txt
22775 | -1.183865 | 1.455173 | 1.134328 | 0.239403 | -0.837991 | -1.130932 | 0.783168 | 1.845520 | 1.437072 | -1.198443 | 1.379098 | 2.129113 | 0.260096 | -0.011975 | 0.043302 | 0.722941 | 1.028152 | -0.235806 | 1.145245 | -1.359598 | 0.232189 | 0.503712 | -0.614264 | -0....
pandas_user_guide/pandas_user_guide_25_3.txt
02 1.212112 -0.173215 2000-01-03 -0.861849 -2.104569 2000-01-04 0.721555 -0.706771 2000-01-05 -0.424972 0.567020 2000-01-06 -0.673690 0.113648 2000-01-07 0.404705 0.577046 2000-01-08 -0.370647 -1.157892 In [15]: df.iloc[:, [1, 0]] = df[['A', 'B']] In [16]: df[['A','B']] ...
pandas_user_guide/tutorialbasicvectori_9_0.txt
Email or phone
pandas_user_guide/tutorialbasicvectori_66_0.txt
Like
pandas_user_guide/pandas_user_guide_25_22.txt
` / ` != ` works similarly to ` in ` / ` not in ` . In [275]: df.query('b == ["a", "b", "c"]') Out[275]: a b c d 0 a a 2 6 1 a a 4 7 2 b a 1 6 3 b a 2 1 4 c b 3 6 5 c b 0 2 6 d b 3 3 7 d b 2 1 8 e c 4 3...
pandas_user_guide/howtospeeduppythonpa_182_0.txt
#### Have any questions?
pandas_user_guide/pandas_user_guide_2_25.txt
d to looking ahead, where the value for a later time is pulled back to a previous time as in the following example with the [ ` BusinessDay ` ](../reference/api/pandas.tseries.offsets.BusinessDay.html#pandas.tseries.offsets.BusinessDay "pandas.tseries.offsets.BusinessDay") frequency: In [300]: s = pd.da...
pandas_user_guide/pandas_user_guide_4_11.txt
rgument. In [206]: a = pd.Categorical(["a", "b", "c"], ordered=True) In [207]: b = pd.Categorical(["c", "b", "a"], ordered=True) In [208]: union_categoricals([a, b], ignore_order=True) Out[208]: ['a', 'b', 'c', 'c', 'b', 'a'] Categories (3, object): ['a', 'b', 'c'] [ ...
pandas_user_guide/howtospeeduppythonpa_49_0.txt
Our last and final way to evaluate this dataset is to use vectorization. We will call our dataset and apply the default reward being ‘bad_karma’ to the entire data frame. Then we will only check for those that satisfy our parameters using boolean indexing. Think of it like setting a true/false value for each row. If an...
pandas_user_guide/pandas_user_guide_5_7.txt
pandas/core/ops/common.py:76, in _unpack_zerodim_and_defer.<locals>.new_method(self, other) 72 return NotImplemented 74 other = item_from_zerodim(other) ---> 76 return method(self, other) File ~/work/pandas/pandas/pandas/core/arraylike.py:40, in OpsMixin.__eq__(self, other) ...
pandas_user_guide/vectorizationinpanda_38_0.txt
Output: 0 1 1 4 2 9
pandas_user_guide/pandas_user_guide_23_5.txt
0 1 2 2 1.0 2 3.0 In [86]: df.dropna(axis=1) Out[86]: 1 0 1 1 2 2 2 In [87]: ser = pd.Series([1, pd.NA], dtype="int64[pyarrow]") In [88]: ser.dropna() Out[88]: 0 1 dtype: int64[pyarrow] ## Filling missing data # ### Fill...
pandas_user_guide/pandas_user_guide_10_4.txt
f axes ` 'dict' ` | No | dict of artists ` 'dict' ` | Yes | Series of dicts of artists ` 'both' ` | No | namedtuple ` 'both' ` | Yes | Series of namedtuples ` Groupby.boxplot ` always returns a ` Series ` of ` return_type ` . In [61]: np.random.seed(1234) In ...
pandas_user_guide/pandas_user_guide_2_2.txt
011-03 dtype: period[M] In [22]: pd.Series([pd.DateOffset(1), pd.DateOffset(2)]) Out[22]: 0 <DateOffset> 1 <2 * DateOffsets> dtype: object In [23]: pd.Series(pd.date_range("1/1/2011", freq="ME", periods=3)) Out[23]: 0 2011-01-31 1 2011-02-28 2 201...
pandas_user_guide/howtospeeduppythonpa_29_0.txt
Now that we have our dataset and our parameters for what we want to return, we can go ahead and explore the fastest way to execute this type of analysis.
pandas_user_guide/vectorizationinpanda_92_0.txt
Happy coding!
pandas_user_guide/pandasvectorization_7_0.txt
Concepts covered
pandas_user_guide/howtospeeduppythonpa_148_0.txt
## Why Vectorization in Pandas is over 300x Faster
pandas_user_guide/tutorialbasicvectori_4_0.txt
## Sign in to view more content
pandas_user_guide/vectorizationinpanda_76_0.txt
Output: NumPy Vectorized Approach: 0.30273 seconds Traditional Loop-Based Approach: 17.91837 seconds
pandas_user_guide/pandas_user_guide_5_33.txt
inference stored all columns as object, which ` infer_objects ` will correct. > > In [387]: df.infer_objects().dtypes > Out[387]: > 0 int64 > 1 object > 2 datetime64[ns] > dtype: object > The following functions are available for one dimensional object arrays or sc...
pandas_user_guide/pandas_user_guide_26_0.txt
Skip to main content __ Back to top __ ` Ctrl ` \+ ` K ` [ ![pandas 2.2.1 documentation - Home](../_static/pandas.svg) ](../index.html) Site Navigation * [ Getting started ](../getting_started/index.html) * [ User Guide ](index.html) * [ API reference ](../reference/index.html) * [ Development ](../develop...
pandas_user_guide/howtospeeduppythonpa_120_0.txt
### The Parameters and Rules
pandas_user_guide/vectorizationinpanda_113_0.txt
ML Quant Researcher
pandas_user_guide/pandas_user_guide_27_16.txt
s not None: File ~/work/pandas/pandas/pandas/io/parsers/c_parser_wrapper.py:155, in CParserWrapper.__init__(self, src, **kwds) 152 # error: Cannot determine type of 'names' 153 if len(self.names) < len(usecols): # type: ignore[has-type] 154 # error: Cannot determine typ...
pandas_user_guide/pandas_user_guide_27_32.txt
r columns. This is useful for numerical text data that has leading zeros. By default columns that are numerical are cast to numeric types and the leading zeros are lost. To avoid this, we can convert these columns to strings. url_mcc = "https://en.wikipedia.org/wiki/Mobile_country_code?oldid=899173761" ...
pandas_user_guide/pandasvectorization_28_0.txt
In [61]:
pandas_user_guide/howtospeeduppythonpa_17_0.txt
[ Pandas ](https://pandas.pydata.org/docs/) is an essential and popular open- source data manipulation and data analysis library for the Python programming language. Pandas is widely used in various fields such as finance, economics, social sciences, and engineering. It is beneficial for data cleaning, preparation, and...
pandas_user_guide/tutorialbasicvectori_1_0.txt
Agree & Join LinkedIn
pandas_user_guide/pandas_user_guide_5_18.txt
<lambda> sqrt 2000-01-01 0.428759 0.135110 NaN 2000-01-02 0.168731 2.338144 1.156782 2000-01-03 1.621034 1.438107 0.661897 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN ...
pandas_user_guide/vectorizationinpanda_50_0.txt
1. **Efficiency** : Vectorized operations are optimized for performance and are much faster than traditional loop-based operations, especially on large datasets. 2. **Clarity** : Vectorized code is often more concise and easier to read compared to code with explicit loops. 3. **Ease of Use** : You can apply operations ...
pandas_user_guide/vectorizationinpanda_37_0.txt
# Applying the 'square' function to the 'A' column df['A_squared'] = df['A'].apply(square) print(df['A_squared'])
pandas_user_guide/howtospeeduppythonpa_187_0.txt
© 2024 Exxact Corporation | [ Privacy ](/Privacy) | Consent Preferences | [ Cookies ](/Cookies)
pandas_user_guide/pandas_user_guide_21_2.txt
aab dtype: object In [25]: df.groupby("B").A.sum() Out[25]: B 1 3 3 0 Name: A, dtype: Int64 ## Scalar NA Value # [ ` arrays.IntegerArray ` ](../reference/api/pandas.arrays.IntegerArray.html#pandas.arrays.IntegerArray "pandas.arrays.IntegerArray") uses [ ` pandas.NA ` ]...
pandas_user_guide/pandasvectorization_0_0.txt
Toggle navigation [ Ritchie Ng ](/)
pandas_user_guide/howtospeeduppythonpa_125_0.txt
#### Accelerate Training with an Exxact Multi-GPU Workstation
pandas_user_guide/howtospeeduppythonpa_142_0.txt
### Vectorization
pandas_user_guide/howtospeeduppythonpa_71_0.txt
March 7, 2024 9 min read ](/blog/Deep-Learning/managing-python-dependencies- with-poetry-vs-conda-pip)
pandas_user_guide/pandas_user_guide_2_11.txt
pd.Series( .....: [1, 2, 3], .....: pd.DatetimeIndex( .....: ["2011-12-31 23:59:59", "2012-01-01 00:00:00", "2012-01-01 00:00:01"] .....: ), .....: ) .....: In [127]: series_second.index.resolution Out[127]: 'second' In [128]: series_...
pandas_user_guide/howtospeeduppythonpa_32_0.txt
With the latest CPUs and most powerful GPUs available, accelerate your deep learning and AI project optimized to your deployment, budget, and desired performance!
pandas_user_guide/pandas_user_guide_24_6.txt
es cells of negligible value. Since this looks at each element in turn we use ` map ` . [23]: def style_negative(v, props=''): return props if v < 0 else None s2 = df2.style.map(style_negative, props='color:red;')\ .map(lambda v: 'opacity: 20%;' if (v < 0...
pandas_user_guide/pandas_user_guide_22_9.txt
40]: MultiIndex([(1, 0, 0), (1, 1, 0), (0, 0, 0), (1, 0, 1)], names=['a', 'b', 'c']) See also [ ` get_dummies() ` ](../reference/api/pandas.get_dummies.html#pandas.get_dummies "pandas.get_dummies") . ## Method summary # Method | Descriptio...
pandas_user_guide/vectorizationinpanda_29_0.txt
import pandas as pd
pandas_user_guide/pandas_user_guide_7_4.txt
eader engine for 'ods' files. Available options: auto, odf, calamine. [default: auto] [currently: auto] io.excel.ods.writer : string The default Excel writer engine for 'ods' files. Available options: auto, odf. [default: auto] [currently: auto] io.excel.xls.reader : stri...
pandas_user_guide/tutorialbasicvectori_25_0.txt
# Tutorial [Basic]: 700x speed improvement on Pandas with Vectorization vs. Iterrows/Apply
pandas_user_guide/howtospeeduppythonpa_5_0.txt
* Supported Software
pandas_user_guide/tutorialbasicvectori_57_0.txt
To compare the performance of these three methods, we can use the timeit library to measure the execution time for each approach. Let’s see an example:
pandas_user_guide/tutorialbasicvectori_24_0.txt
Vectorization illustrator from https://lappweb.in2p3.fr/~paubert/ASTERICS_HPC/6-6-1-985.html
pandas_user_guide/pandas_user_guide_7_3.txt
a summary view. 'None' value means unlimited. In case python/IPython is running in a terminal and `large_repr` equals 'truncate' this can be set to 0 and pandas will auto-detect the height of the terminal and print a truncated object which fits the screen height. The IPython note...
pandas_user_guide/pandas_user_guide_25_1.txt
book-selection) for some advanced strategies. ## Different choices for indexing # Object selection has had a number of user-requested additions in order to support more explicit location based indexing. pandas now supports three types of multi-axis indexing. * ` .loc ` is primarily label based, but may also be ...
pandas_user_guide/howtospeeduppythonpa_96_0.txt
##### Deep Learning
pandas_user_guide/pandas_user_guide_25_9.txt
take_with_is_copy(key, axis=axis) 1715 except IndexError as err: 1716 # re-raise with different error message, e.g. test_getitem_ndarray_3d File ~/work/pandas/pandas/pandas/core/generic.py:4150, in NDFrame._take_with_is_copy(self, indices, axis) 4141 """ 4142 Internal version of...
pandas_user_guide/howtospeeduppythonpa_37_0.txt
Looping and Iterating is the most basic way to deliver the same calculation row by row. We call the data frame and iterate rows with a new cell called reward and run the calculation to fill in the new ‘reward’ according to our previously defined ‘reward_calc’ code block. This is the most basic and probably the first me...
pandas_user_guide/vectorizationinpanda_57_0.txt
for i in range(len(list1)): result.append(list1[i] + list2[i]) print(result)
pandas_user_guide/pandas_user_guide_25_15.txt
-0.424972 0.276232 -1.087401 NaN NaN 2000-01-06 0.113648 -0.673690 -1.478427 0.524988 7.0 NaN 2000-01-07 0.577046 0.404705 -1.715002 -1.039268 NaN NaN List comprehensions and the ` map ` method of Series can also be used to produce more complex criteria: In [164]: df2 = pd.DataFram...
pandas_user_guide/tutorialbasicvectori_26_0.txt
* [ Report this article ](/uas/login?session_redirect=https%3A%2F%2Fwww.linkedin.com%2Fpulse%2Ftutorial-basic-vectorization-pandas-iterrows-apply-duc-lai-trung-minh-75d4c&trk=article-ssr-frontend-pulse_ellipsis-menu-semaphore-sign-in-redirect&guestReportContentType=PONCHO_ARTICLE&_f=guest-reporting)
pandas_user_guide/pandas_user_guide_19_5.txt
ved ....: if value % 2 == 1: ....: del values[idx] ....: n_removed += 1 ....: else: ....: values[idx] = value + 1 ....: In [31]: values Out[31]: [1, 3, 5] In [32]: def f(s): ....: s = s.copy() .....
pandas_user_guide/pandas_user_guide_7_6.txt
/pandas.set_option.html#pandas.set_option "pandas.set_option") are available from the pandas namespace. To change an option, call ` set_option('option regex', new_value) ` . In [12]: pd.get_option("mode.sim_interactive") Out[12]: False In [13]: pd.set_option("mode.sim_interactive", True) ...
pandas_user_guide/pandas_user_guide_25_17.txt
In addition, ` where ` takes an optional ` other ` argument for replacement of values where the condition is False, in the returned copy. In [200]: df.where(df < 0, -df) Out[200]: A B C D 2000-01-01 -2.104139 -1.309525 -0.485855 -0.245166 ...
pandas_user_guide/vectorizationinpanda_10_0.txt
[ ![Gaurav Kumar](https://miro.medium.com/v2/resize:fill:88:88/2*xAplm3pOe1nTES_QmVagIQ.jpeg) ](https://gaurav-adarshi.medium.com/?source=post_page----- 3a4fda08a184--------------------------------) [ ![Python in Plain English](https://miro.medium.com/v2/resize:fill:48:48/1*VA3oGfprJgj5fRsTjXp6fA@2x.png) ](https://pyth...
pandas_user_guide/pandas_user_guide_2_20.txt
) ` ](../reference/api/pandas.date_range.html#pandas.date_range "pandas.date_range") and [ ` bdate_range() ` ](../reference/api/pandas.bdate_range.html#pandas.bdate_range "pandas.bdate_range") will only return the valid timestamps between the ` start_date ` and ` end_date ` . If these are not valid timestamps for t...
pandas_user_guide/howtospeeduppythonpa_93_0.txt
#### Access Open Source LLMs Anywhere - Mobile LLMs with Ollama