language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | kamyu104__LeetCode-Solutions | Python/delete-columns-to-make-sorted.py | {
"start": 430,
"end": 735
} | class ____(object):
def minDeletionSize(self, A):
"""
:type A: List[str]
:rtype: int
"""
result = 0
for col in itertools.izip(*A):
if any(col[i] > col[i+1] for i in xrange(len(col)-1)):
result += 1
return result
| Solution2 |
python | getsentry__sentry | src/sentry/seer/endpoints/group_ai_summary.py | {
"start": 714,
"end": 1692
} | class ____(GroupAiEndpoint):
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ML_AI
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={
"POST": {
RateLimitCategory.IP: RateLimit(limit=20, window=60),
RateLimitCategory.USER: RateLimit(limit=20, window=60),
RateLimitCategory.ORGANIZATION: RateLimit(limit=100, window=60),
}
}
)
def post(self, request: Request, group: Group) -> Response:
data = orjson.loads(request.body) if request.body else {}
force_event_id = data.get("event_id", None)
summary_data, status_code = get_issue_summary(
group=group,
user=request.user,
force_event_id=force_event_id,
source=SeerAutomationSource.ISSUE_DETAILS,
)
return Response(summary_data, status=status_code)
| GroupAiSummaryEndpoint |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/_poly_fixtures.py | {
"start": 960,
"end": 10507
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
run_inserts = "once"
run_setup_mappers = "once"
run_deletes = None
label_style = LABEL_STYLE_TABLENAME_PLUS_COL
@classmethod
def define_tables(cls, metadata):
global people, engineers, managers, boss
global companies, paperwork, machines
companies = Table(
"companies",
metadata,
Column(
"company_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(50)),
)
people = Table(
"people",
metadata,
Column(
"person_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("company_id", Integer, ForeignKey("companies.company_id")),
Column("name", String(50)),
Column("type", String(30)),
)
engineers = Table(
"engineers",
metadata,
Column(
"person_id",
Integer,
ForeignKey("people.person_id"),
primary_key=True,
),
Column("status", String(30)),
Column("engineer_name", String(50)),
Column("primary_language", String(50)),
)
machines = Table(
"machines",
metadata,
Column(
"machine_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(50)),
Column("engineer_id", Integer, ForeignKey("engineers.person_id")),
)
managers = Table(
"managers",
metadata,
Column(
"person_id",
Integer,
ForeignKey("people.person_id"),
primary_key=True,
),
Column("status", String(30)),
Column("manager_name", String(50)),
)
boss = Table(
"boss",
metadata,
Column(
"boss_id",
Integer,
ForeignKey("managers.person_id"),
primary_key=True,
),
Column("golf_swing", String(30)),
)
paperwork = Table(
"paperwork",
metadata,
Column(
"paperwork_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("description", String(50)),
Column("person_id", Integer, ForeignKey("people.person_id")),
)
@classmethod
def setup_classes(cls):
cls.classes["Engineer"] = Engineer
cls.classes["Person"] = Person
cls.classes["Manager"] = Manager
cls.classes["Machine"] = Machine
cls.classes["Boss"] = Boss
cls.classes["Company"] = Company
cls.classes["Paperwork"] = Paperwork
@classmethod
def insert_data(cls, connection):
cls.e1 = e1 = Engineer(
name="dilbert",
engineer_name="dilbert",
primary_language="java",
status="regular engineer",
paperwork=[
Paperwork(description="tps report #1"),
Paperwork(description="tps report #2"),
],
machines=[Machine(name="IBM ThinkPad"), Machine(name="IPhone")],
)
cls.e2 = e2 = Engineer(
name="wally",
engineer_name="wally",
primary_language="c++",
status="regular engineer",
paperwork=[
Paperwork(description="tps report #3"),
Paperwork(description="tps report #4"),
],
machines=[Machine(name="Commodore 64")],
)
cls.b1 = b1 = Boss(
name="pointy haired boss",
golf_swing="fore",
manager_name="pointy",
status="da boss",
paperwork=[Paperwork(description="review #1")],
)
cls.m1 = m1 = Manager(
name="dogbert",
manager_name="dogbert",
status="regular manager",
paperwork=[
Paperwork(description="review #2"),
Paperwork(description="review #3"),
],
)
cls.e3 = e3 = Engineer(
name="vlad",
engineer_name="vlad",
primary_language="cobol",
status="elbonian engineer",
paperwork=[Paperwork(description="elbonian missive #3")],
machines=[Machine(name="Commodore 64"), Machine(name="IBM 3270")],
)
cls.c1 = c1 = Company(name="MegaCorp, Inc.")
c1.employees = [e1, e2, b1, m1]
cls.c2 = c2 = Company(name="Elbonia, Inc.")
c2.employees = [e3]
with sessionmaker(connection, expire_on_commit=False).begin() as sess:
sess.add(c1)
sess.add(c2)
cls.all_employees = [e1, e2, b1, m1, e3]
cls.c1_employees = [e1, e2, b1, m1]
cls.c2_employees = [e3]
def _company_with_emps_machines_fixture(self):
fixture = self._company_with_emps_fixture()
fixture[0].employees[0].machines = [
Machine(name="IBM ThinkPad"),
Machine(name="IPhone"),
]
fixture[0].employees[1].machines = [Machine(name="Commodore 64")]
return fixture
def _company_with_emps_fixture(self):
return [
Company(
name="MegaCorp, Inc.",
employees=[
Engineer(
name="dilbert",
engineer_name="dilbert",
primary_language="java",
status="regular engineer",
),
Engineer(
name="wally",
engineer_name="wally",
primary_language="c++",
status="regular engineer",
),
Boss(
name="pointy haired boss",
golf_swing="fore",
manager_name="pointy",
status="da boss",
),
Manager(
name="dogbert",
manager_name="dogbert",
status="regular manager",
),
],
),
Company(
name="Elbonia, Inc.",
employees=[
Engineer(
name="vlad",
engineer_name="vlad",
primary_language="cobol",
status="elbonian engineer",
)
],
),
]
def _emps_wo_relationships_fixture(self):
return [
Engineer(
name="dilbert",
engineer_name="dilbert",
primary_language="java",
status="regular engineer",
),
Engineer(
name="wally",
engineer_name="wally",
primary_language="c++",
status="regular engineer",
),
Boss(
name="pointy haired boss",
golf_swing="fore",
manager_name="pointy",
status="da boss",
),
Manager(
name="dogbert",
manager_name="dogbert",
status="regular manager",
),
Engineer(
name="vlad",
engineer_name="vlad",
primary_language="cobol",
status="elbonian engineer",
),
]
@classmethod
def setup_mappers(cls):
cls.mapper(
Company,
companies,
properties={
"employees": relationship(Person, order_by=people.c.person_id)
},
)
cls.mapper(Machine, machines)
(
person_with_polymorphic,
manager_with_polymorphic,
) = cls._get_polymorphics()
cls.mapper(
Person,
people,
with_polymorphic=person_with_polymorphic,
polymorphic_on=people.c.type,
polymorphic_identity="person",
properties={
"paperwork": relationship(
Paperwork, order_by=paperwork.c.paperwork_id
)
},
)
cls.mapper(
Engineer,
engineers,
inherits=Person,
polymorphic_identity="engineer",
properties={
"company": relationship(Company, viewonly=True),
"machines": relationship(
Machine, order_by=machines.c.machine_id
),
},
)
cls.mapper(
Manager,
managers,
with_polymorphic=manager_with_polymorphic,
inherits=Person,
polymorphic_identity="manager",
)
cls.mapper(Boss, boss, inherits=Manager, polymorphic_identity="boss")
cls.mapper(Paperwork, paperwork)
| _PolymorphicFixtureBase |
python | google__flatbuffers | tests/MyGame/Example/Monster.py | {
"start": 51119,
"end": 84511
} | class ____(object):
# MonsterT
def __init__(
self,
pos = None,
mana = 150,
hp = 100,
name = None,
inventory = None,
color = 8,
testType = 0,
test = None,
test4 = None,
testarrayofstring = None,
testarrayoftables = None,
enemy = None,
testnestedflatbuffer = None,
testempty = None,
testbool = False,
testhashs32Fnv1 = 0,
testhashu32Fnv1 = 0,
testhashs64Fnv1 = 0,
testhashu64Fnv1 = 0,
testhashs32Fnv1a = 0,
testhashu32Fnv1a = 0,
testhashs64Fnv1a = 0,
testhashu64Fnv1a = 0,
testarrayofbools = None,
testf = 3.14159,
testf2 = 3.0,
testf3 = 0.0,
testarrayofstring2 = None,
testarrayofsortedstruct = None,
flex = None,
test5 = None,
vectorOfLongs = None,
vectorOfDoubles = None,
parentNamespaceTest = None,
vectorOfReferrables = None,
singleWeakReference = 0,
vectorOfWeakReferences = None,
vectorOfStrongReferrables = None,
coOwningReference = 0,
vectorOfCoOwningReferences = None,
nonOwningReference = 0,
vectorOfNonOwningReferences = None,
anyUniqueType = 0,
anyUnique = None,
anyAmbiguousType = 0,
anyAmbiguous = None,
vectorOfEnums = None,
signedEnum = -1,
testrequirednestedflatbuffer = None,
scalarKeySortedTables = None,
nativeInline = None,
longEnumNonEnumDefault = 0,
longEnumNormalDefault = 2,
nanDefault = float('nan'),
infDefault = float('inf'),
positiveInfDefault = float('inf'),
infinityDefault = float('inf'),
positiveInfinityDefault = float('inf'),
negativeInfDefault = float('-inf'),
negativeInfinityDefault = float('-inf'),
doubleInfDefault = float('inf'),
):
self.pos = pos # type: Optional[MyGame.Example.Vec3.Vec3T]
self.mana = mana # type: int
self.hp = hp # type: int
self.name = name # type: Optional[str]
self.inventory = inventory # type: Optional[List[int]]
self.color = color # type: int
self.testType = testType # type: int
self.test = test # type: Union[None, 'MyGame.Example.Monster.MonsterT', 'MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT', 'MyGame.Example2.Monster.MonsterT']
self.test4 = test4 # type: Optional[List[MyGame.Example.Test.TestT]]
self.testarrayofstring = testarrayofstring # type: Optional[List[Optional[str]]]
self.testarrayoftables = testarrayoftables # type: Optional[List[MyGame.Example.Monster.MonsterT]]
self.enemy = enemy # type: Optional[MyGame.Example.Monster.MonsterT]
self.testnestedflatbuffer = testnestedflatbuffer # type: Optional[List[int]]
self.testempty = testempty # type: Optional[MyGame.Example.Stat.StatT]
self.testbool = testbool # type: bool
self.testhashs32Fnv1 = testhashs32Fnv1 # type: int
self.testhashu32Fnv1 = testhashu32Fnv1 # type: int
self.testhashs64Fnv1 = testhashs64Fnv1 # type: int
self.testhashu64Fnv1 = testhashu64Fnv1 # type: int
self.testhashs32Fnv1a = testhashs32Fnv1a # type: int
self.testhashu32Fnv1a = testhashu32Fnv1a # type: int
self.testhashs64Fnv1a = testhashs64Fnv1a # type: int
self.testhashu64Fnv1a = testhashu64Fnv1a # type: int
self.testarrayofbools = testarrayofbools # type: Optional[List[bool]]
self.testf = testf # type: float
self.testf2 = testf2 # type: float
self.testf3 = testf3 # type: float
self.testarrayofstring2 = testarrayofstring2 # type: Optional[List[Optional[str]]]
self.testarrayofsortedstruct = testarrayofsortedstruct # type: Optional[List[MyGame.Example.Ability.AbilityT]]
self.flex = flex # type: Optional[List[int]]
self.test5 = test5 # type: Optional[List[MyGame.Example.Test.TestT]]
self.vectorOfLongs = vectorOfLongs # type: Optional[List[int]]
self.vectorOfDoubles = vectorOfDoubles # type: Optional[List[float]]
self.parentNamespaceTest = parentNamespaceTest # type: Optional[MyGame.InParentNamespace.InParentNamespaceT]
self.vectorOfReferrables = vectorOfReferrables # type: Optional[List[MyGame.Example.Referrable.ReferrableT]]
self.singleWeakReference = singleWeakReference # type: int
self.vectorOfWeakReferences = vectorOfWeakReferences # type: Optional[List[int]]
self.vectorOfStrongReferrables = vectorOfStrongReferrables # type: Optional[List[MyGame.Example.Referrable.ReferrableT]]
self.coOwningReference = coOwningReference # type: int
self.vectorOfCoOwningReferences = vectorOfCoOwningReferences # type: Optional[List[int]]
self.nonOwningReference = nonOwningReference # type: int
self.vectorOfNonOwningReferences = vectorOfNonOwningReferences # type: Optional[List[int]]
self.anyUniqueType = anyUniqueType # type: int
self.anyUnique = anyUnique # type: Union[None, 'MyGame.Example.Monster.MonsterT', 'MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT', 'MyGame.Example2.Monster.MonsterT']
self.anyAmbiguousType = anyAmbiguousType # type: int
self.anyAmbiguous = anyAmbiguous # type: Union[None, 'MyGame.Example.Monster.MonsterT', 'MyGame.Example.Monster.MonsterT', 'MyGame.Example.Monster.MonsterT']
self.vectorOfEnums = vectorOfEnums # type: Optional[List[int]]
self.signedEnum = signedEnum # type: int
self.testrequirednestedflatbuffer = testrequirednestedflatbuffer # type: Optional[List[int]]
self.scalarKeySortedTables = scalarKeySortedTables # type: Optional[List[MyGame.Example.Stat.StatT]]
self.nativeInline = nativeInline # type: Optional[MyGame.Example.Test.TestT]
self.longEnumNonEnumDefault = longEnumNonEnumDefault # type: int
self.longEnumNormalDefault = longEnumNormalDefault # type: int
self.nanDefault = nanDefault # type: float
self.infDefault = infDefault # type: float
self.positiveInfDefault = positiveInfDefault # type: float
self.infinityDefault = infinityDefault # type: float
self.positiveInfinityDefault = positiveInfinityDefault # type: float
self.negativeInfDefault = negativeInfDefault # type: float
self.negativeInfinityDefault = negativeInfinityDefault # type: float
self.doubleInfDefault = doubleInfDefault # type: float
@classmethod
def InitFromBuf(cls, buf, pos):
monster = Monster()
monster.Init(buf, pos)
return cls.InitFromObj(monster)
@classmethod
def InitFromPackedBuf(cls, buf, pos=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
return cls.InitFromBuf(buf, pos+n)
@classmethod
def InitFromObj(cls, monster):
x = MonsterT()
x._UnPack(monster)
return x
# MonsterT
def _UnPack(self, monster):
if monster is None:
return
if monster.Pos() is not None:
self.pos = MyGame.Example.Vec3.Vec3T.InitFromObj(monster.Pos())
self.mana = monster.Mana()
self.hp = monster.Hp()
self.name = monster.Name()
if not monster.InventoryIsNone():
if np is None:
self.inventory = []
for i in range(monster.InventoryLength()):
self.inventory.append(monster.Inventory(i))
else:
self.inventory = monster.InventoryAsNumpy()
self.color = monster.Color()
self.testType = monster.TestType()
self.test = MyGame.Example.Any.AnyCreator(self.testType, monster.Test())
if not monster.Test4IsNone():
self.test4 = []
for i in range(monster.Test4Length()):
if monster.Test4(i) is None:
self.test4.append(None)
else:
test_ = MyGame.Example.Test.TestT.InitFromObj(monster.Test4(i))
self.test4.append(test_)
if not monster.TestarrayofstringIsNone():
self.testarrayofstring = []
for i in range(monster.TestarrayofstringLength()):
self.testarrayofstring.append(monster.Testarrayofstring(i))
if not monster.TestarrayoftablesIsNone():
self.testarrayoftables = []
for i in range(monster.TestarrayoftablesLength()):
if monster.Testarrayoftables(i) is None:
self.testarrayoftables.append(None)
else:
monster_ = MyGame.Example.Monster.MonsterT.InitFromObj(monster.Testarrayoftables(i))
self.testarrayoftables.append(monster_)
if monster.Enemy() is not None:
self.enemy = MyGame.Example.Monster.MonsterT.InitFromObj(monster.Enemy())
if not monster.TestnestedflatbufferIsNone():
if np is None:
self.testnestedflatbuffer = []
for i in range(monster.TestnestedflatbufferLength()):
self.testnestedflatbuffer.append(monster.Testnestedflatbuffer(i))
else:
self.testnestedflatbuffer = monster.TestnestedflatbufferAsNumpy()
if monster.Testempty() is not None:
self.testempty = MyGame.Example.Stat.StatT.InitFromObj(monster.Testempty())
self.testbool = monster.Testbool()
self.testhashs32Fnv1 = monster.Testhashs32Fnv1()
self.testhashu32Fnv1 = monster.Testhashu32Fnv1()
self.testhashs64Fnv1 = monster.Testhashs64Fnv1()
self.testhashu64Fnv1 = monster.Testhashu64Fnv1()
self.testhashs32Fnv1a = monster.Testhashs32Fnv1a()
self.testhashu32Fnv1a = monster.Testhashu32Fnv1a()
self.testhashs64Fnv1a = monster.Testhashs64Fnv1a()
self.testhashu64Fnv1a = monster.Testhashu64Fnv1a()
if not monster.TestarrayofboolsIsNone():
if np is None:
self.testarrayofbools = []
for i in range(monster.TestarrayofboolsLength()):
self.testarrayofbools.append(monster.Testarrayofbools(i))
else:
self.testarrayofbools = monster.TestarrayofboolsAsNumpy()
self.testf = monster.Testf()
self.testf2 = monster.Testf2()
self.testf3 = monster.Testf3()
if not monster.Testarrayofstring2IsNone():
self.testarrayofstring2 = []
for i in range(monster.Testarrayofstring2Length()):
self.testarrayofstring2.append(monster.Testarrayofstring2(i))
if not monster.TestarrayofsortedstructIsNone():
self.testarrayofsortedstruct = []
for i in range(monster.TestarrayofsortedstructLength()):
if monster.Testarrayofsortedstruct(i) is None:
self.testarrayofsortedstruct.append(None)
else:
ability_ = MyGame.Example.Ability.AbilityT.InitFromObj(monster.Testarrayofsortedstruct(i))
self.testarrayofsortedstruct.append(ability_)
if not monster.FlexIsNone():
if np is None:
self.flex = []
for i in range(monster.FlexLength()):
self.flex.append(monster.Flex(i))
else:
self.flex = monster.FlexAsNumpy()
if not monster.Test5IsNone():
self.test5 = []
for i in range(monster.Test5Length()):
if monster.Test5(i) is None:
self.test5.append(None)
else:
test_ = MyGame.Example.Test.TestT.InitFromObj(monster.Test5(i))
self.test5.append(test_)
if not monster.VectorOfLongsIsNone():
if np is None:
self.vectorOfLongs = []
for i in range(monster.VectorOfLongsLength()):
self.vectorOfLongs.append(monster.VectorOfLongs(i))
else:
self.vectorOfLongs = monster.VectorOfLongsAsNumpy()
if not monster.VectorOfDoublesIsNone():
if np is None:
self.vectorOfDoubles = []
for i in range(monster.VectorOfDoublesLength()):
self.vectorOfDoubles.append(monster.VectorOfDoubles(i))
else:
self.vectorOfDoubles = monster.VectorOfDoublesAsNumpy()
if monster.ParentNamespaceTest() is not None:
self.parentNamespaceTest = MyGame.InParentNamespace.InParentNamespaceT.InitFromObj(monster.ParentNamespaceTest())
if not monster.VectorOfReferrablesIsNone():
self.vectorOfReferrables = []
for i in range(monster.VectorOfReferrablesLength()):
if monster.VectorOfReferrables(i) is None:
self.vectorOfReferrables.append(None)
else:
referrable_ = MyGame.Example.Referrable.ReferrableT.InitFromObj(monster.VectorOfReferrables(i))
self.vectorOfReferrables.append(referrable_)
self.singleWeakReference = monster.SingleWeakReference()
if not monster.VectorOfWeakReferencesIsNone():
if np is None:
self.vectorOfWeakReferences = []
for i in range(monster.VectorOfWeakReferencesLength()):
self.vectorOfWeakReferences.append(monster.VectorOfWeakReferences(i))
else:
self.vectorOfWeakReferences = monster.VectorOfWeakReferencesAsNumpy()
if not monster.VectorOfStrongReferrablesIsNone():
self.vectorOfStrongReferrables = []
for i in range(monster.VectorOfStrongReferrablesLength()):
if monster.VectorOfStrongReferrables(i) is None:
self.vectorOfStrongReferrables.append(None)
else:
referrable_ = MyGame.Example.Referrable.ReferrableT.InitFromObj(monster.VectorOfStrongReferrables(i))
self.vectorOfStrongReferrables.append(referrable_)
self.coOwningReference = monster.CoOwningReference()
if not monster.VectorOfCoOwningReferencesIsNone():
if np is None:
self.vectorOfCoOwningReferences = []
for i in range(monster.VectorOfCoOwningReferencesLength()):
self.vectorOfCoOwningReferences.append(monster.VectorOfCoOwningReferences(i))
else:
self.vectorOfCoOwningReferences = monster.VectorOfCoOwningReferencesAsNumpy()
self.nonOwningReference = monster.NonOwningReference()
if not monster.VectorOfNonOwningReferencesIsNone():
if np is None:
self.vectorOfNonOwningReferences = []
for i in range(monster.VectorOfNonOwningReferencesLength()):
self.vectorOfNonOwningReferences.append(monster.VectorOfNonOwningReferences(i))
else:
self.vectorOfNonOwningReferences = monster.VectorOfNonOwningReferencesAsNumpy()
self.anyUniqueType = monster.AnyUniqueType()
self.anyUnique = MyGame.Example.AnyUniqueAliases.AnyUniqueAliasesCreator(self.anyUniqueType, monster.AnyUnique())
self.anyAmbiguousType = monster.AnyAmbiguousType()
self.anyAmbiguous = MyGame.Example.AnyAmbiguousAliases.AnyAmbiguousAliasesCreator(self.anyAmbiguousType, monster.AnyAmbiguous())
if not monster.VectorOfEnumsIsNone():
if np is None:
self.vectorOfEnums = []
for i in range(monster.VectorOfEnumsLength()):
self.vectorOfEnums.append(monster.VectorOfEnums(i))
else:
self.vectorOfEnums = monster.VectorOfEnumsAsNumpy()
self.signedEnum = monster.SignedEnum()
if not monster.TestrequirednestedflatbufferIsNone():
if np is None:
self.testrequirednestedflatbuffer = []
for i in range(monster.TestrequirednestedflatbufferLength()):
self.testrequirednestedflatbuffer.append(monster.Testrequirednestedflatbuffer(i))
else:
self.testrequirednestedflatbuffer = monster.TestrequirednestedflatbufferAsNumpy()
if not monster.ScalarKeySortedTablesIsNone():
self.scalarKeySortedTables = []
for i in range(monster.ScalarKeySortedTablesLength()):
if monster.ScalarKeySortedTables(i) is None:
self.scalarKeySortedTables.append(None)
else:
stat_ = MyGame.Example.Stat.StatT.InitFromObj(monster.ScalarKeySortedTables(i))
self.scalarKeySortedTables.append(stat_)
if monster.NativeInline() is not None:
self.nativeInline = MyGame.Example.Test.TestT.InitFromObj(monster.NativeInline())
self.longEnumNonEnumDefault = monster.LongEnumNonEnumDefault()
self.longEnumNormalDefault = monster.LongEnumNormalDefault()
self.nanDefault = monster.NanDefault()
self.infDefault = monster.InfDefault()
self.positiveInfDefault = monster.PositiveInfDefault()
self.infinityDefault = monster.InfinityDefault()
self.positiveInfinityDefault = monster.PositiveInfinityDefault()
self.negativeInfDefault = monster.NegativeInfDefault()
self.negativeInfinityDefault = monster.NegativeInfinityDefault()
self.doubleInfDefault = monster.DoubleInfDefault()
# MonsterT
def Pack(self, builder):
if self.name is not None:
name = builder.CreateString(self.name)
if self.inventory is not None:
if np is not None and type(self.inventory) is np.ndarray:
inventory = builder.CreateNumpyVector(self.inventory)
else:
MonsterStartInventoryVector(builder, len(self.inventory))
for i in reversed(range(len(self.inventory))):
builder.PrependUint8(self.inventory[i])
inventory = builder.EndVector()
if self.test is not None:
test = self.test.Pack(builder)
if self.test4 is not None:
MonsterStartTest4Vector(builder, len(self.test4))
for i in reversed(range(len(self.test4))):
self.test4[i].Pack(builder)
test4 = builder.EndVector()
if self.testarrayofstring is not None:
testarrayofstringlist = []
for i in range(len(self.testarrayofstring)):
testarrayofstringlist.append(builder.CreateString(self.testarrayofstring[i]))
MonsterStartTestarrayofstringVector(builder, len(self.testarrayofstring))
for i in reversed(range(len(self.testarrayofstring))):
builder.PrependUOffsetTRelative(testarrayofstringlist[i])
testarrayofstring = builder.EndVector()
if self.testarrayoftables is not None:
testarrayoftableslist = []
for i in range(len(self.testarrayoftables)):
testarrayoftableslist.append(self.testarrayoftables[i].Pack(builder))
MonsterStartTestarrayoftablesVector(builder, len(self.testarrayoftables))
for i in reversed(range(len(self.testarrayoftables))):
builder.PrependUOffsetTRelative(testarrayoftableslist[i])
testarrayoftables = builder.EndVector()
if self.enemy is not None:
enemy = self.enemy.Pack(builder)
if self.testnestedflatbuffer is not None:
if np is not None and type(self.testnestedflatbuffer) is np.ndarray:
testnestedflatbuffer = builder.CreateNumpyVector(self.testnestedflatbuffer)
else:
MonsterStartTestnestedflatbufferVector(builder, len(self.testnestedflatbuffer))
for i in reversed(range(len(self.testnestedflatbuffer))):
builder.PrependUint8(self.testnestedflatbuffer[i])
testnestedflatbuffer = builder.EndVector()
if self.testempty is not None:
testempty = self.testempty.Pack(builder)
if self.testarrayofbools is not None:
if np is not None and type(self.testarrayofbools) is np.ndarray:
testarrayofbools = builder.CreateNumpyVector(self.testarrayofbools)
else:
MonsterStartTestarrayofboolsVector(builder, len(self.testarrayofbools))
for i in reversed(range(len(self.testarrayofbools))):
builder.PrependBool(self.testarrayofbools[i])
testarrayofbools = builder.EndVector()
if self.testarrayofstring2 is not None:
testarrayofstring2list = []
for i in range(len(self.testarrayofstring2)):
testarrayofstring2list.append(builder.CreateString(self.testarrayofstring2[i]))
MonsterStartTestarrayofstring2Vector(builder, len(self.testarrayofstring2))
for i in reversed(range(len(self.testarrayofstring2))):
builder.PrependUOffsetTRelative(testarrayofstring2list[i])
testarrayofstring2 = builder.EndVector()
if self.testarrayofsortedstruct is not None:
MonsterStartTestarrayofsortedstructVector(builder, len(self.testarrayofsortedstruct))
for i in reversed(range(len(self.testarrayofsortedstruct))):
self.testarrayofsortedstruct[i].Pack(builder)
testarrayofsortedstruct = builder.EndVector()
if self.flex is not None:
if np is not None and type(self.flex) is np.ndarray:
flex = builder.CreateNumpyVector(self.flex)
else:
MonsterStartFlexVector(builder, len(self.flex))
for i in reversed(range(len(self.flex))):
builder.PrependUint8(self.flex[i])
flex = builder.EndVector()
if self.test5 is not None:
MonsterStartTest5Vector(builder, len(self.test5))
for i in reversed(range(len(self.test5))):
self.test5[i].Pack(builder)
test5 = builder.EndVector()
if self.vectorOfLongs is not None:
if np is not None and type(self.vectorOfLongs) is np.ndarray:
vectorOfLongs = builder.CreateNumpyVector(self.vectorOfLongs)
else:
MonsterStartVectorOfLongsVector(builder, len(self.vectorOfLongs))
for i in reversed(range(len(self.vectorOfLongs))):
builder.PrependInt64(self.vectorOfLongs[i])
vectorOfLongs = builder.EndVector()
if self.vectorOfDoubles is not None:
if np is not None and type(self.vectorOfDoubles) is np.ndarray:
vectorOfDoubles = builder.CreateNumpyVector(self.vectorOfDoubles)
else:
MonsterStartVectorOfDoublesVector(builder, len(self.vectorOfDoubles))
for i in reversed(range(len(self.vectorOfDoubles))):
builder.PrependFloat64(self.vectorOfDoubles[i])
vectorOfDoubles = builder.EndVector()
if self.parentNamespaceTest is not None:
parentNamespaceTest = self.parentNamespaceTest.Pack(builder)
if self.vectorOfReferrables is not None:
vectorOfReferrableslist = []
for i in range(len(self.vectorOfReferrables)):
vectorOfReferrableslist.append(self.vectorOfReferrables[i].Pack(builder))
MonsterStartVectorOfReferrablesVector(builder, len(self.vectorOfReferrables))
for i in reversed(range(len(self.vectorOfReferrables))):
builder.PrependUOffsetTRelative(vectorOfReferrableslist[i])
vectorOfReferrables = builder.EndVector()
if self.vectorOfWeakReferences is not None:
if np is not None and type(self.vectorOfWeakReferences) is np.ndarray:
vectorOfWeakReferences = builder.CreateNumpyVector(self.vectorOfWeakReferences)
else:
MonsterStartVectorOfWeakReferencesVector(builder, len(self.vectorOfWeakReferences))
for i in reversed(range(len(self.vectorOfWeakReferences))):
builder.PrependUint64(self.vectorOfWeakReferences[i])
vectorOfWeakReferences = builder.EndVector()
if self.vectorOfStrongReferrables is not None:
vectorOfStrongReferrableslist = []
for i in range(len(self.vectorOfStrongReferrables)):
vectorOfStrongReferrableslist.append(self.vectorOfStrongReferrables[i].Pack(builder))
MonsterStartVectorOfStrongReferrablesVector(builder, len(self.vectorOfStrongReferrables))
for i in reversed(range(len(self.vectorOfStrongReferrables))):
builder.PrependUOffsetTRelative(vectorOfStrongReferrableslist[i])
vectorOfStrongReferrables = builder.EndVector()
if self.vectorOfCoOwningReferences is not None:
if np is not None and type(self.vectorOfCoOwningReferences) is np.ndarray:
vectorOfCoOwningReferences = builder.CreateNumpyVector(self.vectorOfCoOwningReferences)
else:
MonsterStartVectorOfCoOwningReferencesVector(builder, len(self.vectorOfCoOwningReferences))
for i in reversed(range(len(self.vectorOfCoOwningReferences))):
builder.PrependUint64(self.vectorOfCoOwningReferences[i])
vectorOfCoOwningReferences = builder.EndVector()
if self.vectorOfNonOwningReferences is not None:
if np is not None and type(self.vectorOfNonOwningReferences) is np.ndarray:
vectorOfNonOwningReferences = builder.CreateNumpyVector(self.vectorOfNonOwningReferences)
else:
MonsterStartVectorOfNonOwningReferencesVector(builder, len(self.vectorOfNonOwningReferences))
for i in reversed(range(len(self.vectorOfNonOwningReferences))):
builder.PrependUint64(self.vectorOfNonOwningReferences[i])
vectorOfNonOwningReferences = builder.EndVector()
if self.anyUnique is not None:
anyUnique = self.anyUnique.Pack(builder)
if self.anyAmbiguous is not None:
anyAmbiguous = self.anyAmbiguous.Pack(builder)
if self.vectorOfEnums is not None:
if np is not None and type(self.vectorOfEnums) is np.ndarray:
vectorOfEnums = builder.CreateNumpyVector(self.vectorOfEnums)
else:
MonsterStartVectorOfEnumsVector(builder, len(self.vectorOfEnums))
for i in reversed(range(len(self.vectorOfEnums))):
builder.PrependUint8(self.vectorOfEnums[i])
vectorOfEnums = builder.EndVector()
if self.testrequirednestedflatbuffer is not None:
if np is not None and type(self.testrequirednestedflatbuffer) is np.ndarray:
testrequirednestedflatbuffer = builder.CreateNumpyVector(self.testrequirednestedflatbuffer)
else:
MonsterStartTestrequirednestedflatbufferVector(builder, len(self.testrequirednestedflatbuffer))
for i in reversed(range(len(self.testrequirednestedflatbuffer))):
builder.PrependUint8(self.testrequirednestedflatbuffer[i])
testrequirednestedflatbuffer = builder.EndVector()
if self.scalarKeySortedTables is not None:
scalarKeySortedTableslist = []
for i in range(len(self.scalarKeySortedTables)):
scalarKeySortedTableslist.append(self.scalarKeySortedTables[i].Pack(builder))
MonsterStartScalarKeySortedTablesVector(builder, len(self.scalarKeySortedTables))
for i in reversed(range(len(self.scalarKeySortedTables))):
builder.PrependUOffsetTRelative(scalarKeySortedTableslist[i])
scalarKeySortedTables = builder.EndVector()
MonsterStart(builder)
if self.pos is not None:
pos = self.pos.Pack(builder)
MonsterAddPos(builder, pos)
MonsterAddMana(builder, self.mana)
MonsterAddHp(builder, self.hp)
if self.name is not None:
MonsterAddName(builder, name)
if self.inventory is not None:
MonsterAddInventory(builder, inventory)
MonsterAddColor(builder, self.color)
MonsterAddTestType(builder, self.testType)
if self.test is not None:
MonsterAddTest(builder, test)
if self.test4 is not None:
MonsterAddTest4(builder, test4)
if self.testarrayofstring is not None:
MonsterAddTestarrayofstring(builder, testarrayofstring)
if self.testarrayoftables is not None:
MonsterAddTestarrayoftables(builder, testarrayoftables)
if self.enemy is not None:
MonsterAddEnemy(builder, enemy)
if self.testnestedflatbuffer is not None:
MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer)
if self.testempty is not None:
MonsterAddTestempty(builder, testempty)
MonsterAddTestbool(builder, self.testbool)
MonsterAddTesthashs32Fnv1(builder, self.testhashs32Fnv1)
MonsterAddTesthashu32Fnv1(builder, self.testhashu32Fnv1)
MonsterAddTesthashs64Fnv1(builder, self.testhashs64Fnv1)
MonsterAddTesthashu64Fnv1(builder, self.testhashu64Fnv1)
MonsterAddTesthashs32Fnv1a(builder, self.testhashs32Fnv1a)
MonsterAddTesthashu32Fnv1a(builder, self.testhashu32Fnv1a)
MonsterAddTesthashs64Fnv1a(builder, self.testhashs64Fnv1a)
MonsterAddTesthashu64Fnv1a(builder, self.testhashu64Fnv1a)
if self.testarrayofbools is not None:
MonsterAddTestarrayofbools(builder, testarrayofbools)
MonsterAddTestf(builder, self.testf)
MonsterAddTestf2(builder, self.testf2)
MonsterAddTestf3(builder, self.testf3)
if self.testarrayofstring2 is not None:
MonsterAddTestarrayofstring2(builder, testarrayofstring2)
if self.testarrayofsortedstruct is not None:
MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct)
if self.flex is not None:
MonsterAddFlex(builder, flex)
if self.test5 is not None:
MonsterAddTest5(builder, test5)
if self.vectorOfLongs is not None:
MonsterAddVectorOfLongs(builder, vectorOfLongs)
if self.vectorOfDoubles is not None:
MonsterAddVectorOfDoubles(builder, vectorOfDoubles)
if self.parentNamespaceTest is not None:
MonsterAddParentNamespaceTest(builder, parentNamespaceTest)
if self.vectorOfReferrables is not None:
MonsterAddVectorOfReferrables(builder, vectorOfReferrables)
MonsterAddSingleWeakReference(builder, self.singleWeakReference)
if self.vectorOfWeakReferences is not None:
MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences)
if self.vectorOfStrongReferrables is not None:
MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables)
MonsterAddCoOwningReference(builder, self.coOwningReference)
if self.vectorOfCoOwningReferences is not None:
MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences)
MonsterAddNonOwningReference(builder, self.nonOwningReference)
if self.vectorOfNonOwningReferences is not None:
MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences)
MonsterAddAnyUniqueType(builder, self.anyUniqueType)
if self.anyUnique is not None:
MonsterAddAnyUnique(builder, anyUnique)
MonsterAddAnyAmbiguousType(builder, self.anyAmbiguousType)
if self.anyAmbiguous is not None:
MonsterAddAnyAmbiguous(builder, anyAmbiguous)
if self.vectorOfEnums is not None:
MonsterAddVectorOfEnums(builder, vectorOfEnums)
MonsterAddSignedEnum(builder, self.signedEnum)
if self.testrequirednestedflatbuffer is not None:
MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer)
if self.scalarKeySortedTables is not None:
MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables)
if self.nativeInline is not None:
nativeInline = self.nativeInline.Pack(builder)
MonsterAddNativeInline(builder, nativeInline)
MonsterAddLongEnumNonEnumDefault(builder, self.longEnumNonEnumDefault)
MonsterAddLongEnumNormalDefault(builder, self.longEnumNormalDefault)
MonsterAddNanDefault(builder, self.nanDefault)
MonsterAddInfDefault(builder, self.infDefault)
MonsterAddPositiveInfDefault(builder, self.positiveInfDefault)
MonsterAddInfinityDefault(builder, self.infinityDefault)
MonsterAddPositiveInfinityDefault(builder, self.positiveInfinityDefault)
MonsterAddNegativeInfDefault(builder, self.negativeInfDefault)
MonsterAddNegativeInfinityDefault(builder, self.negativeInfinityDefault)
MonsterAddDoubleInfDefault(builder, self.doubleInfDefault)
monster = MonsterEnd(builder)
return monster
| MonsterT |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 4531,
"end": 4663
} | class ____(ExpressionElementRole[_T]):
__slots__ = ()
_role_name = "SQL expression element or literal value"
| BinaryElementRole |
python | getsentry__sentry | src/sentry/models/groupinbox.py | {
"start": 1250,
"end": 4278
} | class ____(Model):
"""
A Group that is in the inbox.
"""
__relocation_scope__ = RelocationScope.Excluded
group = FlexibleForeignKey("sentry.Group", unique=True, db_constraint=False)
project = FlexibleForeignKey("sentry.Project", null=True, db_constraint=False)
organization = FlexibleForeignKey("sentry.Organization", null=True, db_constraint=False)
reason = models.PositiveSmallIntegerField(null=False, default=GroupInboxReason.NEW.value)
reason_details = LegacyTextJSONField(default=dict, null=True)
date_added = models.DateTimeField(default=timezone.now, db_index=True)
class Meta:
app_label = "sentry"
db_table = "sentry_groupinbox"
indexes = (models.Index(fields=("project", "date_added")),)
def add_group_to_inbox(
group: Group,
reason: GroupInboxReason,
reason_details: InboxReasonDetails | None = None,
) -> GroupInbox:
group_inbox, _ = GroupInbox.objects.get_or_create(
group=group,
defaults={
"project": group.project,
"organization_id": group.project.organization_id,
"reason": reason.value,
"reason_details": reason_details,
},
)
return group_inbox
def remove_group_from_inbox(
group: Group,
action: GroupInboxRemoveAction | None = None,
user: User | RpcUser | None = None,
) -> None:
try:
group_inbox = GroupInbox.objects.get(group=group)
group_inbox.delete()
if action is GroupInboxRemoveAction.MARK_REVIEWED and user is not None:
Activity.objects.create(
project_id=group_inbox.group.project_id,
group_id=group_inbox.group_id,
type=ActivityType.MARK_REVIEWED.value,
user_id=user.id,
)
record_group_history(group, GroupHistoryStatus.REVIEWED, actor=user)
except GroupInbox.DoesNotExist:
pass
def bulk_remove_groups_from_inbox(
groups: BaseQuerySet[Group, Group],
action: GroupInboxRemoveAction | None = None,
user: User | RpcUser | Team | None = None,
) -> None:
with sentry_sdk.start_span(name="bulk_remove_groups_from_inbox"):
try:
group_inbox = GroupInbox.objects.filter(group__in=groups)
group_inbox.delete()
if action is GroupInboxRemoveAction.MARK_REVIEWED and user is not None:
Activity.objects.bulk_create(
[
Activity(
project_id=group_inbox_item.group.project_id,
group_id=group_inbox_item.group.id,
type=ActivityType.MARK_REVIEWED.value,
user_id=user.id,
)
for group_inbox_item in group_inbox
]
)
bulk_record_group_history(list(groups), GroupHistoryStatus.REVIEWED, actor=user)
except GroupInbox.DoesNotExist:
pass
| GroupInbox |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 24034,
"end": 24185
} | class ____(DagsterUserCodeExecutionError):
"""Error raised during the execution of a user-defined run status sensor."""
| RunStatusSensorExecutionError |
python | geekcomputers__Python | Rotate_Linked_List.py | {
"start": 94,
"end": 1467
} | class ____:
def __init__(self):
self.head = None
def Insert_At_Beginning(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
new_node.next = self.head
self.head = new_node
def Rotation(self, key):
if key == 0:
return
current = self.head
count = 1
while count < key and current is not None:
current = current.next
count += 1
if current is None:
return
Kth_Node = current
while current.next is not None:
current = current.next
current.next = self.head
self.head = Kth_Node.next
Kth_Node.next = None
def Display(self):
temp = self.head
while temp:
print(temp.data, "->", end=" ")
temp = temp.next
print("None")
if __name__ == "__main__":
L_list = Linked_List()
L_list.Insert_At_Beginning(8)
L_list.Insert_At_Beginning(5)
L_list.Insert_At_Beginning(10)
L_list.Insert_At_Beginning(7)
L_list.Insert_At_Beginning(6)
L_list.Insert_At_Beginning(11)
L_list.Insert_At_Beginning(9)
print("Linked List Before Rotation: ")
L_list.Display()
print("Linked List After Rotation: ")
L_list.Rotation(4)
L_list.Display()
| Linked_List |
python | huggingface__transformers | tests/models/lfm2_vl/test_modeling_lfm2_vl.py | {
"start": 9101,
"end": 12563
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained("LiquidAI/LFM2-VL-1.6B")
self.processor.tokenizer.padding_side = "left"
self.image = Image.open(
requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw
)
self.image2 = Image.open(
BytesIO(
requests.get(
"https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
).content
)
)
def tearDown(self):
cleanup(torch_device, gc_collect=True)
def test_integration_test(self):
model = Lfm2VlForConditionalGeneration.from_pretrained(
"LiquidAI/LFM2-VL-1.6B",
dtype=torch.bfloat16,
device_map="auto",
)
# Create inputs
text = "<image>In this image, we see"
images = self.image
inputs = self.processor(text=text, images=images, return_tensors="pt")
inputs.to(device=torch_device, dtype=torch.bfloat16)
generated_ids = model.generate(**inputs, max_new_tokens=20, do_sample=False)
generated_texts = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
expected_generated_text = "In this image, we see a cat and a dog lying on a pink blanket. They are both sleeping peacefully. They are"
self.assertEqual(generated_texts[0], expected_generated_text)
def test_integration_test_high_resolution(self):
model = Lfm2VlForConditionalGeneration.from_pretrained(
"LiquidAI/LFM2-VL-1.6B",
dtype=torch.bfloat16,
device_map="auto",
)
# Create inputs
text = "<image>In this image, we see"
images = self.image2
inputs = self.processor(text=text, images=images, return_tensors="pt")
inputs.to(device=torch_device, dtype=torch.bfloat16)
generated_ids = model.generate(**inputs, max_new_tokens=20, do_sample=False)
generated_texts = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
expected_generated_text = (
"In this image, we see the Statue of Liberty, standing tall on its pedestal. The statue is made of metal,"
)
self.assertEqual(generated_texts[0], expected_generated_text)
def test_integration_test_batched(self):
model = Lfm2VlForConditionalGeneration.from_pretrained(
"LiquidAI/LFM2-VL-450M",
dtype=torch.bfloat16,
device_map="auto",
)
# Create inputs
text = ["<image>In this image, we see", "<image>In this image, we see a cat"]
images = [[self.image2], [self.image]]
inputs = self.processor(text=text, images=images, return_tensors="pt", padding=True)
inputs.to(device=torch_device, dtype=torch.bfloat16)
generated_ids = model.generate(**inputs, max_new_tokens=20, do_sample=False)
generated_texts = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
expected_generated_text = [
"In this image, we see a panoramic view of the New York City skyline. The iconic Statics and the New York",
"In this image, we see a cat that is lying on its side on a cat bed.",
]
self.assertListEqual(generated_texts, expected_generated_text)
| Lfm2VlForConditionalGenerationIntegrationTest |
python | doocs__leetcode | solution/0900-0999/0939.Minimum Area Rectangle/Solution.py | {
"start": 0,
"end": 560
} | class ____:
def minAreaRect(self, points: List[List[int]]) -> int:
d = defaultdict(list)
for x, y in points:
d[x].append(y)
pos = {}
ans = inf
for x in sorted(d):
ys = d[x]
ys.sort()
n = len(ys)
for i, y1 in enumerate(ys):
for y2 in ys[i + 1 :]:
if (y1, y2) in pos:
ans = min(ans, (x - pos[(y1, y2)]) * (y2 - y1))
pos[(y1, y2)] = x
return 0 if ans == inf else ans
| Solution |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-openai/llama_index/voice_agents/openai/types.py | {
"start": 282,
"end": 580
} | class ____(BaseModel):
type_t: str = Field(serialization_alias="type", default="server_vad")
threshold: float = Field(default=0.5)
prefix_padding_ms: int = Field(default=300)
silence_duration_ms: int = Field(default=500)
create_response: bool = Field(default=True)
| ConversationVAD |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 489465,
"end": 490191
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for CheckRun."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("CheckRunEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("CheckRun"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| CheckRunConnection |
python | sympy__sympy | sympy/integrals/transforms.py | {
"start": 42857,
"end": 44457
} | class ____(SineCosineTypeTransform):
"""
Class representing unevaluated cosine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute cosine transforms, see the :func:`cosine_transform`
docstring.
"""
_name = 'Cosine'
_kern = cos
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return S.One
def cosine_transform(f, x, k, **hints):
r"""
Compute the unitary, ordinary-frequency cosine transform of `f`, defined
as
.. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \cos(2\pi x k) \mathrm{d} x.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`CosineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import cosine_transform, exp, sqrt, cos
>>> from sympy.abc import x, k, a
>>> cosine_transform(exp(-a*x), x, k)
sqrt(2)*a/(sqrt(pi)*(a**2 + k**2))
>>> cosine_transform(exp(-a*sqrt(x))*cos(a*sqrt(x)), x, k)
a*exp(-a**2/(2*k))/(2*k**(3/2))
See Also
========
fourier_transform, inverse_fourier_transform,
sine_transform, inverse_sine_transform
inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return CosineTransform(f, x, k).doit(**hints)
| CosineTransform |
python | getsentry__sentry | src/sentry/backup/dependencies.py | {
"start": 7208,
"end": 8352
} | class ____(json.JSONEncoder):
"""JSON serializer that outputs a detailed serialization of all models included in a
`ModelRelations`."""
def default(self, obj):
if meta := getattr(obj, "_meta", None):
return f"{meta.app_label}.{meta.object_name}".lower()
if isinstance(obj, ModelRelations):
return obj.__dict__
if isinstance(obj, ForeignFieldKind):
return obj.name
if isinstance(obj, RelocationScope):
return obj.name
if isinstance(obj, set) and all(isinstance(rs, RelocationScope) for rs in obj):
# Order by enum value, which should correspond to `RelocationScope` breadth.
return sorted(obj, key=lambda obj: obj.value)
if isinstance(obj, SiloMode):
return obj.name.lower().capitalize()
if isinstance(obj, set):
return sorted(obj, key=lambda obj: get_model_name(obj))
# JSON serialization of `uniques` values, which are stored in `frozenset`s.
if isinstance(obj, frozenset):
return sorted(obj)
return super().default(obj)
| DependenciesJSONEncoder |
python | viewflow__viewflow | tests/fsm/test_fsm__model.py | {
"start": 236,
"end": 953
} | class ____(object):
stage = fsm.State(ReviewState, default=ReviewState.NEW)
def __init__(self, report):
self.report = report
@stage.setter()
def _set_report_stage(self, value):
self.report.stage = value
@stage.getter()
def _get_report_stage(self):
return self.report.stage
@stage.on_success()
def _on_transition_success(self, descriptor, source, target):
self.report.save()
@stage.transition(
source=ReviewState.NEW,
target=ReviewState.PUBLISHED
)
def publish(self):
pass
@stage.transition(
source=fsm.State.ANY,
target=ReviewState.REMOVED
)
def remove(self):
pass
| ReportReview |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_new_jersey_zip.py | {
"start": 1766,
"end": 4123
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid New Jersey zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"valid_new_jersey_zip": ["07001", "07310", "07712", "08009"],
"invalid_new_jersey_zip": ["-10000", "1234", "99999", "25487"],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "valid_new_jersey_zip"},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "invalid_new_jersey_zip"},
"out": {"success": False},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_new_jersey_zip"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental", # "experimental", "beta", or "production"
"tags": [
"hackathon",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@luismdiaz01",
"@derekma73", # Don't forget to add your github handle here!
],
"requirements": ["zipcodes"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidNewJerseyZip().print_diagnostic_checklist()
| ExpectColumnValuesToBeValidNewJerseyZip |
python | cython__cython | tests/run/richcmp_str_equals.py | {
"start": 13,
"end": 71
} | class ____(object):
def __init__(self):
pass
| plop |
python | pytorch__pytorch | torch/_inductor/template_heuristics/gemm.py | {
"start": 221,
"end": 540
} | class ____(TemplateConfigHeuristics):
def should_run(self, inputs: KernelInputs) -> bool:
"""
simple base override for GEMM family templates that run only in max-autotune
"""
return inductor_config.max_autotune or inductor_config.max_autotune_gemm
| GemmMaxAutotuneTemplateConfigHeuristics |
python | explosion__spaCy | spacy/lang/lg/__init__.py | {
"start": 292,
"end": 388
} | class ____(Language):
lang = "lg"
Defaults = LugandaDefaults
__all__ = ["Luganda"]
| Luganda |
python | ipython__ipython | IPython/utils/io.py | {
"start": 349,
"end": 3928
} | class ____:
"""A class to duplicate an output stream to stdout/err.
This works in a manner very similar to the Unix 'tee' command.
When the object is closed or deleted, it closes the original file given to
it for duplication.
"""
# Inspired by:
# http://mail.python.org/pipermail/python-list/2007-May/442737.html
def __init__(self, file_or_name, mode="w", channel='stdout'):
"""Construct a new Tee object.
Parameters
----------
file_or_name : filename or open filehandle (writable)
File that will be duplicated
mode : optional, valid mode for open().
If a filename was give, open with this mode.
channel : str, one of ['stdout', 'stderr']
"""
if channel not in ['stdout', 'stderr']:
raise ValueError('Invalid channel spec %s' % channel)
if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
self.file = file_or_name
else:
encoding = None if "b" in mode else "utf-8"
self.file = open(file_or_name, mode, encoding=encoding)
self.channel = channel
self.ostream = getattr(sys, channel)
setattr(sys, channel, self)
self._closed = False
def close(self):
"""Close the file and restore the channel."""
self.flush()
setattr(sys, self.channel, self.ostream)
self.file.close()
self._closed = True
def write(self, data):
"""Write data to both channels."""
self.file.write(data)
self.ostream.write(data)
self.ostream.flush()
def flush(self):
"""Flush both channels."""
self.file.flush()
self.ostream.flush()
def __del__(self):
if not self._closed:
self.close()
def isatty(self):
return False
def ask_yes_no(prompt, default=None, interrupt=None):
"""Asks a question and returns a boolean (y/n) answer.
If default is given (one of 'y','n'), it is used if the user input is
empty. If interrupt is given (one of 'y','n'), it is used if the user
presses Ctrl-C. Otherwise the question is repeated until an answer is
given.
An EOF is treated as the default answer. If there is no default, an
exception is raised to prevent infinite loops.
Valid answers are: y/yes/n/no (match is not case sensitive)."""
answers = {'y':True,'n':False,'yes':True,'no':False}
ans = None
while ans not in answers.keys():
try:
ans = input(prompt+' ').lower()
if not ans: # response was an empty string
ans = default
except KeyboardInterrupt:
if interrupt:
ans = interrupt
print("\r")
except EOFError:
if default in answers.keys():
ans = default
print()
else:
raise
return answers[ans]
def temp_pyfile(src, ext='.py'):
"""Make a temporary python file, return filename and filehandle.
Parameters
----------
src : string or list of strings (no need for ending newlines if list)
Source code to be written to the file.
ext : optional, string
Extension for the generated file.
Returns
-------
(filename, open filehandle)
It is the caller's responsibility to close the open file and unlink it.
"""
fname = tempfile.mkstemp(ext)[1]
with open(Path(fname), "w", encoding="utf-8") as f:
f.write(src)
f.flush()
return fname
| Tee |
python | facebook__pyre-check | client/commands/tests/language_server_test.py | {
"start": 35271,
"end": 49704
} | class ____(testslide.TestCase):
@setup.async_test
async def test_subscription_protocol(self) -> None:
server_state = state.ServerState(
client_capabilities=lsp.ClientCapabilities(
window=lsp.WindowClientCapabilities(
status=lsp.ShowStatusRequestClientCapabilities(),
),
),
server_options=server_setup.mock_initial_server_options,
)
bytes_writer = connections.MemoryBytesWriter()
def fake_server_options_reader() -> pyre_server_options.PyreServerOptions:
# Server start option is not relevant to this test
raise NotImplementedError()
client_output_channel = connections.AsyncTextWriter(bytes_writer)
server_handler = persistent.PyrePersistentDaemonLaunchAndSubscribeHandler(
server_options_reader=fake_server_options_reader,
server_state=server_state,
client_status_message_handler=status_message_handler.ClientStatusMessageHandler(
client_output_channel, server_state
),
client_type_error_handler=type_error_handler.ClientTypeErrorHandler(
client_output_channel, server_state
),
)
await server_handler.handle_status_update_event(
subscription.StatusUpdate(kind="Rebuilding")
)
await server_handler.handle_status_update_event(
subscription.StatusUpdate(kind="Rechecking")
)
await server_handler.handle_type_error_event(
subscription.TypeErrors(
errors=[
error.Error(
line=1,
column=1,
stop_line=2,
stop_column=2,
path=Path("derp.py"),
code=42,
name="name",
description="description",
)
]
)
)
client_messages = [x.decode("utf-8") for x in bytes_writer.items()]
self.assertTrue(len(client_messages) == 4)
# Forward the rebuild status message
self.assertIn("window/showStatus", client_messages[0])
# Forward the recheck status message
self.assertIn("window/showStatus", client_messages[1])
# Clear out diagnostics for subsequent type errors
self.assertIn("textDocument/publishDiagnostics", client_messages[2])
# Notify the user that incremental check has finished
self.assertIn("window/showStatus", client_messages[3])
@setup.async_test
async def test_subscription_protocol_no_status_updates(self) -> None:
server_state = state.ServerState(
client_capabilities=lsp.ClientCapabilities(
window=lsp.WindowClientCapabilities(
status=lsp.ShowStatusRequestClientCapabilities(),
),
),
server_options=server_setup.create_server_options(
language_server_features=features.LanguageServerFeatures(
status_updates=features.StatusUpdatesAvailability.DISABLED,
)
),
)
bytes_writer = connections.MemoryBytesWriter()
def fake_server_options_reader() -> pyre_server_options.PyreServerOptions:
# Server start option is not relevant to this test
raise NotImplementedError()
client_output_channel = connections.AsyncTextWriter(bytes_writer)
server_handler = persistent.PyrePersistentDaemonLaunchAndSubscribeHandler(
server_options_reader=fake_server_options_reader,
server_state=server_state,
client_status_message_handler=status_message_handler.ClientStatusMessageHandler(
client_output_channel, server_state
),
client_type_error_handler=type_error_handler.ClientTypeErrorHandler(
client_output_channel, server_state
),
)
await server_handler.handle_status_update_event(
subscription.StatusUpdate(kind="Rebuilding")
)
await server_handler.handle_status_update_event(
subscription.StatusUpdate(kind="Rechecking")
)
await server_handler.handle_type_error_event(
subscription.TypeErrors(
errors=[
error.Error(
line=1,
column=1,
stop_line=2,
stop_column=2,
path=Path("derp.py"),
code=42,
name="name",
description="description",
)
]
)
)
client_messages = [x.decode("utf-8") for x in bytes_writer.items()]
self.assertTrue(len(client_messages) == 1)
self.assertIn("textDocument/publishDiagnostics", client_messages[0])
@setup.async_test
async def test_subscription_error(self) -> None:
def fake_server_options_reader() -> pyre_server_options.PyreServerOptions:
# Server start option is not relevant to this test
raise NotImplementedError()
client_output_channel = connections.AsyncTextWriter(
connections.MemoryBytesWriter()
)
server_handler = persistent.PyrePersistentDaemonLaunchAndSubscribeHandler(
server_options_reader=fake_server_options_reader,
server_state=server_setup.mock_server_state,
client_status_message_handler=status_message_handler.ClientStatusMessageHandler(
client_output_channel, server_setup.mock_server_state
),
client_type_error_handler=type_error_handler.ClientTypeErrorHandler(
client_output_channel, server_setup.mock_server_state
),
)
with self.assertRaises(launch_and_subscribe_handler.PyreDaemonShutdown):
await server_handler.handle_error_event(
subscription.Error(message="Doom Eternal")
)
@setup.async_test
async def test_busy_status_clear_diagnostics(self) -> None:
path = Path("foo.py")
server_state = state.ServerState(
server_options=server_setup.mock_initial_server_options,
diagnostics={path: []},
)
bytes_writer = connections.MemoryBytesWriter()
def fake_server_options_reader() -> pyre_server_options.PyreServerOptions:
# Server start option is not relevant to this test
raise NotImplementedError()
client_output_channel = connections.AsyncTextWriter(bytes_writer)
server_handler = persistent.PyrePersistentDaemonLaunchAndSubscribeHandler(
server_options_reader=fake_server_options_reader,
server_state=server_state,
client_status_message_handler=status_message_handler.ClientStatusMessageHandler(
client_output_channel, server_state
),
client_type_error_handler=type_error_handler.ClientTypeErrorHandler(
client_output_channel, server_state
),
)
await server_handler.handle_status_update_event(
subscription.StatusUpdate(kind="Rebuilding")
)
await server_handler.handle_status_update_event(
subscription.StatusUpdate(kind="Rechecking")
)
client_messages = [x.decode("utf-8") for x in bytes_writer.items()]
self.assertTrue(len(client_messages) == 2)
# Clear out diagnostics for rebuilding status
self.assertIn('"diagnostics": []', client_messages[0])
self.assertIn('"diagnostics": []', client_messages[1])
@setup.async_test
async def test_busy_status_no_clear_diagnostics_if_no_type_errors(self) -> None:
path = Path("foo.py")
server_state = state.ServerState(
server_options=server_setup.create_server_options(
language_server_features=features.LanguageServerFeatures(
type_errors=features.TypeErrorsAvailability.DISABLED,
),
),
diagnostics={path: []},
)
bytes_writer = connections.MemoryBytesWriter()
client_output_channel = connections.AsyncTextWriter(bytes_writer)
def fake_server_options_reader() -> pyre_server_options.PyreServerOptions:
# Server start option is not relevant to this test
raise NotImplementedError()
server_handler = persistent.PyrePersistentDaemonLaunchAndSubscribeHandler(
server_options_reader=fake_server_options_reader,
server_state=server_state,
client_status_message_handler=status_message_handler.ClientStatusMessageHandler(
client_output_channel, server_state
),
client_type_error_handler=type_error_handler.ClientTypeErrorHandler(
client_output_channel, server_state
),
)
await server_handler.handle_status_update_event(
subscription.StatusUpdate(kind="Rebuilding")
)
await server_handler.handle_status_update_event(
subscription.StatusUpdate(kind="Rechecking")
)
client_messages = [x.decode("utf-8") for x in bytes_writer.items()]
self.assertTrue(len(client_messages) == 0)
@setup.async_test
async def test_connections_lost(self) -> None:
test_path = Path("/foo.py")
server_state = state.ServerState(
server_options=server_setup.mock_initial_server_options,
diagnostics={test_path: []},
)
bytes_writer = connections.MemoryBytesWriter()
client_output_channel = connections.AsyncTextWriter(bytes_writer)
server_handler = persistent.PyrePersistentDaemonLaunchAndSubscribeHandler(
server_options_reader=lambda: server_setup.create_server_options(
binary="/bin/pyre",
server_identifier="foo",
start_arguments=start.Arguments(
base_arguments=backend_arguments.BaseArguments(
source_paths=backend_arguments.SimpleSourcePath(),
log_path="/log/path",
global_root="/global/root",
),
socket_path=Path("irrelevant_socket_path.sock"),
),
),
server_state=server_state,
client_status_message_handler=status_message_handler.ClientStatusMessageHandler(
client_output_channel, server_state
),
client_type_error_handler=type_error_handler.ClientTypeErrorHandler(
client_output_channel, server_state
),
)
with self.assertRaises(asyncio.IncompleteReadError):
await server_handler.subscribe(
# Intentionally inject a broken server response
connections.create_memory_text_reader("derp"),
connections.create_memory_text_writer(),
)
client_visible_messages = bytes_writer.items()
self.assertTrue(len(client_visible_messages) > 0)
self.assertEqual(
await lsp.read_json_rpc(
connections.AsyncTextReader(
connections.MemoryBytesReader(
# The server may send several status updates but we are
# mostly interested in the last message, which contains
# the diagnostics.
client_visible_messages[-1]
)
)
),
json_rpc.Request(
method="textDocument/publishDiagnostics",
parameters=json_rpc.ByNameParameters(
{"uri": "file:///foo.py", "diagnostics": []}
),
),
)
self.assertEqual(server_state.diagnostics, {})
@setup.async_test
async def test_send_message_to_status_bar(self) -> None:
bytes_writer = connections.MemoryBytesWriter()
client_output_channel = connections.AsyncTextWriter(bytes_writer)
server_state = state.ServerState(
client_capabilities=lsp.ClientCapabilities(
window=lsp.WindowClientCapabilities(
status=lsp.ShowStatusRequestClientCapabilities(),
),
),
server_options=server_setup.mock_initial_server_options,
)
server_handler = persistent.PyrePersistentDaemonLaunchAndSubscribeHandler(
server_options_reader=lambda: server_setup.create_server_options(
binary="/bin/pyre",
server_identifier="foo",
start_arguments=start.Arguments(
base_arguments=backend_arguments.BaseArguments(
source_paths=backend_arguments.SimpleSourcePath(),
log_path="/log/path",
global_root="/global/root",
),
socket_path=Path("irrelevant_socket_path.sock"),
),
),
server_state=server_state,
client_status_message_handler=status_message_handler.ClientStatusMessageHandler(
client_output_channel, server_state
),
client_type_error_handler=type_error_handler.ClientTypeErrorHandler(
client_output_channel, server_state
),
)
await (
server_handler.client_status_message_handler.show_status_message_to_client(
message="derp", level=lsp.MessageType.WARNING
)
)
client_visible_messages = bytes_writer.items()
self.assertTrue(len(client_visible_messages) > 0)
self.assertEqual(
await lsp.read_json_rpc(
connections.AsyncTextReader(
connections.MemoryBytesReader(client_visible_messages[-1])
)
),
json_rpc.Request(
method="window/showStatus",
id=0,
parameters=json_rpc.ByNameParameters({"type": 2, "message": "derp"}),
),
)
| PyreDaemonLaunchAndSubscribeHandlerTest |
python | keon__algorithms | tests/test_ml.py | {
"start": 101,
"end": 1477
} | class ____(unittest.TestCase):
def setUp(self):
# train set for the AND-function
self.trainSetAND = {(0, 0): 0, (0, 1): 0, (1, 0): 0, (1, 1): 1}
# train set for light or dark colors
self.trainSetLight = {(11, 98, 237): 'L', (3, 39, 96): 'D',
(242, 226, 12): 'L', (99, 93, 4): 'D',
(232, 62, 32): 'L', (119, 28, 11): 'D',
(25, 214, 47): 'L', (89, 136, 247): 'L',
(21, 34, 63): 'D', (237, 99, 120): 'L',
(73, 33, 39): 'D'}
def test_nearest_neighbor(self):
# AND-function
self.assertEqual(nearest_neighbor((1, 1), self.trainSetAND), 1)
self.assertEqual(nearest_neighbor((0, 1), self.trainSetAND), 0)
# dark/light color test
self.assertEqual(nearest_neighbor((31, 242, 164),
self.trainSetLight), 'L')
self.assertEqual(nearest_neighbor((13, 94, 64),
self.trainSetLight), 'D')
self.assertEqual(nearest_neighbor((230, 52, 239),
self.trainSetLight), 'L')
def test_distance(self):
self.assertAlmostEqual(distance((1, 2, 3), (1, 0, -1)), 4.47, 2)
if __name__ == "__main__":
unittest.main()
| TestML |
python | apache__airflow | providers/keycloak/tests/unit/keycloak/auth_manager/services/test_token.py | {
"start": 1118,
"end": 3333
} | class ____:
token = "token"
test_username = "test_user"
test_password = "test_pass"
test_access_token = "access_token"
test_refresh_token = "refresh_token"
@conf_vars(
{
("api_auth", "jwt_expiration_time"): "10",
}
)
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
def test_create_token(self, mock_get_keycloak_client, mock_get_auth_manager):
mock_keycloak_client = Mock()
mock_keycloak_client.token.return_value = {
"access_token": self.test_access_token,
"refresh_token": self.test_refresh_token,
}
mock_keycloak_client.userinfo.return_value = {"sub": "sub", "preferred_username": "username"}
mock_get_keycloak_client.return_value = mock_keycloak_client
mock_auth_manager = Mock()
mock_get_auth_manager.return_value = mock_auth_manager
mock_auth_manager.generate_jwt.return_value = self.token
assert create_token_for(username=self.test_username, password=self.test_password) == self.token
mock_keycloak_client.token.assert_called_once_with(self.test_username, self.test_password)
mock_keycloak_client.userinfo.assert_called_once_with(self.test_access_token)
@conf_vars(
{
("api_auth", "jwt_cli_expiration_time"): "10",
("api_auth", "jwt_expiration_time"): "10",
}
)
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
def test_create_token_with_invalid_creds(self, mock_get_keycloak_client):
mock_keycloak_client = Mock()
mock_keycloak_client.token.side_effect = KeycloakAuthenticationError()
mock_get_keycloak_client.return_value = mock_keycloak_client
with pytest.raises(fastapi.exceptions.HTTPException):
create_token_for(
username=self.test_username,
password=self.test_password,
expiration_time_in_seconds=conf.getint("api_auth", "jwt_cli_expiration_time"),
)
| TestTokenService |
python | kamyu104__LeetCode-Solutions | Python/find-triangular-sum-of-an-array.py | {
"start": 2075,
"end": 2359
} | class ____(object):
def triangularSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in reversed(xrange(len(nums))):
for j in xrange(i):
nums[j] = (nums[j]+nums[j+1])%10
return nums[0]
| Solution3 |
python | tensorflow__tensorflow | tensorflow/python/distribute/combinations_test.py | {
"start": 7238,
"end": 7556
} | class ____(test.TestCase,
parameterized.TestCase):
def test(self, distribution):
resolver = tfconfig_cluster_resolver.TFConfigClusterResolver()
# This should fail.
self.assertIsNone(resolver.task_id)
| CombinationsOnClassMultiWorkerExpectedFailureTest |
python | pytorch__pytorch | test/package/package_a/test_all_leaf_modules_tracer.py | {
"start": 70,
"end": 173
} | class ____(Tracer):
def is_leaf_module(self, m, qualname):
return True
| TestAllLeafModulesTracer |
python | getsentry__sentry | src/sentry/digests/notifications.py | {
"start": 956,
"end": 11565
} | class ____(NamedTuple):
digest: Digest
event_counts: dict[int, int]
user_counts: Mapping[int, int]
def split_key(
key: str,
) -> tuple[Project, ActionTargetType, int | str | None, FallthroughChoiceType | None]:
key_parts = key.split(":", 5)
project_id = key_parts[2]
# XXX: We transitioned to new style keys (len == 5) a while ago on
# sentry.io. But self-hosted users might transition at any time, so we need
# to keep this transition code around for a while, maybe indefinitely.
target_identifier: int | str | None = None
if len(key_parts) == 6:
target_type = ActionTargetType(key_parts[3])
if key_parts[4]:
if key_parts[4] == "None":
target_identifier = key_parts[4]
else:
target_identifier = int(key_parts[4])
try:
fallthrough_choice = FallthroughChoiceType(key_parts[5])
except ValueError:
fallthrough_choice = None
elif len(key_parts) == 5:
target_type = ActionTargetType(key_parts[3])
if key_parts[4]:
if key_parts[4] == "None":
target_identifier = key_parts[4]
else:
target_identifier = int(key_parts[4])
fallthrough_choice = None
else:
target_type = ActionTargetType.ISSUE_OWNERS
target_identifier = None
fallthrough_choice = None
return Project.objects.get(pk=project_id), target_type, target_identifier, fallthrough_choice
def unsplit_key(
project: Project,
target_type: ActionTargetType,
target_identifier: int | None,
fallthrough_choice: FallthroughChoiceType | None,
) -> str:
target_str = target_identifier if target_identifier is not None else ""
fallthrough = fallthrough_choice.value if fallthrough_choice is not None else ""
return f"mail:p:{project.id}:{target_type.value}:{target_str}:{fallthrough}"
def event_to_record(
event: Event | GroupEvent, rules: Sequence[Rule], notification_uuid: str | None = None
) -> Record:
from sentry.notifications.notification_action.utils import should_fire_workflow_actions
if not rules:
logger.warning("Creating record for %s that does not contain any rules!", event)
# TODO(iamrajjoshi): The typing on this function is wrong, the type should be GroupEvent
# TODO(iamrajjoshi): Creating a PR to fix this
assert event.group is not None
rule_ids = []
identifier_key = IdentifierKey.RULE
if features.has("organizations:workflow-engine-ui-links", event.organization):
identifier_key = IdentifierKey.WORKFLOW
for rule in rules:
rule_ids.append(int(get_key_from_rule_data(rule, "workflow_id")))
elif should_fire_workflow_actions(event.organization, event.group.type):
for rule in rules:
rule_ids.append(int(get_key_from_rule_data(rule, "legacy_rule_id")))
else:
for rule in rules:
rule_ids.append(rule.id)
return Record(
event.event_id,
Notification(event, rule_ids, notification_uuid, identifier_key),
event.datetime.timestamp(),
)
def _bind_records(
records: Sequence[Record], groups: dict[int, Group], rules: dict[int, Rule]
) -> list[RecordWithRuleObjects]:
ret = []
for record in records:
if record.value.event.group_id is None:
continue
group = groups.get(record.value.event.group_id)
if group is None:
logger.debug("%s could not be associated with a group.", record)
continue
elif group.get_status() != GroupStatus.UNRESOLVED:
continue
record.value.event.group = group
record_rules = [
rule
for rule in (rules.get(rule_id) for rule_id in record.value.rules)
if rule is not None
]
ret.append(record.with_rules(record_rules))
return ret
def _group_records(
records: Sequence[RecordWithRuleObjects], groups: dict[int, Group], rules: dict[int, Rule]
) -> Digest:
grouped: Digest = defaultdict(lambda: defaultdict(list))
for record in records:
assert record.value.event.group is not None
for rule in record.value.rules:
grouped[rule][record.value.event.group].append(record)
return grouped
def _sort_digest(
digest: Digest, event_counts: dict[int, int], user_counts: Mapping[Any, int]
) -> Digest:
# sort inner groups dict by (event_count, user_count) descending
for key, rule_groups in digest.items():
digest[key] = dict(
sorted(
rule_groups.items(),
# x = (group, records)
key=lambda x: (event_counts[x[0].id], user_counts[x[0].id]),
reverse=True,
)
)
# sort outer rules dict by number of groups (descending)
return dict(
sorted(
digest.items(),
# x = (rule, groups)
key=lambda x: len(x[1]),
reverse=True,
)
)
def _build_digest_impl(
records: Sequence[Record],
groups: dict[int, Group],
rules: dict[int, Rule],
event_counts: dict[int, int],
user_counts: Mapping[Any, int],
) -> Digest:
# sans-io implementation details
bound_records = _bind_records(records, groups, rules)
grouped = _group_records(bound_records, groups, rules)
return _sort_digest(grouped, event_counts=event_counts, user_counts=user_counts)
def get_rules_from_workflows(project: Project, workflow_ids: set[int]) -> dict[int, Rule]:
rules: dict[int, Rule] = {}
if not workflow_ids:
return rules
# Fetch all workflows in bulk
workflows = Workflow.objects.filter(organization_id=project.organization_id).in_bulk(
workflow_ids
)
# We are only processing the workflows in the digest if under the new flag
# This should be ok since we should only add workflow_ids to redis when under this flag
if features.has("organizations:workflow-engine-ui-links", project.organization):
for workflow_id, workflow in workflows.items():
assert (
workflow.organization_id == project.organization_id
), "Workflow must belong to Organization"
rules[workflow_id] = Rule(
label=workflow.name,
id=workflow_id,
project_id=project.id,
# We need to do this so that the links are built correctly downstream
data={"actions": [{"workflow_id": workflow_id}]},
)
# This is if we had workflows in the digest but the flag is not enabled
# This can happen if we rollback the flag, but the records in the digest aren't flushed
else:
alert_rule_workflows = AlertRuleWorkflow.objects.filter(workflow_id__in=workflow_ids)
alert_rule_workflows_map = {awf.workflow_id: awf for awf in alert_rule_workflows}
rule_ids_to_fetch = {awf.rule_id for awf in alert_rule_workflows}
bulk_rules = Rule.objects.filter(project_id=project.id).in_bulk(rule_ids_to_fetch)
for workflow_id in workflow_ids:
alert_workflow = alert_rule_workflows_map.get(workflow_id)
if not alert_workflow:
logger.warning(
"Workflow %s does not have a corresponding AlertRuleWorkflow entry", workflow_id
)
raise
rule = bulk_rules.get(alert_workflow.rule_id)
if not rule:
logger.warning(
"Rule %s linked to Workflow %s not found or does not belong to project %s",
alert_workflow.rule_id,
workflow_id,
project.id,
)
continue
assert rule.project_id == project.id, "Rule must belong to Project"
try:
rule.data["actions"][0]["legacy_rule_id"] = rule.id
except KeyError:
# This shouldn't happen, but isn't a deal breaker if it does
sentry_sdk.capture_exception(
Exception(f"Rule {rule.id} does not have a legacy_rule_id"),
level="warning",
)
rules[workflow_id] = rule
return rules
def build_digest(project: Project, records: Sequence[Record]) -> DigestInfo:
if not records:
return DigestInfo({}, {}, {})
# This reads a little strange, but remember that records are returned in
# reverse chronological order, and we query the database in chronological
# order.
# NOTE: This doesn't account for any issues that are filtered out later.
start = records[-1].datetime
end = records[0].datetime
rule_ids: set[int] = set()
workflow_ids: set[int] = set()
for record in records:
identifier_key = getattr(record.value, "identifier_key", IdentifierKey.RULE)
# record.value is Notification, record.value.rules is Sequence[int]
ids_to_add = record.value.rules
if identifier_key == IdentifierKey.RULE:
rule_ids.update(ids_to_add)
elif identifier_key == IdentifierKey.WORKFLOW:
workflow_ids.update(ids_to_add)
groups = Group.objects.in_bulk(record.value.event.group_id for record in records)
group_ids = list(groups)
rules = Rule.objects.in_bulk(rule_ids)
for rule in rules.values():
try:
rule.data["actions"][0]["legacy_rule_id"] = rule.id
except KeyError:
# This shouldn't happen, but isn't a deal breaker if it does
sentry_sdk.capture_exception(
Exception(f"Rule {rule.id} does not have a legacy_rule_id"),
level="warning",
)
rules.update(get_rules_from_workflows(project, workflow_ids))
for group_id, g in groups.items():
assert g.project_id == project.id, "Group must belong to Project"
for rule_id, rule in rules.items():
assert rule.project_id == project.id, "Rule must belong to Project"
tenant_ids = {"organization_id": project.organization_id}
event_counts = tsdb.backend.get_timeseries_sums(
TSDBModel.group,
group_ids,
start,
end,
tenant_ids=tenant_ids,
)
user_counts = tsdb.backend.get_distinct_counts_totals(
TSDBModel.users_affected_by_group,
group_ids,
start,
end,
tenant_ids=tenant_ids,
)
digest = _build_digest_impl(records, groups, rules, event_counts, user_counts)
return DigestInfo(digest, event_counts, user_counts)
| DigestInfo |
python | walkccc__LeetCode | solutions/2547. Minimum Cost to Split an Array/2547.py | {
"start": 0,
"end": 716
} | class ____:
def minCost(self, nums: list[int], k: int) -> int:
MAX = 1001
n = len(nums)
# trimmedLength[i][j] := trimmed(nums[i..j]).length
trimmedLength = [[0] * n for _ in range(n)]
# dp[i] := the minimum cost to split nums[i..n)
dp = [math.inf] * n + [0]
for i in range(n):
length = 0
count = [0] * MAX
for j in range(i, n):
count[nums[j]] += 1
if count[nums[j]] == 2:
length += 2
elif count[nums[j]] > 2:
length += 1
trimmedLength[i][j] = length
dp[n] = 0
for i in range(n - 1, -1, -1):
for j in range(i, n):
dp[i] = min(dp[i], k + trimmedLength[i][j] + dp[j + 1])
return dp[0]
| Solution |
python | ray-project__ray | python/ray/train/v2/_internal/state/schema.py | {
"start": 2024,
"end": 2247
} | class ____(str, Enum):
"""Enumeration of the statuses for a Train worker actor."""
# The actor is currently active.
ALIVE = "ALIVE"
# The actor is no longer active.
DEAD = "DEAD"
@DeveloperAPI
| ActorStatus |
python | pytest-dev__pytest | testing/python/raises.py | {
"start": 303,
"end": 14898
} | class ____:
def test_check_callable(self) -> None:
with pytest.raises(TypeError, match=r".* must be callable"):
pytest.raises(RuntimeError, "int('qwe')") # type: ignore[call-overload]
def test_raises(self):
excinfo = pytest.raises(ValueError, int, "qwe")
assert "invalid literal" in str(excinfo.value)
def test_raises_function(self):
excinfo = pytest.raises(ValueError, int, "hello")
assert "invalid literal" in str(excinfo.value)
def test_raises_does_not_allow_none(self):
with pytest.raises(
ValueError,
match=wrap_escape("You must specify at least one parameter to match on."),
):
# We're testing that this invalid usage gives a helpful error,
# so we can ignore Mypy telling us that None is invalid.
pytest.raises(expected_exception=None) # type: ignore
# it's unclear if this message is helpful, and if it is, should it trigger more
# liberally? Usually you'd get a TypeError here
def test_raises_false_and_arg(self):
with pytest.raises(
ValueError,
match=wrap_escape(
"Expected an exception type or a tuple of exception types, but got `False`. "
"Raising exceptions is already understood as failing the test, so you don't need "
"any special code to say 'this should never raise an exception'."
),
):
pytest.raises(False, int) # type: ignore[call-overload]
def test_raises_does_not_allow_empty_tuple(self):
with pytest.raises(
ValueError,
match=wrap_escape("You must specify at least one parameter to match on."),
):
pytest.raises(expected_exception=())
def test_raises_callable_no_exception(self) -> None:
class A:
def __call__(self):
pass
try:
pytest.raises(ValueError, A())
except pytest.fail.Exception:
pass
def test_raises_falsey_type_error(self) -> None:
with pytest.raises(TypeError):
with pytest.raises(AssertionError, match=0): # type: ignore[call-overload]
raise AssertionError("ohai")
def test_raises_repr_inflight(self):
"""Ensure repr() on an exception info inside a pytest.raises with block works (#4386)"""
class E(Exception):
pass
with pytest.raises(E) as excinfo:
# this test prints the inflight uninitialized object
# using repr and str as well as pprint to demonstrate
# it works
print(str(excinfo))
print(repr(excinfo))
import pprint
pprint.pprint(excinfo)
raise E()
def test_raises_as_contextmanager(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
import _pytest._code
def test_simple():
with pytest.raises(ZeroDivisionError) as excinfo:
assert isinstance(excinfo, _pytest._code.ExceptionInfo)
1/0
print(excinfo)
assert excinfo.type == ZeroDivisionError
assert isinstance(excinfo.value, ZeroDivisionError)
def test_noraise():
with pytest.raises(pytest.raises.Exception):
with pytest.raises(ValueError):
int()
def test_raise_wrong_exception_passes_by():
with pytest.raises(ZeroDivisionError):
with pytest.raises(ValueError):
1/0
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*3 passed*"])
def test_does_not_raise(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
from contextlib import nullcontext as does_not_raise
import pytest
@pytest.mark.parametrize('example_input,expectation', [
(3, does_not_raise()),
(2, does_not_raise()),
(1, does_not_raise()),
(0, pytest.raises(ZeroDivisionError)),
])
def test_division(example_input, expectation):
'''Test how much I know division.'''
with expectation:
assert (6 / example_input) is not None
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*4 passed*"])
def test_does_not_raise_does_raise(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
from contextlib import nullcontext as does_not_raise
import pytest
@pytest.mark.parametrize('example_input,expectation', [
(0, does_not_raise()),
(1, pytest.raises(ZeroDivisionError)),
])
def test_division(example_input, expectation):
'''Test how much I know division.'''
with expectation:
assert (6 / example_input) is not None
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 failed*"])
def test_raises_with_invalid_regex(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def test_invalid_regex():
with pytest.raises(ValueError, match="invalid regex character ["):
raise ValueError()
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*Invalid regex pattern provided to 'match': unterminated character set at position 24*",
]
)
result.stdout.no_fnmatch_line("*Traceback*")
result.stdout.no_fnmatch_line("*File*")
result.stdout.no_fnmatch_line("*line*")
def test_noclass(self) -> None:
with pytest.raises(TypeError):
pytest.raises("wrong", lambda: None) # type: ignore[call-overload]
def test_invalid_arguments_to_raises(self) -> None:
with pytest.raises(TypeError, match="unknown"):
with pytest.raises(TypeError, unknown="bogus"): # type: ignore[call-overload]
raise ValueError()
def test_tuple(self):
with pytest.raises((KeyError, ValueError)):
raise KeyError("oops")
def test_no_raise_message(self) -> None:
try:
pytest.raises(ValueError, int, "0")
except pytest.fail.Exception as e:
assert e.msg == f"DID NOT RAISE {ValueError!r}"
else:
assert False, "Expected pytest.raises.Exception"
try:
with pytest.raises(ValueError):
pass
except pytest.fail.Exception as e:
assert e.msg == f"DID NOT RAISE {ValueError!r}"
else:
assert False, "Expected pytest.raises.Exception"
@pytest.mark.parametrize(
"method", ["function", "function_match", "with", "with_raisesexc", "with_group"]
)
def test_raises_cyclic_reference(self, method):
"""Ensure pytest.raises does not leave a reference cycle (#1965)."""
import gc
class T:
def __call__(self):
raise ValueError
t = T()
refcount = len(gc.get_referrers(t))
if method == "function":
pytest.raises(ValueError, t)
elif method == "function_match":
pytest.raises(ValueError, t).match("^$")
elif method == "with":
with pytest.raises(ValueError):
t()
elif method == "with_raisesexc":
with pytest.RaisesExc(ValueError):
t()
elif method == "with_group":
with pytest.RaisesGroup(ValueError, allow_unwrapped=True):
t()
else: # pragma: no cover
raise AssertionError("bad parametrization")
# ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()
assert sys.exc_info() == (None, None, None)
assert refcount == len(gc.get_referrers(t))
def test_raises_match(self) -> None:
msg = r"with base \d+"
with pytest.raises(ValueError, match=msg):
int("asdf")
msg = "with base 10"
with pytest.raises(ValueError, match=msg):
int("asdf")
msg = "with base 16"
expr = (
"Regex pattern did not match.\n"
f" Expected regex: {msg!r}\n"
f" Actual message: \"invalid literal for int() with base 10: 'asdf'\""
)
with pytest.raises(AssertionError, match="^" + re.escape(expr) + "$"):
with pytest.raises(ValueError, match=msg):
int("asdf", base=10)
# "match" without context manager.
pytest.raises(ValueError, int, "asdf").match("invalid literal")
with pytest.raises(AssertionError) as excinfo:
pytest.raises(ValueError, int, "asdf").match(msg)
assert str(excinfo.value) == expr
pytest.raises(TypeError, int, match="invalid")
def tfunc(match):
raise ValueError(f"match={match}")
pytest.raises(ValueError, tfunc, match="asdf").match("match=asdf")
pytest.raises(ValueError, tfunc, match="").match("match=")
# empty string matches everything, which is probably not what the user wants
with pytest.warns(
PytestWarning,
match=wrap_escape(
"matching against an empty string will *always* pass. If you want to check for an empty message you "
"need to pass '^$'. If you don't want to match you should pass `None` or leave out the parameter."
),
):
pytest.raises(match="")
def test_match_failure_string_quoting(self):
with pytest.raises(AssertionError) as excinfo:
with pytest.raises(AssertionError, match="'foo"):
raise AssertionError("'bar")
(msg,) = excinfo.value.args
assert (
msg
== '''Regex pattern did not match.\n Expected regex: "'foo"\n Actual message: "'bar"'''
)
def test_match_failure_exact_string_message(self):
message = "Oh here is a message with (42) numbers in parameters"
with pytest.raises(AssertionError) as excinfo:
with pytest.raises(AssertionError, match=message):
raise AssertionError(message)
(msg,) = excinfo.value.args
assert msg == (
"Regex pattern did not match.\n"
" Expected regex: 'Oh here is a message with (42) numbers in parameters'\n"
" Actual message: 'Oh here is a message with (42) numbers in parameters'\n"
" Did you mean to `re.escape()` the regex?"
)
def test_raises_match_wrong_type(self):
"""Raising an exception with the wrong type and match= given.
pytest should throw the unexpected exception - the pattern match is not
really relevant if we got a different exception.
"""
with pytest.raises(
ValueError,
match=wrap_escape("invalid literal for int() with base 10: 'asdf'"),
):
with pytest.raises(IndexError, match="nomatch"):
int("asdf")
def test_raises_exception_looks_iterable(self):
class Meta(type):
def __getitem__(self, item):
return 1 / 0
def __len__(self):
return 1
class ClassLooksIterableException(Exception, metaclass=Meta):
pass
with pytest.raises(
Failed,
match=r"DID NOT RAISE <class 'raises(\..*)*ClassLooksIterableException'>",
):
pytest.raises(ClassLooksIterableException, lambda: None)
def test_raises_with_raising_dunder_class(self) -> None:
"""Test current behavior with regard to exceptions via __class__ (#4284)."""
class CrappyClass(Exception):
# Type ignored because it's bypassed intentionally.
@property # type: ignore
def __class__(self):
assert False, "via __class__"
with pytest.raises(AssertionError) as excinfo:
with pytest.raises(CrappyClass()): # type: ignore[call-overload]
pass
assert "via __class__" in excinfo.value.args[0]
def test_raises_context_manager_with_kwargs(self):
with pytest.raises(expected_exception=ValueError):
raise ValueError
with pytest.raises(
TypeError,
match=wrap_escape(
"Unexpected keyword arguments passed to pytest.raises: foo\n"
"Use context-manager form instead?"
),
):
with pytest.raises(OSError, foo="bar"): # type: ignore[call-overload]
pass
def test_expected_exception_is_not_a_baseexception(self) -> None:
with pytest.raises(
TypeError,
match=wrap_escape("Expected a BaseException type, but got 'str'"),
):
with pytest.raises("hello"): # type: ignore[call-overload]
pass # pragma: no cover
class NotAnException:
pass
with pytest.raises(
ValueError,
match=wrap_escape(
"Expected a BaseException type, but got 'NotAnException'"
),
):
with pytest.raises(NotAnException): # type: ignore[type-var]
pass # pragma: no cover
with pytest.raises(
TypeError,
match=wrap_escape("Expected a BaseException type, but got 'str'"),
):
with pytest.raises(("hello", NotAnException)): # type: ignore[arg-type]
pass # pragma: no cover
def test_issue_11872(self) -> None:
"""Regression test for #11872.
urllib.error.HTTPError on some Python 3.10/11 minor releases raises
KeyError instead of AttributeError on invalid attribute access.
https://github.com/python/cpython/issues/98778
"""
from email.message import Message
from urllib.error import HTTPError
with pytest.raises(HTTPError, match="Not Found") as exc_info:
raise HTTPError(
code=404, msg="Not Found", fp=io.BytesIO(), hdrs=Message(), url=""
)
exc_info.value.close() # avoid a resource warning
| TestRaises |
python | sphinx-doc__sphinx | sphinx/roles.py | {
"start": 16155,
"end": 16634
} | class ____(SphinxRole):
abbr_re = re.compile(r'\((.*)\)$', re.DOTALL)
def run(self) -> tuple[list[Node], list[system_message]]:
options = self.options.copy()
matched = self.abbr_re.search(self.text)
if matched:
text = self.text[: matched.start()].strip()
options['explanation'] = matched.group(1)
else:
text = self.text
return [nodes.abbreviation(self.rawtext, text, **options)], []
| Abbreviation |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/stateful.py | {
"start": 40411,
"end": 42544
} | class ____:
function: Any
preconditions: Any
check_during_init: bool
def __repr__(self) -> str:
parts = [
f"function={get_pretty_function_description(self.function)}",
f"{self.preconditions=}",
f"{self.check_during_init=}",
]
return f"Invariant({', '.join(parts)})"
def invariant(*, check_during_init: bool = False) -> Callable[[TestFunc], TestFunc]:
"""Decorator to apply an invariant for rules in a RuleBasedStateMachine.
The decorated function will be run after every rule and can raise an
exception to indicate failed invariants.
For example::
class MyTestMachine(RuleBasedStateMachine):
state = 1
@invariant()
def is_nonzero(self):
assert self.state != 0
By default, invariants are only checked after all
:func:`@initialize() <hypothesis.stateful.initialize>` rules have been run.
Pass ``check_during_init=True`` for invariants which can also be checked
during initialization.
"""
check_type(bool, check_during_init, "check_during_init")
def accept(f):
if getattr(f, RULE_MARKER, None) or getattr(f, INITIALIZE_RULE_MARKER, None):
raise InvalidDefinition(
f"{_rule_qualname(f)} has been decorated with both @invariant and "
"@rule, which is not allowed."
)
existing_invariant = getattr(f, INVARIANT_MARKER, None)
if existing_invariant is not None:
raise InvalidDefinition(
f"{_rule_qualname(f)} has been decorated with @invariant twice, "
"which is not allowed."
)
preconditions = getattr(f, PRECONDITIONS_MARKER, ())
invar = Invariant(
function=f,
preconditions=preconditions,
check_during_init=check_during_init,
)
@proxies(f)
def invariant_wrapper(*args, **kwargs):
return f(*args, **kwargs)
setattr(invariant_wrapper, INVARIANT_MARKER, invar)
return invariant_wrapper
return accept
| Invariant |
python | pytorch__pytorch | test/mobile/model_test/quantization_ops.py | {
"start": 4389,
"end": 6146
} | class ____:
def getModule(self):
model_fp32 = self.M()
model_fp32.eval()
model_fp32.qconfig = torch.ao.quantization.get_default_qconfig("qnnpack")
model_fp32_prepared = torch.ao.quantization.prepare(model_fp32)
model_int8 = torch.ao.quantization.convert(model_fp32_prepared)
return model_int8
class M(torch.nn.Module):
def __init__(self) -> None:
super(StaticQuantModule.M, self).__init__()
self.quant = torch.ao.quantization.QuantStub()
self.input1d = torch.randn(4, 2, 2)
self.input2d = torch.randn((4, 2, 4, 4))
self.input3d = torch.randn(4, 2, 2, 4, 4)
self.linear_input = torch.randn(32, 20)
self.layer1 = nn.Sequential(
nn.Conv1d(2, 2, 1), nn.InstanceNorm1d(1), nn.Hardswish()
)
self.layer2 = nn.Sequential(
nn.Conv2d(2, 2, 1),
nn.BatchNorm2d(2),
nn.InstanceNorm2d(1),
nn.LeakyReLU(),
)
self.layer3 = nn.Sequential(
nn.Conv3d(2, 2, 1), nn.BatchNorm3d(2), nn.InstanceNorm3d(1), nn.ReLU()
)
self.layer4 = nn.Sequential(nn.Linear(4, 3))
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self):
x = self.quant(self.input1d)
x = self.layer1(x)
x = self.dequant(x)
y = self.input2d
y = self.quant(y)
y = self.layer2(y)
y = self.layer4(y)
y = self.dequant(y)
z = self.quant(self.input3d)
z = self.layer3(z)
z = self.dequant(z)
return (x, y, z)
| StaticQuantModule |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/distlib/database.py | {
"start": 32675,
"end": 41992
} | class ____(BaseInstalledDistribution):
"""Created with the *path* of the ``.egg-info`` directory or file provided
to the constructor. It reads the metadata contained in the file itself, or
if the given path happens to be a directory, the metadata is read from the
file ``PKG-INFO`` under that directory."""
requested = True # as we have no way of knowing, assume it was
shared_locations = {}
def __init__(self, path, env=None):
def set_name_and_version(s, n, v):
s.name = n
s.key = n.lower() # for case-insensitive comparisons
s.version = v
self.path = path
self.dist_path = env
if env and env._cache_enabled and path in env._cache_egg.path:
metadata = env._cache_egg.path[path].metadata
set_name_and_version(self, metadata.name, metadata.version)
else:
metadata = self._get_metadata(path)
# Need to be set before caching
set_name_and_version(self, metadata.name, metadata.version)
if env and env._cache_enabled:
env._cache_egg.add(self)
super(EggInfoDistribution, self).__init__(metadata, path, env)
def _get_metadata(self, path):
requires = None
def parse_requires_data(data):
"""Create a list of dependencies from a requires.txt file.
*data*: the contents of a setuptools-produced requires.txt file.
"""
reqs = []
lines = data.splitlines()
for line in lines:
line = line.strip()
# sectioned files have bare newlines (separating sections)
if not line: # pragma: no cover
continue
if line.startswith('['): # pragma: no cover
logger.warning(
'Unexpected line: quitting requirement scan: %r', line)
break
r = parse_requirement(line)
if not r: # pragma: no cover
logger.warning('Not recognised as a requirement: %r', line)
continue
if r.extras: # pragma: no cover
logger.warning('extra requirements in requires.txt are '
'not supported')
if not r.constraints:
reqs.append(r.name)
else:
cons = ', '.join('%s%s' % c for c in r.constraints)
reqs.append('%s (%s)' % (r.name, cons))
return reqs
def parse_requires_path(req_path):
"""Create a list of dependencies from a requires.txt file.
*req_path*: the path to a setuptools-produced requires.txt file.
"""
reqs = []
try:
with codecs.open(req_path, 'r', 'utf-8') as fp:
reqs = parse_requires_data(fp.read())
except IOError:
pass
return reqs
tl_path = tl_data = None
if path.endswith('.egg'):
if os.path.isdir(path):
p = os.path.join(path, 'EGG-INFO')
meta_path = os.path.join(p, 'PKG-INFO')
metadata = Metadata(path=meta_path, scheme='legacy')
req_path = os.path.join(p, 'requires.txt')
tl_path = os.path.join(p, 'top_level.txt')
requires = parse_requires_path(req_path)
else:
# FIXME handle the case where zipfile is not available
zipf = zipimport.zipimporter(path)
fileobj = StringIO(
zipf.get_data('EGG-INFO/PKG-INFO').decode('utf8'))
metadata = Metadata(fileobj=fileobj, scheme='legacy')
try:
data = zipf.get_data('EGG-INFO/requires.txt')
tl_data = zipf.get_data('EGG-INFO/top_level.txt').decode(
'utf-8')
requires = parse_requires_data(data.decode('utf-8'))
except IOError:
requires = None
elif path.endswith('.egg-info'):
if os.path.isdir(path):
req_path = os.path.join(path, 'requires.txt')
requires = parse_requires_path(req_path)
path = os.path.join(path, 'PKG-INFO')
tl_path = os.path.join(path, 'top_level.txt')
metadata = Metadata(path=path, scheme='legacy')
else:
raise DistlibException('path must end with .egg-info or .egg, '
'got %r' % path)
if requires:
metadata.add_requirements(requires)
# look for top-level modules in top_level.txt, if present
if tl_data is None:
if tl_path is not None and os.path.exists(tl_path):
with open(tl_path, 'rb') as f:
tl_data = f.read().decode('utf-8')
if not tl_data:
tl_data = []
else:
tl_data = tl_data.splitlines()
self.modules = tl_data
return metadata
def __repr__(self):
return '<EggInfoDistribution %r %s at %r>' % (self.name, self.version,
self.path)
def __str__(self):
return "%s %s" % (self.name, self.version)
def check_installed_files(self):
"""
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
"""
mismatches = []
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
for path, _, _ in self.list_installed_files():
if path == record_path:
continue
if not os.path.exists(path):
mismatches.append((path, 'exists', True, False))
return mismatches
def list_installed_files(self):
"""
Iterates over the ``installed-files.txt`` entries and returns a tuple
``(path, hash, size)`` for each line.
:returns: a list of (path, hash, size)
"""
def _md5(path):
f = open(path, 'rb')
try:
content = f.read()
finally:
f.close()
return hashlib.md5(content).hexdigest()
def _size(path):
return os.stat(path).st_size
record_path = os.path.join(self.path, 'installed-files.txt')
result = []
if os.path.exists(record_path):
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
p = os.path.normpath(os.path.join(self.path, line))
# "./" is present as a marker between installed files
# and installation metadata files
if not os.path.exists(p):
logger.warning('Non-existent file: %s', p)
if p.endswith(('.pyc', '.pyo')):
continue
# otherwise fall through and fail
if not os.path.isdir(p):
result.append((p, _md5(p), _size(p)))
result.append((record_path, None, None))
return result
def list_distinfo_files(self, absolute=False):
"""
Iterates over the ``installed-files.txt`` entries and returns paths for
each line if the path is pointing to a file located in the
``.egg-info`` directory or one of its subdirectories.
:parameter absolute: If *absolute* is ``True``, each returned path is
transformed into a local absolute path. Otherwise the
raw value from ``installed-files.txt`` is returned.
:type absolute: boolean
:returns: iterator of paths
"""
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
skip = True
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line == './':
skip = False
continue
if not skip:
p = os.path.normpath(os.path.join(self.path, line))
if p.startswith(self.path):
if absolute:
yield p
else:
yield line
def __eq__(self, other):
return (isinstance(other, EggInfoDistribution)
and self.path == other.path)
# See http://docs.python.org/reference/datamodel#object.__hash__
__hash__ = object.__hash__
new_dist_class = InstalledDistribution
old_dist_class = EggInfoDistribution
| EggInfoDistribution |
python | bokeh__bokeh | tests/unit/bokeh/server/test_auth_provider.py | {
"start": 3701,
"end": 4277
} | class ____(RequestHandler): pass
""", func, suffix='.py')
def test_login_logout_url_endpoint(self) -> None:
def func(filename: str):
am = bsa.AuthModule(filename)
endpoints = sorted(am.endpoints)
assert endpoints[0][0] == '/bar'
assert issubclass(endpoints[0][1], RequestHandler)
assert endpoints[1][0] == '/foo'
assert issubclass(endpoints[1][1], RequestHandler)
with_file_contents("""
def get_user(): pass
login_url = "/foo"
from tornado.web import RequestHandler
| LogoutHandler |
python | matplotlib__matplotlib | lib/matplotlib/projections/polar.py | {
"start": 398,
"end": 5229
} | class ____(mtransforms.Transform):
r"""
The base polar transform.
This transform maps polar coordinates :math:`\theta, r` into Cartesian
coordinates :math:`x, y = r \cos(\theta), r \sin(\theta)`
(but does not fully transform into Axes coordinates or
handle positioning in screen space).
This transformation is designed to be applied to data after any scaling
along the radial axis (e.g. log-scaling) has been applied to the input
data.
Path segments at a fixed radius are automatically transformed to circular
arcs as long as ``path._interpolation_steps > 1``.
"""
input_dims = output_dims = 2
def __init__(self, axis=None, use_rmin=True, *, scale_transform=None):
"""
Parameters
----------
axis : `~matplotlib.axis.Axis`, optional
Axis associated with this transform. This is used to get the
minimum radial limit.
use_rmin : `bool`, optional
If ``True``, subtract the minimum radial axis limit before
transforming to Cartesian coordinates. *axis* must also be
specified for this to take effect.
"""
super().__init__()
self._axis = axis
self._use_rmin = use_rmin
self._scale_transform = scale_transform
__str__ = mtransforms._make_str_method(
"_axis",
use_rmin="_use_rmin"
)
def _get_rorigin(self):
# Get lower r limit after being scaled by the radial scale transform
return self._scale_transform.transform(
(0, self._axis.get_rorigin()))[1]
def transform_non_affine(self, values):
# docstring inherited
theta, r = np.transpose(values)
if self._use_rmin and self._axis is not None:
r = (r - self._get_rorigin()) * self._axis.get_rsign()
r = np.where(r >= 0, r, np.nan)
return np.column_stack([r * np.cos(theta), r * np.sin(theta)])
def transform_path_non_affine(self, path):
# docstring inherited
if not len(path) or path._interpolation_steps == 1:
return Path(self.transform_non_affine(path.vertices), path.codes)
xys = []
codes = []
last_t = last_r = None
for trs, c in path.iter_segments():
trs = trs.reshape((-1, 2))
if c == Path.LINETO:
(t, r), = trs
if t == last_t: # Same angle: draw a straight line.
xys.extend(self.transform_non_affine(trs))
codes.append(Path.LINETO)
elif r == last_r: # Same radius: draw an arc.
# The following is complicated by Path.arc() being
# "helpful" and unwrapping the angles, but we don't want
# that behavior here.
last_td, td = np.rad2deg([last_t, t])
if self._use_rmin and self._axis is not None:
r = ((r - self._get_rorigin())
* self._axis.get_rsign())
if last_td <= td:
while td - last_td > 360:
arc = Path.arc(last_td, last_td + 360)
xys.extend(arc.vertices[1:] * r)
codes.extend(arc.codes[1:])
last_td += 360
arc = Path.arc(last_td, td)
xys.extend(arc.vertices[1:] * r)
codes.extend(arc.codes[1:])
else:
# The reverse version also relies on the fact that all
# codes but the first one are the same.
while last_td - td > 360:
arc = Path.arc(last_td - 360, last_td)
xys.extend(arc.vertices[::-1][1:] * r)
codes.extend(arc.codes[1:])
last_td -= 360
arc = Path.arc(td, last_td)
xys.extend(arc.vertices[::-1][1:] * r)
codes.extend(arc.codes[1:])
else: # Interpolate.
trs = cbook.simple_linear_interpolation(
np.vstack([(last_t, last_r), trs]),
path._interpolation_steps)[1:]
xys.extend(self.transform_non_affine(trs))
codes.extend([Path.LINETO] * len(trs))
else: # Not a straight line.
xys.extend(self.transform_non_affine(trs))
codes.extend([c] * len(trs))
last_t, last_r = trs[-1]
return Path(xys, codes)
def inverted(self):
# docstring inherited
return PolarAxes.InvertedPolarTransform(self._axis, self._use_rmin)
| PolarTransform |
python | pyqtgraph__pyqtgraph | pyqtgraph/opengl/MeshData.py | {
"start": 45,
"end": 22649
} | class ____(object):
"""
Class for storing and operating on 3D mesh data. May contain:
- list of vertex locations
- list of edges
- list of triangles
- colors per vertex, edge, or tri
- normals per vertex or tri
This class handles conversion between the standard [list of vertexes, list of faces]
format (suitable for use with glDrawElements) and 'indexed' [list of vertexes] format
(suitable for use with glDrawArrays). It will automatically compute face normal
vectors as well as averaged vertex normal vectors.
The class attempts to be as efficient as possible in caching conversion results and
avoiding unnecessary conversions.
"""
def __init__(self, vertexes=None, faces=None, edges=None, vertexColors=None, faceColors=None):
"""
============== =====================================================
**Arguments:**
vertexes (Nv, 3) array of vertex coordinates.
If faces is not specified, then this will instead be
interpreted as (Nf, 3, 3) array of coordinates.
faces (Nf, 3) array of indexes into the vertex array.
edges [not available yet]
vertexColors (Nv, 4) array of vertex colors.
If faces is not specified, then this will instead be
interpreted as (Nf, 3, 4) array of colors.
faceColors (Nf, 4) array of face colors.
============== =====================================================
All arguments are optional.
"""
self._vertexes = None # (Nv,3) array of vertex coordinates
self._vertexesIndexedByFaces = None # (Nf, 3, 3) array of vertex coordinates
self._vertexesIndexedByEdges = None # (Ne, 2, 3) array of vertex coordinates
## mappings between vertexes, faces, and edges
self._faces = None # Nx3 array of indexes into self._vertexes specifying three vertexes for each face
self._edges = None # Nx2 array of indexes into self._vertexes specifying two vertexes per edge
self._vertexFaces = None ## maps vertex ID to a list of face IDs (inverse mapping of _faces)
self._vertexEdges = None ## maps vertex ID to a list of edge IDs (inverse mapping of _edges)
## Per-vertex data
self._vertexNormals = None # (Nv, 3) array of normals, one per vertex
self._vertexNormalsIndexedByFaces = None # (Nf, 3, 3) array of normals
self._vertexColors = None # (Nv, 3) array of colors
self._vertexColorsIndexedByFaces = None # (Nf, 3, 4) array of colors
self._vertexColorsIndexedByEdges = None # (Nf, 2, 4) array of colors
## Per-face data
self._faceNormals = None # (Nf, 3) array of face normals
self._faceNormalsIndexedByFaces = None # (Nf, 3, 3) array of face normals
self._faceColors = None # (Nf, 4) array of face colors
self._faceColorsIndexedByFaces = None # (Nf, 3, 4) array of face colors
self._faceColorsIndexedByEdges = None # (Ne, 2, 4) array of face colors
## Per-edge data
self._edgeColors = None # (Ne, 4) array of edge colors
self._edgeColorsIndexedByEdges = None # (Ne, 2, 4) array of edge colors
#self._meshColor = (1, 1, 1, 0.1) # default color to use if no face/edge/vertex colors are given
if vertexes is not None:
if faces is None:
self.setVertexes(vertexes, indexed='faces')
if vertexColors is not None:
self.setVertexColors(vertexColors, indexed='faces')
if faceColors is not None:
self.setFaceColors(faceColors, indexed='faces')
else:
self.setVertexes(vertexes)
self.setFaces(faces)
if vertexColors is not None:
self.setVertexColors(vertexColors)
if faceColors is not None:
self.setFaceColors(faceColors)
def faces(self):
"""Return an array (Nf, 3) of vertex indexes, three per triangular face in the mesh.
If faces have not been computed for this mesh, the function returns None.
"""
return self._faces
def edges(self):
"""Return an array (Nf, 3) of vertex indexes, two per edge in the mesh."""
if self._edges is None:
self._computeEdges()
return self._edges
def setFaces(self, faces):
"""Set the (Nf, 3) array of faces. Each row in the array contains
three indexes into the vertex array, specifying the three corners
of a triangular face."""
self._faces = np.ascontiguousarray(faces, dtype=np.uint32)
self._edges = None
self._vertexFaces = None
self._vertexesIndexedByFaces = None
self.resetNormals()
self._vertexColorsIndexedByFaces = None
self._faceColorsIndexedByFaces = None
def vertexes(self, indexed=None):
"""Return an array (N,3) of the positions of vertexes in the mesh.
By default, each unique vertex appears only once in the array.
If indexed is 'faces', then the array will instead contain three vertexes
per face in the mesh (and a single vertex may appear more than once in the array)."""
if indexed is None:
if self._vertexes is None and self._vertexesIndexedByFaces is not None:
self._computeUnindexedVertexes()
return self._vertexes
elif indexed == 'faces':
if self._vertexesIndexedByFaces is None and self._vertexes is not None:
self._vertexesIndexedByFaces = self._vertexes[self.faces()]
return self._vertexesIndexedByFaces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
def setVertexes(self, verts=None, indexed=None, resetNormals=True):
"""
Set the array (Nv, 3) of vertex coordinates.
If indexed=='faces', then the data must have shape (Nf, 3, 3) and is
assumed to be already indexed as a list of faces.
This will cause any pre-existing normal vectors to be cleared
unless resetNormals=False.
"""
if indexed is None:
if verts is not None:
self._vertexes = np.ascontiguousarray(verts, dtype=np.float32)
self._vertexesIndexedByFaces = None
elif indexed=='faces':
self._vertexes = None
if verts is not None:
self._vertexesIndexedByFaces = np.ascontiguousarray(verts, dtype=np.float32)
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
if resetNormals:
self.resetNormals()
def resetNormals(self):
self._vertexNormals = None
self._vertexNormalsIndexedByFaces = None
self._faceNormals = None
self._faceNormalsIndexedByFaces = None
def hasFaceIndexedData(self):
"""Return True if this object already has vertex positions indexed by face"""
return self._vertexesIndexedByFaces is not None
def hasEdgeIndexedData(self):
return self._vertexesIndexedByEdges is not None
def hasVertexColor(self):
"""Return True if this data set has vertex color information"""
for v in (self._vertexColors, self._vertexColorsIndexedByFaces, self._vertexColorsIndexedByEdges):
if v is not None:
return True
return False
def hasFaceColor(self):
"""Return True if this data set has face color information"""
for v in (self._faceColors, self._faceColorsIndexedByFaces, self._faceColorsIndexedByEdges):
if v is not None:
return True
return False
def faceNormals(self, indexed=None):
"""
Return an array (Nf, 3) of normal vectors for each face.
If indexed='faces', then instead return an indexed array
(Nf, 3, 3) (this is just the same array with each vector
copied three times).
"""
if self._faceNormals is None:
v = self.vertexes(indexed='faces')
self._faceNormals = np.cross(v[:,1]-v[:,0], v[:,2]-v[:,0])
if indexed is None:
return self._faceNormals
elif indexed == 'faces':
if self._faceNormalsIndexedByFaces is None:
norms = np.empty((self._faceNormals.shape[0], 3, 3), dtype=np.float32)
norms[:] = self._faceNormals[:,np.newaxis,:]
self._faceNormalsIndexedByFaces = norms
return self._faceNormalsIndexedByFaces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
def vertexNormals(self, indexed=None):
"""
Return an array of normal vectors.
By default, the array will be (N, 3) with one entry per unique vertex in the mesh.
If indexed is 'faces', then the array will contain three normal vectors per face
(and some vertexes may be repeated).
"""
if self._vertexNormals is None:
faceNorms = self.faceNormals()
vertFaces = self.vertexFaces()
self._vertexNormals = np.empty(self._vertexes.shape, dtype=np.float32)
for vindex in range(self._vertexes.shape[0]):
faces = vertFaces[vindex]
if len(faces) == 0:
self._vertexNormals[vindex] = (0,0,0)
continue
norms = faceNorms[faces] ## get all face normals
norm = norms.sum(axis=0) ## sum normals
norm /= (norm**2).sum()**0.5 ## and re-normalize
self._vertexNormals[vindex] = norm
if indexed is None:
return self._vertexNormals
elif indexed == 'faces':
return self._vertexNormals[self.faces()]
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
@staticmethod
def _ensure_colors_dtype(colors):
if isinstance(colors, np.ndarray) and colors.dtype == np.uint8:
dtype = np.uint8
else:
dtype = np.float32
return np.ascontiguousarray(colors, dtype=dtype)
def vertexColors(self, indexed=None):
"""
Return an array (Nv, 4) of vertex colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4).
"""
if indexed is None:
return self._vertexColors
elif indexed == 'faces':
if self._vertexColorsIndexedByFaces is None:
self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
return self._vertexColorsIndexedByFaces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
def setVertexColors(self, colors, indexed=None):
"""
Set the vertex color array (Nv, 4).
If indexed=='faces', then the array will be interpreted
as indexed and should have shape (Nf, 3, 4)
"""
colors = self._ensure_colors_dtype(colors)
if indexed is None:
self._vertexColors = colors
self._vertexColorsIndexedByFaces = None
elif indexed == 'faces':
self._vertexColors = None
self._vertexColorsIndexedByFaces = colors
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
def faceColors(self, indexed=None):
"""
Return an array (Nf, 4) of face colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4) (note this is just the same array with each color
repeated three times).
"""
if indexed is None:
return self._faceColors
elif indexed == 'faces':
if self._faceColorsIndexedByFaces is None and self._faceColors is not None:
Nf = self._faceColors.shape[0]
self._faceColorsIndexedByFaces = np.empty((Nf, 3, 4), dtype=self._faceColors.dtype)
self._faceColorsIndexedByFaces[:] = self._faceColors.reshape(Nf, 1, 4)
return self._faceColorsIndexedByFaces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
def setFaceColors(self, colors, indexed=None):
"""
Set the face color array (Nf, 4).
If indexed=='faces', then the array will be interpreted
as indexed and should have shape (Nf, 3, 4)
"""
colors = self._ensure_colors_dtype(colors)
if indexed is None:
self._faceColors = colors
self._faceColorsIndexedByFaces = None
elif indexed == 'faces':
self._faceColors = None
self._faceColorsIndexedByFaces = colors
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
def faceCount(self):
"""
Return the number of faces in the mesh.
"""
if self._faces is not None:
return self._faces.shape[0]
elif self._vertexesIndexedByFaces is not None:
return self._vertexesIndexedByFaces.shape[0]
def edgeColors(self):
return self._edgeColors
#def _setIndexedFaces(self, faces, vertexColors=None, faceColors=None):
#self._vertexesIndexedByFaces = faces
#self._vertexColorsIndexedByFaces = vertexColors
#self._faceColorsIndexedByFaces = faceColors
def _computeUnindexedVertexes(self):
## Given (Nv, 3, 3) array of vertexes-indexed-by-face, convert backward to unindexed vertexes
## This is done by collapsing into a list of 'unique' vertexes (difference < 1e-14)
## I think generally this should be discouraged..
faces = self._vertexesIndexedByFaces
verts = {} ## used to remember the index of each vertex position
self._faces = np.empty(faces.shape[:2], dtype=np.uint32)
self._vertexes = []
self._vertexFaces = []
self._faceNormals = None
self._vertexNormals = None
for i in range(faces.shape[0]):
face = faces[i]
for j in range(face.shape[0]):
pt = face[j]
pt2 = tuple([round(x*1e14) for x in pt]) ## quantize to be sure that nearly-identical points will be merged
index = verts.get(pt2, None)
if index is None:
#self._vertexes.append(QtGui.QVector3D(*pt))
self._vertexes.append(pt)
self._vertexFaces.append([])
index = len(self._vertexes)-1
verts[pt2] = index
self._vertexFaces[index].append(i) # keep track of which vertexes belong to which faces
self._faces[i,j] = index
self._vertexes = np.array(self._vertexes, dtype=np.float32)
#def _setUnindexedFaces(self, faces, vertexes, vertexColors=None, faceColors=None):
#self._vertexes = vertexes #[QtGui.QVector3D(*v) for v in vertexes]
#self._faces = faces.astype(np.uint32)
#self._edges = None
#self._vertexFaces = None
#self._faceNormals = None
#self._vertexNormals = None
#self._vertexColors = vertexColors
#self._faceColors = faceColors
def vertexFaces(self):
"""
Return list mapping each vertex index to a list of face indexes that use the vertex.
"""
if self._vertexFaces is None:
self._vertexFaces = [[] for i in range(len(self.vertexes()))]
for i in range(self._faces.shape[0]):
face = self._faces[i]
for ind in face:
self._vertexFaces[ind].append(i)
return self._vertexFaces
#def reverseNormals(self):
#"""
#Reverses the direction of all normal vectors.
#"""
#pass
#def generateEdgesFromFaces(self):
#"""
#Generate a set of edges by listing all the edges of faces and removing any duplicates.
#Useful for displaying wireframe meshes.
#"""
#pass
def _computeEdges(self):
if not self.hasFaceIndexedData():
## generate self._edges from self._faces
nf = len(self._faces)
edges = np.empty(nf*3, dtype=[('i', np.uint32, 2)])
edges['i'][0:nf] = self._faces[:,:2]
edges['i'][nf:2*nf] = self._faces[:,1:3]
edges['i'][-nf:,0] = self._faces[:,2]
edges['i'][-nf:,1] = self._faces[:,0]
# sort per-edge
mask = edges['i'][:,0] > edges['i'][:,1]
edges['i'][mask] = edges['i'][mask][:,::-1]
# remove duplicate entries
self._edges = np.unique(edges)['i']
#print self._edges
elif self._vertexesIndexedByFaces is not None:
verts = self._vertexesIndexedByFaces
edges = np.empty((verts.shape[0], 3, 2), dtype=np.uint32)
nf = verts.shape[0]
edges[:,0,0] = np.arange(nf) * 3
edges[:,0,1] = edges[:,0,0] + 1
edges[:,1,0] = edges[:,0,1]
edges[:,1,1] = edges[:,1,0] + 1
edges[:,2,0] = edges[:,1,1]
edges[:,2,1] = edges[:,0,0]
self._edges = edges
else:
raise Exception("MeshData cannot generate edges--no faces in this data.")
def save(self):
"""Serialize this mesh to a string appropriate for disk storage"""
import pickle
if self._faces is not None:
names = ['_vertexes', '_faces']
else:
names = ['_vertexesIndexedByFaces']
if self._vertexColors is not None:
names.append('_vertexColors')
elif self._vertexColorsIndexedByFaces is not None:
names.append('_vertexColorsIndexedByFaces')
if self._faceColors is not None:
names.append('_faceColors')
elif self._faceColorsIndexedByFaces is not None:
names.append('_faceColorsIndexedByFaces')
state = dict([(n,getattr(self, n)) for n in names])
return pickle.dumps(state)
def restore(self, state):
"""Restore the state of a mesh previously saved using save()"""
import pickle
state = pickle.loads(state)
for k in state:
if isinstance(state[k], list):
if isinstance(state[k][0], QtGui.QVector3D):
state[k] = [[v.x(), v.y(), v.z()] for v in state[k]]
state[k] = np.array(state[k])
setattr(self, k, state[k])
@staticmethod
def sphere(rows, cols, radius=1.0, offset=True):
"""
Return a MeshData instance with vertexes and faces computed
for a spherical surface.
"""
verts = np.empty((rows+1, cols, 3), dtype=np.float32)
## compute vertexes
phi = (np.arange(rows+1) * np.pi / rows).reshape(rows+1, 1)
s = radius * np.sin(phi)
verts[...,2] = radius * np.cos(phi)
th = ((np.arange(cols) * 2 * np.pi / cols).reshape(1, cols))
if offset:
th = th + ((np.pi / cols) * np.arange(rows+1).reshape(rows+1,1)) ## rotate each row by 1/2 column
verts[...,0] = s * np.cos(th)
verts[...,1] = s * np.sin(th)
verts = verts.reshape((rows+1)*cols, 3)[cols-1:-(cols-1)] ## remove redundant vertexes from top and bottom
## compute faces
faces = np.empty((rows*cols*2, 3), dtype=np.uint32)
rowtemplate1 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]])
rowtemplate2 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]])
for row in range(rows):
start = row * cols * 2
faces[start:start+cols] = rowtemplate1 + row * cols
faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols
faces = faces[cols:-cols] ## cut off zero-area triangles at top and bottom
## adjust for redundant vertexes that were removed from top and bottom
vmin = cols-1
faces[faces<vmin] = vmin
faces -= vmin
vmax = verts.shape[0]-1
faces[faces>vmax] = vmax
return MeshData(vertexes=verts, faces=faces)
@staticmethod
def cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False):
"""
Return a MeshData instance with vertexes and faces computed
for a cylindrical surface.
The cylinder may be tapered with different radii at each end (truncated cone)
"""
verts = np.empty((rows+1, cols, 3), dtype=np.float32)
if isinstance(radius, int):
radius = [radius, radius] # convert to list
## compute vertexes
th = np.linspace(2 * np.pi, (2 * np.pi)/cols, cols).reshape(1, cols)
r = np.linspace(radius[0],radius[1],num=rows+1, endpoint=True).reshape(rows+1, 1) # radius as a function of z
verts[...,2] = np.linspace(0, length, num=rows+1, endpoint=True).reshape(rows+1, 1) # z
if offset:
th = th + ((np.pi / cols) * np.arange(rows+1).reshape(rows+1,1)) ## rotate each row by 1/2 column
verts[...,0] = r * np.cos(th) # x = r cos(th)
verts[...,1] = r * np.sin(th) # y = r sin(th)
verts = verts.reshape((rows+1)*cols, 3) # just reshape: no redundant vertices...
## compute faces
faces = np.empty((rows*cols*2, 3), dtype=np.uint32)
rowtemplate1 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]])
rowtemplate2 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]])
for row in range(rows):
start = row * cols * 2
faces[start:start+cols] = rowtemplate1 + row * cols
faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols
return MeshData(vertexes=verts, faces=faces)
| MeshData |
python | google__jax | jax/_src/pallas/core.py | {
"start": 3207,
"end": 3425
} | class ____(dtypes.extended):
"""Common dtype for all kinds of semaphore dtypes.
This is an abstract class that should never be instantiated, but rather
exists for the sake of `jnp.issubdtype`.
"""
| semaphore_dtype |
python | doocs__leetcode | solution/3300-3399/3364.Minimum Positive Sum Subarray/Solution.py | {
"start": 0,
"end": 367
} | class ____:
def minimumSumSubarray(self, nums: List[int], l: int, r: int) -> int:
n = len(nums)
ans = inf
for i in range(n):
s = 0
for j in range(i, n):
s += nums[j]
if l <= j - i + 1 <= r and s > 0:
ans = min(ans, s)
return -1 if ans == inf else ans
| Solution |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/proto/decode_proto_op_test.py | {
"start": 1025,
"end": 1270
} | class ____(test_base.DecodeProtoOpTestBase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
super(DecodeProtoOpTest, self).__init__(proto_ops, methodName)
if __name__ == '__main__':
test.main()
| DecodeProtoOpTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vision.py | {
"start": 4869,
"end": 5679
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook")
def test_minimal_green_path(self, mock_hook):
mock_hook.return_value.get_product_set.return_value = {}
op = CloudVisionGetProductSetOperator(
location=LOCATION_TEST, product_set_id=PRODUCTSET_ID_TEST, task_id="id"
)
op.execute(context=None)
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=None,
)
mock_hook.return_value.get_product_set.assert_called_once_with(
location=LOCATION_TEST,
product_set_id=PRODUCTSET_ID_TEST,
project_id=None,
retry=DEFAULT,
timeout=None,
metadata=(),
)
| TestCloudVisionProductSetGet |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_eks.py | {
"start": 3216,
"end": 15052
} | class ____:
def setup_method(self) -> None:
# Parameters which are needed to create a cluster.
self.create_cluster_params = ClusterParams(
cluster_name=CLUSTER_NAME,
cluster_role_arn=ROLE_ARN[1],
resources_vpc_config=RESOURCES_VPC_CONFIG[1],
)
self.nodegroup_setup()
self.fargate_profile_setup()
def nodegroup_setup(self) -> None:
# Parameters which are added to the cluster parameters
# when creating both the cluster and nodegroup together.
self.base_nodegroup_params = NodeGroupParams(
nodegroup_name=NODEGROUP_NAME,
nodegroup_role_arn=NODEROLE_ARN[1],
)
# Parameters expected to be passed in the CreateNodegroup hook call.
self.create_nodegroup_params = dict(
**self.base_nodegroup_params,
cluster_name=CLUSTER_NAME,
subnets=SUBNET_IDS,
)
self.create_cluster_operator_with_nodegroup = EksCreateClusterOperator(
task_id=TASK_ID,
**self.create_cluster_params,
**self.base_nodegroup_params,
)
def fargate_profile_setup(self) -> None:
# Parameters which are added to the cluster parameters
# when creating both the cluster and Fargate profile together.
self.base_fargate_profile_params = BaseFargateProfileParams(
fargate_profile_name=FARGATE_PROFILE_NAME,
fargate_pod_execution_role_arn=POD_EXECUTION_ROLE_ARN[1],
fargate_selectors=SELECTORS[1],
)
# Parameters expected to be passed in the CreateFargateProfile hook call.
self.create_fargate_profile_params = dict(
**self.base_fargate_profile_params,
cluster_name=CLUSTER_NAME,
)
self.create_cluster_operator_with_fargate_profile = EksCreateClusterOperator(
task_id=TASK_ID,
**self.create_cluster_params,
**self.base_fargate_profile_params,
compute="fargate",
)
@pytest.mark.parametrize(
"create_cluster_kwargs",
[
pytest.param(None, id="without cluster kwargs"),
pytest.param(CREATE_CLUSTER_KWARGS, id="with cluster kwargs"),
],
)
@mock.patch.object(EksHook, "create_cluster")
@mock.patch.object(EksHook, "create_nodegroup")
def test_execute_create_cluster(self, mock_create_nodegroup, mock_create_cluster, create_cluster_kwargs):
op_kwargs = {**self.create_cluster_params, "compute": None}
if create_cluster_kwargs:
op_kwargs["create_cluster_kwargs"] = create_cluster_kwargs
parameters = {**self.create_cluster_params, **create_cluster_kwargs}
else:
assert "create_cluster_kwargs" not in op_kwargs
parameters = self.create_cluster_params
operator = EksCreateClusterOperator(task_id=TASK_ID, **op_kwargs)
operator.execute({})
mock_create_cluster.assert_called_with(**convert_keys(parameters))
mock_create_nodegroup.assert_not_called()
@pytest.mark.parametrize(
"create_cluster_kwargs",
[
pytest.param(None, id="without cluster kwargs"),
pytest.param(CREATE_CLUSTER_KWARGS, id="with cluster kwargs"),
],
)
@mock.patch.object(Waiter, "wait")
@mock.patch.object(EksHook, "create_cluster")
@mock.patch.object(EksHook, "create_nodegroup")
def test_execute_create_cluster_with_wait(
self, mock_create_nodegroup, mock_create_cluster, mock_waiter, create_cluster_kwargs
):
op_kwargs = {**self.create_cluster_params, "compute": None}
if create_cluster_kwargs:
op_kwargs["create_cluster_kwargs"] = create_cluster_kwargs
parameters = {**self.create_cluster_params, **create_cluster_kwargs}
else:
assert "create_cluster_kwargs" not in op_kwargs
parameters = self.create_cluster_params
operator = EksCreateClusterOperator(task_id=TASK_ID, **op_kwargs, wait_for_completion=True)
operator.execute({})
mock_create_cluster.assert_called_with(**convert_keys(parameters))
mock_create_nodegroup.assert_not_called()
mock_waiter.assert_called_once_with(
mock.ANY,
name=CLUSTER_NAME,
WaiterConfig={"Delay": mock.ANY, "MaxAttempts": mock.ANY},
)
assert_expected_waiter_type(mock_waiter, "ClusterActive")
@mock.patch.object(Waiter, "wait")
@mock.patch.object(EksHook, "get_cluster_state")
@mock.patch.object(EksHook, "create_cluster")
@mock.patch.object(EksHook, "create_nodegroup")
def test_execute_when_called_with_nodegroup_creates_both(
self, mock_create_nodegroup, mock_create_cluster, mock_cluster_state, mock_waiter
):
mock_cluster_state.return_value = ClusterStates.ACTIVE
self.create_cluster_operator_with_nodegroup.execute({})
mock_create_cluster.assert_called_once_with(**convert_keys(self.create_cluster_params))
mock_create_nodegroup.assert_called_once_with(**convert_keys(self.create_nodegroup_params))
mock_waiter.assert_called_once_with(
mock.ANY,
name=CLUSTER_NAME,
WaiterConfig={"Delay": mock.ANY, "MaxAttempts": mock.ANY},
)
assert_expected_waiter_type(mock_waiter, "ClusterActive")
@mock.patch.object(Waiter, "wait")
@mock.patch.object(EksHook, "get_cluster_state")
@mock.patch.object(EksHook, "create_cluster")
@mock.patch.object(EksHook, "create_nodegroup")
def test_execute_with_wait_when_called_with_nodegroup_creates_both(
self, mock_create_nodegroup, mock_create_cluster, mock_cluster_state, mock_waiter
):
mock_cluster_state.return_value = ClusterStates.ACTIVE
self.create_cluster_operator_with_nodegroup.wait_for_completion = True
self.create_cluster_operator_with_nodegroup.execute({})
mock_create_cluster.assert_called_once_with(**convert_keys(self.create_cluster_params))
mock_create_nodegroup.assert_called_once_with(**convert_keys(self.create_nodegroup_params))
# Calls waiter once for the cluster and once for the nodegroup.
assert mock_waiter.call_count == 2
mock_waiter.assert_called_with(
mock.ANY,
clusterName=CLUSTER_NAME,
nodegroupName=NODEGROUP_NAME,
WaiterConfig={"MaxAttempts": mock.ANY},
)
assert_expected_waiter_type(mock_waiter, "NodegroupActive")
@mock.patch.object(Waiter, "wait")
@mock.patch.object(EksHook, "get_cluster_state")
@mock.patch.object(EksHook, "create_cluster")
@mock.patch.object(EksHook, "create_fargate_profile")
def test_execute_when_called_with_fargate_creates_both(
self, mock_create_fargate_profile, mock_create_cluster, mock_cluster_state, mock_waiter
):
mock_cluster_state.return_value = ClusterStates.ACTIVE
self.create_cluster_operator_with_fargate_profile.execute({})
mock_create_cluster.assert_called_once_with(**convert_keys(self.create_cluster_params))
mock_create_fargate_profile.assert_called_once_with(
**convert_keys(self.create_fargate_profile_params)
)
mock_waiter.assert_called_once_with(
mock.ANY,
name=CLUSTER_NAME,
WaiterConfig={"Delay": mock.ANY, "MaxAttempts": mock.ANY},
)
assert_expected_waiter_type(mock_waiter, "ClusterActive")
@mock.patch.object(Waiter, "wait")
@mock.patch.object(EksHook, "get_cluster_state")
@mock.patch.object(EksHook, "create_cluster")
@mock.patch.object(EksHook, "create_fargate_profile")
def test_execute_with_wait_when_called_with_fargate_creates_both(
self, mock_create_fargate_profile, mock_create_cluster, mock_cluster_state, mock_waiter
):
mock_cluster_state.return_value = ClusterStates.ACTIVE
self.create_cluster_operator_with_fargate_profile.wait_for_completion = True
self.create_cluster_operator_with_fargate_profile.execute({})
mock_create_cluster.assert_called_once_with(**convert_keys(self.create_cluster_params))
mock_create_fargate_profile.assert_called_once_with(
**convert_keys(self.create_fargate_profile_params)
)
# Calls waiter once for the cluster and once for the nodegroup.
assert mock_waiter.call_count == 2
mock_waiter.assert_called_with(
mock.ANY,
clusterName=CLUSTER_NAME,
fargateProfileName=FARGATE_PROFILE_NAME,
WaiterConfig={"MaxAttempts": mock.ANY},
)
assert_expected_waiter_type(mock_waiter, "FargateProfileActive")
def test_invalid_compute_value(self):
invalid_compute = EksCreateClusterOperator(
task_id=TASK_ID,
**self.create_cluster_params,
compute="infinite",
)
with pytest.raises(ValueError, match="Provided compute type is not supported."):
invalid_compute.execute({})
def test_nodegroup_compute_missing_nodegroup_role_arn(self):
missing_nodegroup_role_arn = EksCreateClusterOperator(
task_id=TASK_ID,
**self.create_cluster_params,
compute="nodegroup",
)
with pytest.raises(
ValueError,
match="Creating an Amazon EKS managed node groups requires nodegroup_role_arn to be passed in.",
):
missing_nodegroup_role_arn.execute({})
def test_fargate_compute_missing_fargate_pod_execution_role_arn(self):
missing_fargate_pod_execution_role_arn = EksCreateClusterOperator(
task_id=TASK_ID,
**self.create_cluster_params,
compute="fargate",
)
with pytest.raises(
ValueError,
match="Creating an AWS Fargate profiles requires fargate_pod_execution_role_arn to be passed in.",
):
missing_fargate_pod_execution_role_arn.execute({})
def test_init_with_region(self):
with pytest.warns(AirflowProviderDeprecationWarning) as m:
m.operator = EksCreateClusterOperator(
task_id=TASK_ID,
**self.create_cluster_params,
compute=None,
region="us-east-2",
)
assert m.operator.region_name == "us-east-2"
@mock.patch.object(EksHook, "create_cluster")
def test_eks_create_cluster_short_circuit_early(self, mock_create_cluster, caplog):
mock_create_cluster.return_value = None
eks_create_cluster_operator = EksCreateClusterOperator(
task_id=TASK_ID,
**self.create_cluster_params,
compute=None,
wait_for_completion=False,
deferrable=False,
)
eks_create_cluster_operator.execute({})
assert len(caplog.records) == 0
@mock.patch.object(EksHook, "create_cluster")
def test_eks_create_cluster_with_deferrable(self, mock_create_cluster, caplog):
mock_create_cluster.return_value = None
eks_create_cluster_operator = EksCreateClusterOperator(
task_id=TASK_ID,
**self.create_cluster_params,
compute=None,
wait_for_completion=False,
deferrable=True,
)
with pytest.raises(TaskDeferred):
eks_create_cluster_operator.execute({})
assert "Waiting for EKS Cluster to provision. This will take some time." in caplog.messages
def test_template_fields(self):
op = EksCreateClusterOperator(
task_id=TASK_ID, **self.create_cluster_params, compute="fargate", region_name="us-east-1"
)
validate_template_fields(op)
| TestEksCreateClusterOperator |
python | pypa__hatch | tests/backend/builders/test_config.py | {
"start": 67923,
"end": 73583
} | class ____:
def test_default(self, isolation):
builder = MockBuilder(str(isolation))
assert builder.config.include_spec is None
def test_global_becomes_spec(self, isolation):
config = {"tool": {"hatch": {"build": {"include": ["foo"]}}}}
builder = MockBuilder(str(isolation), config=config)
assert isinstance(builder.config.include_spec, pathspec.GitIgnoreSpec)
def test_global_invalid_type(self, isolation):
config = {"tool": {"hatch": {"build": {"include": ""}}}}
builder = MockBuilder(str(isolation), config=config)
with pytest.raises(TypeError, match="Field `tool.hatch.build.include` must be an array of strings"):
_ = builder.config.include_spec
@pytest.mark.parametrize("separator", ["/", "\\"])
def test_global(self, isolation, separator, platform):
if separator == "\\" and not platform.windows:
pytest.skip("Not running on Windows")
config = {"tool": {"hatch": {"build": {"include": ["foo", "bar/baz"]}}}}
builder = MockBuilder(str(isolation), config=config)
assert builder.config.include_spec.match_file(f"foo{separator}file.py")
assert builder.config.include_spec.match_file(f"bar{separator}baz{separator}file.py")
assert not builder.config.include_spec.match_file(f"bar{separator}file.py")
def test_global_pattern_not_string(self, isolation):
config = {"tool": {"hatch": {"build": {"include": [0]}}}}
builder = MockBuilder(str(isolation), config=config)
with pytest.raises(TypeError, match="Pattern #1 in field `tool.hatch.build.include` must be a string"):
_ = builder.config.include_spec
def test_global_pattern_empty_string(self, isolation):
config = {"tool": {"hatch": {"build": {"include": [""]}}}}
builder = MockBuilder(str(isolation), config=config)
with pytest.raises(
ValueError, match="Pattern #1 in field `tool.hatch.build.include` cannot be an empty string"
):
_ = builder.config.include_spec
@pytest.mark.parametrize("separator", ["/", "\\"])
def test_global_packages_included(self, isolation, separator, platform):
if separator == "\\" and not platform.windows:
pytest.skip("Not running on Windows")
config = {"tool": {"hatch": {"build": {"packages": ["bar"], "include": ["foo"]}}}}
builder = MockBuilder(str(isolation), config=config)
assert builder.config.include_spec.match_file(f"foo{separator}file.py")
assert builder.config.include_spec.match_file(f"bar{separator}baz{separator}file.py")
assert not builder.config.include_spec.match_file(f"baz{separator}bar{separator}file.py")
@pytest.mark.parametrize("separator", ["/", "\\"])
def test_target(self, isolation, separator, platform):
if separator == "\\" and not platform.windows:
pytest.skip("Not running on Windows")
config = {"tool": {"hatch": {"build": {"targets": {"foo": {"include": ["foo", "bar/baz"]}}}}}}
builder = MockBuilder(str(isolation), config=config)
builder.PLUGIN_NAME = "foo"
assert builder.config.include_spec.match_file(f"foo{separator}file.py")
assert builder.config.include_spec.match_file(f"bar{separator}baz{separator}file.py")
assert not builder.config.include_spec.match_file(f"bar{separator}file.py")
def test_target_pattern_not_string(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"foo": {"include": [0]}}}}}}
builder = MockBuilder(str(isolation), config=config)
builder.PLUGIN_NAME = "foo"
with pytest.raises(
TypeError, match="Pattern #1 in field `tool.hatch.build.targets.foo.include` must be a string"
):
_ = builder.config.include_spec
def test_target_pattern_empty_string(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"foo": {"include": [""]}}}}}}
builder = MockBuilder(str(isolation), config=config)
builder.PLUGIN_NAME = "foo"
with pytest.raises(
ValueError, match="Pattern #1 in field `tool.hatch.build.targets.foo.include` cannot be an empty string"
):
_ = builder.config.include_spec
@pytest.mark.parametrize("separator", ["/", "\\"])
def test_target_overrides_global(self, isolation, separator, platform):
if separator == "\\" and not platform.windows:
pytest.skip("Not running on Windows")
config = {"tool": {"hatch": {"build": {"include": ["foo"], "targets": {"foo": {"include": ["bar"]}}}}}}
builder = MockBuilder(str(isolation), config=config)
builder.PLUGIN_NAME = "foo"
assert not builder.config.include_spec.match_file(f"foo{separator}file.py")
assert builder.config.include_spec.match_file(f"bar{separator}file.py")
@pytest.mark.parametrize("separator", ["/", "\\"])
def test_target_packages_included(self, isolation, separator, platform):
if separator == "\\" and not platform.windows:
pytest.skip("Not running on Windows")
config = {"tool": {"hatch": {"build": {"targets": {"foo": {"packages": ["bar"], "include": ["foo"]}}}}}}
builder = MockBuilder(str(isolation), config=config)
builder.PLUGIN_NAME = "foo"
assert builder.config.include_spec.match_file(f"foo{separator}file.py")
assert builder.config.include_spec.match_file(f"bar{separator}baz{separator}file.py")
assert not builder.config.include_spec.match_file(f"baz{separator}bar{separator}file.py")
| TestPatternInclude |
python | explosion__spaCy | spacy/cli/init_config.py | {
"start": 675,
"end": 765
} | class ____(str, Enum):
efficiency = "efficiency"
accuracy = "accuracy"
| Optimizations |
python | walkccc__LeetCode | solutions/2485. Find the Pivot Integer/2485.py | {
"start": 0,
"end": 356
} | class ____:
def pivotInteger(self, n: int) -> int:
# 1 + 2 + ... + x = x + ... + n
# (1 + x) * x // 2 = (x + n) * (n - x + 1) // 2
# x + x^2 = nx - x^2 + x + n^2 - nx + n
# 2 * x^2 = n^2 + n
# x = sqrt((n^2 + n) // 2)
y = (n * n + n) // 2
x = math.isqrt(y)
return x if x * x == y else -1
| Solution |
python | streamlit__streamlit | lib/tests/streamlit/elements/heading_test.py | {
"start": 888,
"end": 6106
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall header protos."""
def test_st_header(self):
"""Test st.header."""
st.header("some header")
el = self.get_delta_from_queue().new_element
assert el.heading.body == "some header"
assert el.heading.tag == "h2"
assert not el.heading.hide_anchor
assert not el.heading.divider
def test_st_header_with_anchor(self):
"""Test st.header with anchor."""
st.header("some header", anchor="some-anchor")
el = self.get_delta_from_queue().new_element
assert el.heading.body == "some header"
assert el.heading.tag == "h2"
assert el.heading.anchor == "some-anchor"
assert not el.heading.hide_anchor
assert not el.heading.divider
def test_st_header_with_hidden_anchor(self):
"""Test st.header with hidden anchor."""
st.header("some header", anchor=False)
el = self.get_delta_from_queue().new_element
assert el.heading.body == "some header"
assert el.heading.tag == "h2"
assert el.heading.anchor == ""
assert el.heading.hide_anchor is True
assert not el.heading.divider
def test_st_header_with_invalid_anchor(self):
"""Test st.header with invalid anchor."""
with pytest.raises(StreamlitAPIException):
st.header("some header", anchor=True)
def test_st_header_with_help(self):
"""Test st.header with help."""
st.header("some header", help="help text")
el = self.get_delta_from_queue().new_element
assert el.heading.body == "some header"
assert el.heading.tag == "h2"
assert el.heading.help == "help text"
assert not el.heading.divider
def test_st_header_with_divider_true(self):
"""Test st.header with divider True."""
st.header("some header", divider=True)
el = self.get_delta_from_queue().new_element
assert el.heading.body == "some header"
assert el.heading.tag == "h2"
assert not el.heading.hide_anchor
assert el.heading.divider == "auto"
def test_st_header_with_divider_color(self):
"""Test st.header with divider color."""
st.header("some header", divider="blue")
el = self.get_delta_from_queue().new_element
assert el.heading.body == "some header"
assert el.heading.tag == "h2"
assert not el.heading.hide_anchor
assert el.heading.divider == "blue"
def test_st_header_with_invalid_divider(self):
"""Test st.header with invalid divider."""
with pytest.raises(StreamlitAPIException):
st.header("some header", divider="corgi")
def test_st_header_with_width(self):
"""Test st.header with different width types."""
test_cases = [
(500, WidthConfigFields.PIXEL_WIDTH.value, "pixel_width", 500),
("stretch", WidthConfigFields.USE_STRETCH.value, "use_stretch", True),
("content", WidthConfigFields.USE_CONTENT.value, "use_content", True),
]
for width_value, expected_width_spec, field_name, field_value in test_cases:
with self.subTest(width_value=width_value):
st.header("some header", width=width_value)
el = self.get_delta_from_queue().new_element
assert el.heading.body == "some header"
assert el.heading.tag == "h2"
assert el.width_config.WhichOneof("width_spec") == expected_width_spec
assert getattr(el.width_config, field_name) == field_value
def test_st_header_with_invalid_width(self):
"""Test st.header with invalid width values."""
test_cases = [
(
"invalid",
"Invalid width value: 'invalid'. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
-100,
"Invalid width value: -100. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
0,
"Invalid width value: 0. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
100.5,
"Invalid width value: 100.5. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
]
for width_value, expected_error_message in test_cases:
with self.subTest(width_value=width_value):
with pytest.raises(StreamlitAPIException) as exc:
st.header("some header", width=width_value)
assert str(exc.value) == expected_error_message
def test_st_header_default_width(self):
"""Test that st.header defaults to stretch width."""
st.header("some header")
el = self.get_delta_from_queue().new_element
assert el.heading.body == "some header"
assert el.heading.tag == "h2"
assert (
el.width_config.WhichOneof("width_spec")
== WidthConfigFields.USE_STRETCH.value
)
assert el.width_config.use_stretch is True
| StHeaderTest |
python | FactoryBoy__factory_boy | examples/flask_alchemy/demoapp.py | {
"start": 211,
"end": 558
} | class ____(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
| User |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 27885,
"end": 28319
} | class ____:
"""Holds counter state for invoking a method several times in a row."""
def __init__(self, count):
self.counter = 0
self.count = count
def go(self):
"""Return None until after count threshold has been crossed.
Then return True.
"""
if self.counter < self.count:
self.counter += 1
return None
return True
| NoneReturnUntilAfterCount |
python | run-llama__llama_index | llama-index-integrations/storage/index_store/llama-index-storage-index-store-elasticsearch/llama_index/storage/index_store/elasticsearch/base.py | {
"start": 187,
"end": 1040
} | class ____(KVIndexStore):
"""
Elasticsearch Index store.
Args:
elasticsearch_kvstore (ElasticsearchKVStore): Elasticsearch key-value store
namespace (str): namespace for the index store
"""
def __init__(
self,
elasticsearch_kvstore: ElasticsearchKVStore,
collection_index: Optional[str] = None,
namespace: Optional[str] = None,
collection_suffix: Optional[str] = None,
) -> None:
"""Init a ElasticsearchIndexStore."""
super().__init__(
elasticsearch_kvstore,
namespace=namespace,
collection_suffix=collection_suffix,
)
if collection_index:
self._collection = collection_index
else:
self._collection = f"llama_index-index_store.data-{self._namespace}"
| ElasticsearchIndexStore |
python | wandb__wandb | wandb/sdk/artifacts/storage_handlers/gcs_handler.py | {
"start": 1900,
"end": 9124
} | class ____(StorageHandler):
_scheme: str
_client: storage.Client | None
_cache: ArtifactFileCache
def __init__(self, scheme: str = "gs") -> None:
self._scheme = scheme
self._client = None
self._cache = get_artifact_file_cache()
def can_handle(self, parsed_url: ParseResult) -> bool:
return parsed_url.scheme == self._scheme
def init_gcs(self) -> storage.Client:
if self._client is not None:
return self._client
try:
from google.cloud import storage
except ImportError as e:
_handle_import_error(e)
self._client = storage.Client()
return self._client
def load_path(
self,
manifest_entry: ArtifactManifestEntry,
local: bool = False,
) -> URIStr | FilePathStr:
if (ref_uri := manifest_entry.ref) is None:
raise ValueError("Missing reference path/URI on artifact manifest entry")
if not local:
return ref_uri
expected_digest = manifest_entry.digest
expected_size = manifest_entry.size
path, hit, cache_open = self._cache.check_etag_obj_path(
url=ref_uri, etag=expected_digest, size=expected_size or 0
)
if hit:
return path
client = self.init_gcs()
gcs_path = _GCSPath.from_uri(ref_uri)
bucket = client.bucket(gcs_path.bucket)
# Skip downloading an entry that corresponds to a folder
if _is_dir(bucket, gcs_path.key, expected_size):
raise _GCSIsADirectoryError(
f"Unable to download GCS folder {ref_uri!r}, skipping"
)
# Try, in order:
obj = (
# First attempt to get the generation (specific version), if specified.
# Will return None if versioning is disabled.
(
(version_id := manifest_entry.extra.get("versionID")) is not None
and bucket.get_blob(gcs_path.key, generation=version_id)
)
or
# Object versioning is disabled on the bucket, or versionID isn't available,
# so just get the latest version and make sure the MD5 matches.
bucket.get_blob(gcs_path.key)
)
if obj is None:
raise ValueError(
f"Unable to download object {ref_uri!r} with generation {version_id!r}"
)
if (digest := obj.etag) != expected_digest:
raise ValueError(
f"Digest mismatch for object {ref_uri!r}: expected {expected_digest!r} but found {digest!r}"
)
with cache_open(mode="wb") as f:
obj.download_to_file(f)
return path
def store_path(
self,
artifact: Artifact,
path: URIStr | FilePathStr,
name: StrPath | None = None,
checksum: bool = True,
max_objects: int | None = None,
) -> list[ArtifactManifestEntry]:
client = self.init_gcs()
# After parsing any query params / fragments for additional context,
# such as version identifiers, pare down the path to just the bucket
# and key.
gcs_path = _GCSPath.from_uri(path)
path = f"{self._scheme}://{gcs_path.bucket}/{gcs_path.key}"
max_objects = max_objects or DEFAULT_MAX_OBJECTS
if not checksum:
return [
ArtifactManifestEntry(path=name or gcs_path.key, ref=path, digest=path)
]
bucket = client.bucket(gcs_path.bucket)
obj = bucket.get_blob(gcs_path.key, generation=gcs_path.version)
if (obj is None) and (gcs_path.version is not None):
raise ValueError(f"Object does not exist: {path}#{gcs_path.version}")
# HNS buckets store directory markers as blobs, so check the blob name
# to see if it represents a directory.
with TimedIf(multi := ((obj is None) or obj.name.endswith("/"))):
if multi:
termlog(
f"Generating checksum for up to {max_objects} objects with prefix {gcs_path.key!r}... ",
newline=False,
)
objects = bucket.list_blobs(
prefix=gcs_path.key, max_results=max_objects
)
else:
objects = [obj]
entries = [
self._entry_from_obj(obj, path, name, prefix=gcs_path.key, multi=multi)
for obj in objects
if obj and not obj.name.endswith("/")
]
if len(entries) > max_objects:
raise ValueError(
f"Exceeded {max_objects!r} objects tracked, pass max_objects to add_reference"
)
return entries
def _entry_from_obj(
self,
obj: storage.Blob,
path: str,
name: StrPath | None = None,
prefix: str = "",
multi: bool = False,
) -> ArtifactManifestEntry:
"""Create an ArtifactManifestEntry from a GCS object.
Args:
obj: The GCS object
path: The GCS-style path (e.g.: "gs://bucket/file.txt")
name: The user assigned name, or None if not specified
prefix: The prefix to add (will be the same as `path` for directories)
multi: Whether or not this is a multi-object add.
"""
uri = _GCSPath.from_uri(path)
# Always use posix paths, since that's what S3 uses.
posix_key = PurePosixPath(obj.name) # the bucket key
posix_path = PurePosixPath(uri.bucket, uri.key) # path without the scheme
posix_prefix = PurePosixPath(prefix) # the prefix, if adding a prefix
if name is None:
# We're adding a directory (prefix), so calculate a relative path.
if posix_prefix in posix_key.parents:
posix_name = posix_key.relative_to(posix_prefix)
posix_ref = posix_path / posix_name
else:
posix_name = PurePosixPath(posix_key.name)
posix_ref = posix_path
elif multi:
# We're adding a directory with a name override.
relpath = posix_key.relative_to(posix_prefix)
posix_name = PurePosixPath(name) / relpath
posix_ref = posix_path / relpath
else:
posix_name = PurePosixPath(name or "")
posix_ref = posix_path
return ArtifactManifestEntry(
path=posix_name,
ref=f"{self._scheme}://{posix_ref}",
digest=obj.etag,
size=obj.size,
extra={"versionID": obj.generation},
)
def _is_dir(bucket: storage.Bucket, key: str, entry_size: int | None) -> bool:
# A GCS folder key should end with a forward slash, but older manifest
# entries may omit it. To detect folders, check the size and extension,
# ensure there is no file with this reference, and confirm that the
# slash-suffixed reference exists as a folder in GCS.
return key.endswith("/") or (
not (entry_size or PurePosixPath(key).suffix)
and bucket.get_blob(key) is None
and bucket.get_blob(f"{key}/") is not None
)
| GCSHandler |
python | django__django | tests/auth_tests/test_remote_user.py | {
"start": 19286,
"end": 19446
} | class ____(RemoteUserMiddleware):
"""
Middleware that overrides custom HTTP auth user header.
"""
header = "HTTP_AUTHUSER"
| CustomHeaderMiddleware |
python | pola-rs__polars | py-polars/src/polars/dataframe/frame.py | {
"start": 5292,
"end": 441201
} | class ____:
"""
Two-dimensional data structure representing data as a table with rows and columns.
Parameters
----------
data : dict, Sequence, ndarray, Series, or pandas.DataFrame
Two-dimensional data in various forms; dict input must contain Sequences,
Generators, or a `range`. Sequence may contain Series or other Sequences.
schema : Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict
The schema of the resulting DataFrame. The schema may be declared in several
ways:
* As a dict of {name:type} pairs; if type is None, it will be auto-inferred.
* As a list of column names; in this case types are automatically inferred.
* As a list of (name,type) pairs; this is equivalent to the dictionary form.
If you supply a list of column names that does not match the names in the
underlying data, the names given here will overwrite them. The number
of names given in the schema should match the underlying data dimensions.
If set to `None` (default), the schema is inferred from the data.
schema_overrides : dict, default None
Support type specification or override of one or more columns; note that
any dtypes inferred from the schema param will be overridden.
The number of entries in the schema should match the underlying data
dimensions, unless a sequence of dictionaries is being passed, in which case
a *partial* schema can be declared to prevent specific fields from being loaded.
strict : bool, default True
Throw an error if any `data` value does not exactly match the given or inferred
data type for that column. If set to `False`, values that do not match the data
type are cast to that data type or, if casting is not possible, set to null
instead.
orient : {'col', 'row'}, default None
Whether to interpret two-dimensional data as columns or as rows. If None,
the orientation is inferred by matching the columns and data dimensions. If
this does not yield conclusive results, column orientation is used.
infer_schema_length : int or None
The maximum number of rows to scan for schema inference. If set to `None`, the
full data may be scanned *(this can be slow)*. This parameter only applies if
the input data is a sequence or generator of rows; other input is read as-is.
nan_to_null : bool, default False
If the data comes from one or more numpy arrays, can optionally convert input
data np.nan values to null instead. This is a no-op for all other input data.
Notes
-----
Polars explicitly does not support subclassing of its core data types. See
the following GitHub issue for possible workarounds:
https://github.com/pola-rs/polars/issues/2846#issuecomment-1711799869
Examples
--------
Constructing a DataFrame from a dictionary:
>>> data = {"a": [1, 2], "b": [3, 4]}
>>> df = pl.DataFrame(data)
>>> df
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 3 │
│ 2 ┆ 4 │
└─────┴─────┘
Notice that the dtypes are automatically inferred as polars Int64:
>>> df.dtypes
[Int64, Int64]
To specify a more detailed/specific frame schema you can supply the `schema`
parameter with a dictionary of (name,dtype) pairs...
>>> data = {"col1": [0, 2], "col2": [3, 7]}
>>> df2 = pl.DataFrame(data, schema={"col1": pl.Float32, "col2": pl.Int64})
>>> df2
shape: (2, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ --- ┆ --- │
│ f32 ┆ i64 │
╞══════╪══════╡
│ 0.0 ┆ 3 │
│ 2.0 ┆ 7 │
└──────┴──────┘
...a sequence of (name,dtype) pairs...
>>> data = {"col1": [1, 2], "col2": [3, 4]}
>>> df3 = pl.DataFrame(data, schema=[("col1", pl.Float32), ("col2", pl.Int64)])
>>> df3
shape: (2, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ --- ┆ --- │
│ f32 ┆ i64 │
╞══════╪══════╡
│ 1.0 ┆ 3 │
│ 2.0 ┆ 4 │
└──────┴──────┘
...or a list of typed Series.
>>> data = [
... pl.Series("col1", [1, 2], dtype=pl.Float32),
... pl.Series("col2", [3, 4], dtype=pl.Int64),
... ]
>>> df4 = pl.DataFrame(data)
>>> df4
shape: (2, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ --- ┆ --- │
│ f32 ┆ i64 │
╞══════╪══════╡
│ 1.0 ┆ 3 │
│ 2.0 ┆ 4 │
└──────┴──────┘
Constructing a DataFrame from a numpy ndarray, specifying column names:
>>> import numpy as np
>>> data = np.array([(1, 2), (3, 4)], dtype=np.int64)
>>> df5 = pl.DataFrame(data, schema=["a", "b"], orient="col")
>>> df5
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 3 │
│ 2 ┆ 4 │
└─────┴─────┘
Constructing a DataFrame from a list of lists, row orientation specified:
>>> data = [[1, 2, 3], [4, 5, 6]]
>>> df6 = pl.DataFrame(data, schema=["a", "b", "c"], orient="row")
>>> df6
shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 2 ┆ 3 │
│ 4 ┆ 5 ┆ 6 │
└─────┴─────┴─────┘
"""
_df: PyDataFrame
_accessors: ClassVar[set[str]] = {"plot", "style"}
def __init__(
self,
data: FrameInitTypes | None = None,
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
strict: bool = True,
orient: Orientation | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
nan_to_null: bool = False,
) -> None:
if data is None:
self._df = dict_to_pydf(
{}, schema=schema, schema_overrides=schema_overrides
)
elif isinstance(data, dict):
self._df = dict_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
nan_to_null=nan_to_null,
)
elif isinstance(data, (list, tuple, Sequence)):
self._df = sequence_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
orient=orient,
infer_schema_length=infer_schema_length,
nan_to_null=nan_to_null,
)
elif isinstance(data, pl.Series):
self._df = series_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, strict=strict
)
elif _check_for_numpy(data) and isinstance(data, np.ndarray):
self._df = numpy_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
orient=orient,
nan_to_null=nan_to_null,
)
elif _check_for_pyarrow(data) and isinstance(data, pa.Table):
self._df = arrow_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, strict=strict
)
elif _check_for_pandas(data) and isinstance(data, pd.DataFrame):
self._df = pandas_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, strict=strict
)
elif _check_for_torch(data) and isinstance(data, torch.Tensor):
self._df = numpy_to_pydf(
data.numpy(force=False),
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
orient=orient,
nan_to_null=nan_to_null,
)
elif (
not hasattr(data, "__arrow_c_stream__")
and not isinstance(data, Sized)
and isinstance(data, (Generator, Iterable))
):
self._df = iterable_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
orient=orient,
infer_schema_length=infer_schema_length,
)
elif isinstance(data, pl.DataFrame):
self._df = dataframe_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, strict=strict
)
elif is_pycapsule(data):
self._df = pycapsule_to_frame(
data,
schema=schema,
schema_overrides=schema_overrides,
)._df
else:
msg = (
f"DataFrame constructor called with unsupported type {type(data).__name__!r}"
" for the `data` parameter"
)
raise TypeError(msg)
@classmethod
def deserialize(
cls, source: str | Path | IOBase, *, format: SerializationFormat = "binary"
) -> DataFrame:
"""
Read a serialized DataFrame from a file.
Parameters
----------
source
Path to a file or a file-like object (by file-like object, we refer to
objects that have a `read()` method, such as a file handler (e.g.
via builtin `open` function) or `BytesIO`).
format
The format with which the DataFrame was serialized. Options:
- `"binary"`: Deserialize from binary format (bytes). This is the default.
- `"json"`: Deserialize from JSON format (string).
See Also
--------
DataFrame.serialize
Notes
-----
Serialization is not stable across Polars versions: a LazyFrame serialized
in one Polars version may not be deserializable in another Polars version.
Examples
--------
>>> import io
>>> df = pl.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]})
>>> bytes = df.serialize()
>>> pl.DataFrame.deserialize(io.BytesIO(bytes))
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪═════╡
│ 1 ┆ 4.0 │
│ 2 ┆ 5.0 │
│ 3 ┆ 6.0 │
└─────┴─────┘
"""
if isinstance(source, StringIO):
source = BytesIO(source.getvalue().encode())
elif isinstance(source, (str, Path)):
source = normalize_filepath(source)
if format == "binary":
deserializer = PyDataFrame.deserialize_binary
elif format == "json":
deserializer = PyDataFrame.deserialize_json
else:
msg = f"`format` must be one of {{'binary', 'json'}}, got {format!r}"
raise ValueError(msg)
return cls._from_pydf(deserializer(source))
@classmethod
def _from_pydf(cls, py_df: PyDataFrame) -> DataFrame:
"""Construct Polars DataFrame from FFI PyDataFrame object."""
df = cls.__new__(cls)
df._df = py_df
return df
@classmethod
def _from_arrow(
cls,
data: pa.Table | pa.RecordBatch,
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
rechunk: bool = True,
) -> DataFrame:
"""
Construct a DataFrame from an Arrow table.
This operation will be zero copy for the most part. Types that are not
supported by Polars may be cast to the closest supported type.
Parameters
----------
data : arrow Table, RecordBatch, or sequence of sequences
Data representing an Arrow Table or RecordBatch.
schema : Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict
The DataFrame schema may be declared in several ways:
* As a dict of {name:type} pairs; if type is None, it will be auto-inferred.
* As a list of column names; in this case types are automatically inferred.
* As a list of (name,type) pairs; this is equivalent to the dictionary form.
If you supply a list of column names that does not match the names in the
underlying data, the names given here will overwrite them. The number
of names given in the schema should match the underlying data dimensions.
schema_overrides : dict, default None
Support type specification or override of one or more columns; note that
any dtypes inferred from the columns param will be overridden.
rechunk : bool, default True
Make sure that all data is in contiguous memory.
"""
return cls._from_pydf(
arrow_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
rechunk=rechunk,
)
)
@classmethod
def _from_pandas(
cls,
data: pd.DataFrame,
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
rechunk: bool = True,
nan_to_null: bool = True,
include_index: bool = False,
) -> DataFrame:
"""
Construct a Polars DataFrame from a pandas DataFrame.
Parameters
----------
data : pandas DataFrame
Two-dimensional data represented as a pandas DataFrame.
schema : Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict
The DataFrame schema may be declared in several ways:
* As a dict of {name:type} pairs; if type is None, it will be auto-inferred.
* As a list of column names; in this case types are automatically inferred.
* As a list of (name,type) pairs; this is equivalent to the dictionary form.
If you supply a list of column names that does not match the names in the
underlying data, the names given here will overwrite them. The number
of names given in the schema should match the underlying data dimensions.
schema_overrides : dict, default None
Support type specification or override of one or more columns; note that
any dtypes inferred from the columns param will be overridden.
rechunk : bool, default True
Make sure that all data is in contiguous memory.
nan_to_null : bool, default True
If the data contains NaN values they will be converted to null/None.
include_index : bool, default False
Load any non-default pandas indexes as columns.
"""
return cls._from_pydf(
pandas_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
rechunk=rechunk,
nan_to_null=nan_to_null,
include_index=include_index,
)
)
def _replace(self, column: str, new_column: Series) -> DataFrame:
"""Replace a column by a new Series (in place)."""
self._df.replace(column, new_column._s)
return self
@classmethod
def _import_columns(cls, pointer: int, width: int) -> DataFrame:
return cls._from_pydf(PyDataFrame._import_columns(pointer, width))
@property
@unstable()
def plot(self) -> DataFramePlot:
"""
Create a plot namespace.
.. warning::
This functionality is currently considered **unstable**. It may be
changed at any point without it being considered a breaking change.
.. versionchanged:: 1.6.0
In prior versions of Polars, HvPlot was the plotting backend. If you would
like to restore the previous plotting functionality, all you need to do
is add `import hvplot.polars` at the top of your script and replace
`df.plot` with `df.hvplot`.
Polars does not implement plotting logic itself, but instead defers to
`Altair <https://altair-viz.github.io/>`_:
- `df.plot.line(**kwargs)`
is shorthand for
`alt.Chart(df).mark_line(tooltip=True).encode(**kwargs).interactive()`
- `df.plot.point(**kwargs)`
is shorthand for
`alt.Chart(df).mark_point(tooltip=True).encode(**kwargs).interactive()` (and
`plot.scatter` is provided as an alias)
- `df.plot.bar(**kwargs)`
is shorthand for
`alt.Chart(df).mark_bar(tooltip=True).encode(**kwargs).interactive()`
- for any other attribute `attr`, `df.plot.attr(**kwargs)`
is shorthand for
`alt.Chart(df).mark_attr(tooltip=True).encode(**kwargs).interactive()`
For configuration, we suggest reading
`Chart Configuration <https://altair-viz.github.io/altair-tutorial/notebooks/08-Configuration.html>`_.
For example, you can:
- Change the width/height/title with
``.properties(width=500, height=350, title="My amazing plot")``.
- Change the x-axis label rotation with ``.configure_axisX(labelAngle=30)``.
- Change the opacity of the points in your scatter plot with
``.configure_point(opacity=.5)``.
Examples
--------
Scatter plot:
>>> df = pl.DataFrame(
... {
... "length": [1, 4, 6],
... "width": [4, 5, 6],
... "species": ["setosa", "setosa", "versicolor"],
... }
... )
>>> df.plot.point(x="length", y="width", color="species") # doctest: +SKIP
Set the x-axis title by using ``altair.X``:
>>> import altair as alt
>>> df.plot.point(
... x=alt.X("length", title="Length"), y="width", color="species"
... ) # doctest: +SKIP
Line plot:
>>> from datetime import date
>>> df = pl.DataFrame(
... {
... "date": [date(2020, 1, 2), date(2020, 1, 3), date(2020, 1, 4)] * 2,
... "price": [1, 4, 6, 1, 5, 2],
... "stock": ["a", "a", "a", "b", "b", "b"],
... }
... )
>>> df.plot.line(x="date", y="price", color="stock") # doctest: +SKIP
Bar plot:
>>> df = pl.DataFrame(
... {
... "day": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] * 2,
... "group": ["a"] * 7 + ["b"] * 7,
... "value": [1, 3, 2, 4, 5, 6, 1, 1, 3, 2, 4, 5, 1, 2],
... }
... )
>>> df.plot.bar(
... x="day", y="value", color="day", column="group"
... ) # doctest: +SKIP
Or, to make a stacked version of the plot above:
>>> df.plot.bar(x="day", y="value", color="group") # doctest: +SKIP
"""
if not _ALTAIR_AVAILABLE or parse_version(altair.__version__) < (5, 4, 0):
msg = "altair>=5.4.0 is required for `.plot`"
raise ModuleUpgradeRequiredError(msg)
return DataFramePlot(self)
@property
@unstable()
def style(self) -> GT:
"""
Create a Great Table for styling.
.. warning::
This functionality is currently considered **unstable**. It may be
changed at any point without it being considered a breaking change.
Polars does not implement styling logic itself, but instead defers to
the Great Tables package. Please see the `Great Tables reference <https://posit-dev.github.io/great-tables/reference/>`_
for more information and documentation.
Examples
--------
Import some styling helpers, and create example data:
>>> import polars.selectors as cs
>>> from great_tables import loc, style
>>> df = pl.DataFrame(
... {
... "site_id": [0, 1, 2],
... "measure_a": [5, 4, 6],
... "measure_b": [7, 3, 3],
... }
... )
Emphasize the site_id as row names:
>>> df.style.tab_stub(rowname_col="site_id") # doctest: +SKIP
Fill the background for the highest measure_a value row:
>>> df.style.tab_style(
... style.fill("yellow"),
... loc.body(rows=pl.col("measure_a") == pl.col("measure_a").max()),
... ) # doctest: +SKIP
Put a spanner (high-level label) over measure columns:
>>> df.style.tab_spanner(
... "Measures", cs.starts_with("measure")
... ) # doctest: +SKIP
Format measure_b values to two decimal places:
>>> df.style.fmt_number("measure_b", decimals=2) # doctest: +SKIP
"""
if not _GREAT_TABLES_AVAILABLE:
msg = "great_tables is required for `.style`"
raise ModuleNotFoundError(msg)
return great_tables.GT(self)
@property
def shape(self) -> tuple[int, int]:
"""
Get the shape of the DataFrame.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5]})
>>> df.shape
(5, 1)
"""
return self._df.shape()
@property
def height(self) -> int:
"""
Get the number of rows.
Returns
-------
int
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5]})
>>> df.height
5
"""
return self._df.height()
@property
def width(self) -> int:
"""
Get the number of columns.
Returns
-------
int
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [4, 5, 6],
... }
... )
>>> df.width
2
"""
return self._df.width()
@property
def columns(self) -> list[str]:
"""
Get or set column names.
Returns
-------
list of str
A list containing the name of each column in order.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.columns
['foo', 'bar', 'ham']
Set column names:
>>> df.columns = ["apple", "banana", "orange"]
>>> df
shape: (3, 3)
┌───────┬────────┬────────┐
│ apple ┆ banana ┆ orange │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═══════╪════════╪════════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└───────┴────────┴────────┘
"""
return self._df.columns()
@columns.setter
def columns(self, names: Sequence[str]) -> None:
"""
Change the column names of the `DataFrame`.
Parameters
----------
names
A list with new names for the `DataFrame`.
The length of the list should be equal to the width of the `DataFrame`.
"""
self._df.set_column_names(names)
@property
def dtypes(self) -> list[DataType]:
"""
Get the column data types.
The data types can also be found in column headers when printing the DataFrame.
Returns
-------
list of DataType
A list containing the data type of each column in order.
See Also
--------
schema
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.dtypes
[Int64, Float64, String]
>>> df
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6.0 ┆ a │
│ 2 ┆ 7.0 ┆ b │
│ 3 ┆ 8.0 ┆ c │
└─────┴─────┴─────┘
"""
return self._df.dtypes()
@property
def flags(self) -> dict[str, dict[str, bool]]:
"""
Get flags that are set on the columns of this DataFrame.
Returns
-------
dict
Mapping from column names to column flags.
"""
return {name: self[name].flags for name in self.columns}
@property
def schema(self) -> Schema:
"""
Get an ordered mapping of column names to their data type.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.schema
Schema({'foo': Int64, 'bar': Float64, 'ham': String})
"""
return Schema(zip(self.columns, self.dtypes), check_dtypes=False)
def __array__(
self,
dtype: npt.DTypeLike | None = None,
copy: bool | None = None, # noqa: FBT001
) -> np.ndarray[Any, Any]:
"""
Return a NumPy ndarray with the given data type.
This method ensures a Polars DataFrame can be treated as a NumPy ndarray.
It enables `np.asarray` and NumPy universal functions.
See the NumPy documentation for more information:
https://numpy.org/doc/stable/user/basics.interoperability.html#the-array-method
"""
if copy is None:
writable, allow_copy = False, True
elif copy is True:
writable, allow_copy = True, True
elif copy is False:
writable, allow_copy = False, False
else:
msg = f"invalid input for `copy`: {copy!r}"
raise TypeError(msg)
arr = self.to_numpy(writable=writable, allow_copy=allow_copy)
if dtype is not None and dtype != arr.dtype:
if copy is False:
# TODO: Only raise when data must be copied
msg = f"copy not allowed: cast from {arr.dtype} to {dtype} prohibited"
raise RuntimeError(msg)
arr = arr.__array__(dtype)
return arr
def __dataframe__(
self,
nan_as_null: bool = False, # noqa: FBT001
allow_copy: bool = True, # noqa: FBT001
) -> PolarsDataFrame:
"""
Convert to a dataframe object implementing the dataframe interchange protocol.
Parameters
----------
nan_as_null
Overwrite null values in the data with `NaN`.
.. warning::
This functionality has not been implemented and the parameter will be
removed in a future version.
Setting this to `True` will raise a `NotImplementedError`.
allow_copy
Allow memory to be copied to perform the conversion. If set to `False`,
causes conversions that are not zero-copy to fail.
Notes
-----
Details on the Python dataframe interchange protocol:
https://data-apis.org/dataframe-protocol/latest/index.html
Examples
--------
Convert a Polars DataFrame to a generic dataframe object and access some
properties.
>>> df = pl.DataFrame({"a": [1, 2], "b": [3.0, 4.0], "c": ["x", "y"]})
>>> dfi = df.__dataframe__()
>>> dfi.num_rows()
2
>>> dfi.get_column(1).dtype
(<DtypeKind.FLOAT: 2>, 64, 'g', '=')
"""
if nan_as_null:
msg = (
"functionality for `nan_as_null` has not been implemented and the"
" parameter will be removed in a future version"
"\n\nUse the default `nan_as_null=False`."
)
raise NotImplementedError(msg)
from polars.interchange.dataframe import PolarsDataFrame
return PolarsDataFrame(self, allow_copy=allow_copy)
def _comp(self, other: Any, op: ComparisonOperator) -> DataFrame:
"""Compare a DataFrame with another object."""
if isinstance(other, DataFrame):
return self._compare_to_other_df(other, op)
else:
return self._compare_to_non_df(other, op)
def _compare_to_other_df(
self,
other: DataFrame,
op: ComparisonOperator,
) -> DataFrame:
"""Compare a DataFrame with another DataFrame."""
if self.columns != other.columns:
msg = "DataFrame columns do not match"
raise ValueError(msg)
if self.shape != other.shape:
msg = "DataFrame dimensions do not match"
raise ValueError(msg)
suffix = "__POLARS_CMP_OTHER"
other_renamed = other.select(F.all().name.suffix(suffix))
combined = F.concat([self, other_renamed], how="horizontal")
if op == "eq":
expr = [F.col(n) == F.col(f"{n}{suffix}") for n in self.columns]
elif op == "neq":
expr = [F.col(n) != F.col(f"{n}{suffix}") for n in self.columns]
elif op == "gt":
expr = [F.col(n) > F.col(f"{n}{suffix}") for n in self.columns]
elif op == "lt":
expr = [F.col(n) < F.col(f"{n}{suffix}") for n in self.columns]
elif op == "gt_eq":
expr = [F.col(n) >= F.col(f"{n}{suffix}") for n in self.columns]
elif op == "lt_eq":
expr = [F.col(n) <= F.col(f"{n}{suffix}") for n in self.columns]
else:
msg = f"unexpected comparison operator {op!r}"
raise ValueError(msg)
return combined.select(expr)
def _compare_to_non_df(
self,
other: Any,
op: ComparisonOperator,
) -> DataFrame:
"""Compare a DataFrame with a non-DataFrame object."""
warn_null_comparison(other)
if op == "eq":
return self.select(F.all() == other)
elif op == "neq":
return self.select(F.all() != other)
elif op == "gt":
return self.select(F.all() > other)
elif op == "lt":
return self.select(F.all() < other)
elif op == "gt_eq":
return self.select(F.all() >= other)
elif op == "lt_eq":
return self.select(F.all() <= other)
else:
msg = f"unexpected comparison operator {op!r}"
raise ValueError(msg)
def _div(self, other: Any, *, floordiv: bool) -> DataFrame:
if isinstance(other, pl.Series):
if floordiv:
return self.select(F.all() // lit(other))
return self.select(F.all() / lit(other))
elif not isinstance(other, DataFrame):
s = _prepare_other_arg(other, length=self.height)
other = DataFrame([s.alias(f"n{i}") for i in range(self.width)])
orig_dtypes = other.dtypes
# TODO: Dispatch to a native floordiv
other = self._cast_all_from_to(other, INTEGER_DTYPES, Float64)
df = self._from_pydf(self._df.div_df(other._df))
df = (
df
if not floordiv
else df.with_columns([s.floor() for s in df if s.dtype.is_float()])
)
if floordiv:
int_casts = [
col(column).cast(tp)
for i, (column, tp) in enumerate(self.schema.items())
if tp.is_integer()
and (orig_dtypes[i].is_integer() or orig_dtypes[i] == Null)
]
if int_casts:
return df.with_columns(int_casts)
return df
def _cast_all_from_to(
self, df: DataFrame, from_: frozenset[PolarsDataType], to: PolarsDataType
) -> DataFrame:
casts = [s.cast(to).alias(s.name) for s in df if s.dtype in from_]
return df.with_columns(casts) if casts else df
def __floordiv__(self, other: DataFrame | Series | int | float) -> DataFrame:
return self._div(other, floordiv=True)
def __truediv__(self, other: DataFrame | Series | int | float) -> DataFrame:
return self._div(other, floordiv=False)
def __bool__(self) -> NoReturn:
msg = (
"the truth value of a DataFrame is ambiguous"
"\n\nHint: to check if a DataFrame contains any values, use `is_empty()`."
)
raise TypeError(msg)
def __eq__(self, other: object) -> DataFrame: # type: ignore[override]
return self._comp(other, "eq")
def __ne__(self, other: object) -> DataFrame: # type: ignore[override]
return self._comp(other, "neq")
def __gt__(self, other: Any) -> DataFrame:
return self._comp(other, "gt")
def __lt__(self, other: Any) -> DataFrame:
return self._comp(other, "lt")
def __ge__(self, other: Any) -> DataFrame:
return self._comp(other, "gt_eq")
def __le__(self, other: Any) -> DataFrame:
return self._comp(other, "lt_eq")
def __getstate__(self) -> bytes:
return self.serialize()
def __setstate__(self, state: bytes) -> None:
self._df = self.deserialize(BytesIO(state))._df
def __mul__(self, other: DataFrame | Series | int | float) -> DataFrame:
if isinstance(other, DataFrame):
return self._from_pydf(self._df.mul_df(other._df))
other = _prepare_other_arg(other)
return self._from_pydf(self._df.mul(other._s))
def __rmul__(self, other: int | float) -> DataFrame:
return self * other
def __add__(
self, other: DataFrame | Series | int | float | bool | str
) -> DataFrame:
if isinstance(other, DataFrame):
return self._from_pydf(self._df.add_df(other._df))
other = _prepare_other_arg(other)
return self._from_pydf(self._df.add(other._s))
def __radd__(
self, other: DataFrame | Series | int | float | bool | str
) -> DataFrame:
if isinstance(other, str):
return self.select((lit(other) + F.col("*")).name.keep())
return self + other
def __sub__(self, other: DataFrame | Series | int | float) -> DataFrame:
if isinstance(other, DataFrame):
return self._from_pydf(self._df.sub_df(other._df))
other = _prepare_other_arg(other)
return self._from_pydf(self._df.sub(other._s))
def __mod__(self, other: DataFrame | Series | int | float) -> DataFrame:
if isinstance(other, DataFrame):
return self._from_pydf(self._df.rem_df(other._df))
other = _prepare_other_arg(other)
return self._from_pydf(self._df.rem(other._s))
def __str__(self) -> str:
return self._df.as_str()
def __repr__(self) -> str:
return self.__str__()
def __contains__(self, key: str) -> bool:
return key in self.columns
def __iter__(self) -> Iterator[Series]:
return self.iter_columns()
def __reversed__(self) -> Iterator[Series]:
return reversed(self.get_columns())
# `str` overlaps with `Sequence[str]`
# We can ignore this but we must keep this overload ordering
@overload
def __getitem__(
self, key: tuple[SingleIndexSelector, SingleColSelector]
) -> Any: ...
@overload
def __getitem__( # type: ignore[overload-overlap]
self, key: str | tuple[MultiIndexSelector, SingleColSelector]
) -> Series: ...
@overload
def __getitem__(
self,
key: (
SingleIndexSelector
| MultiIndexSelector
| MultiColSelector
| tuple[SingleIndexSelector, MultiColSelector]
| tuple[MultiIndexSelector, MultiColSelector]
),
) -> DataFrame: ...
def __getitem__(
self,
key: (
SingleIndexSelector
| SingleColSelector
| MultiColSelector
| MultiIndexSelector
| tuple[SingleIndexSelector, SingleColSelector]
| tuple[SingleIndexSelector, MultiColSelector]
| tuple[MultiIndexSelector, SingleColSelector]
| tuple[MultiIndexSelector, MultiColSelector]
),
) -> DataFrame | Series | Any:
"""
Get part of the DataFrame as a new DataFrame, Series, or scalar.
Parameters
----------
key
Rows / columns to select. This is easiest to explain via example. Suppose
we have a DataFrame with columns `'a'`, `'d'`, `'c'`, `'d'`. Here is what
various types of `key` would do:
- `df[0, 'a']` extracts the first element of column `'a'` and returns a
scalar.
- `df[0]` extracts the first row and returns a Dataframe.
- `df['a']` extracts column `'a'` and returns a Series.
- `df[0:2]` extracts the first two rows and returns a Dataframe.
- `df[0:2, 'a']` extracts the first two rows from column `'a'` and returns
a Series.
- `df[0:2, 0]` extracts the first two rows from the first column and returns
a Series.
- `df[[0, 1], [0, 1, 2]]` extracts the first two rows and the first three
columns and returns a Dataframe.
- `df[0: 2, ['a', 'c']]` extracts the first two rows from columns `'a'` and
`'c'` and returns a Dataframe.
- `df[:, 0: 2]` extracts all rows from the first two columns and returns a
Dataframe.
- `df[:, 'a': 'c']` extracts all rows and all columns positioned between
`'a'` and `'c'` *inclusive* and returns a Dataframe. In our example,
that would extract columns `'a'`, `'d'`, and `'c'`.
Returns
-------
DataFrame, Series, or scalar, depending on `key`.
Examples
--------
>>> df = pl.DataFrame(
... {"a": [1, 2, 3], "d": [4, 5, 6], "c": [1, 3, 2], "b": [7, 8, 9]}
... )
>>> df[0]
shape: (1, 4)
┌─────┬─────┬─────┬─────┐
│ a ┆ d ┆ c ┆ b │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╡
│ 1 ┆ 4 ┆ 1 ┆ 7 │
└─────┴─────┴─────┴─────┘
>>> df[0, "a"]
1
>>> df["a"]
shape: (3,)
Series: 'a' [i64]
[
1
2
3
]
>>> df[0:2]
shape: (2, 4)
┌─────┬─────┬─────┬─────┐
│ a ┆ d ┆ c ┆ b │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╡
│ 1 ┆ 4 ┆ 1 ┆ 7 │
│ 2 ┆ 5 ┆ 3 ┆ 8 │
└─────┴─────┴─────┴─────┘
>>> df[0:2, "a"]
shape: (2,)
Series: 'a' [i64]
[
1
2
]
>>> df[0:2, 0]
shape: (2,)
Series: 'a' [i64]
[
1
2
]
>>> df[[0, 1], [0, 1, 2]]
shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ d ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 4 ┆ 1 │
│ 2 ┆ 5 ┆ 3 │
└─────┴─────┴─────┘
>>> df[0:2, ["a", "c"]]
shape: (2, 2)
┌─────┬─────┐
│ a ┆ c │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 1 │
│ 2 ┆ 3 │
└─────┴─────┘
>>> df[:, 0:2]
shape: (3, 2)
┌─────┬─────┐
│ a ┆ d │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 4 │
│ 2 ┆ 5 │
│ 3 ┆ 6 │
└─────┴─────┘
>>> df[:, "a":"c"]
shape: (3, 3)
┌─────┬─────┬─────┐
│ a ┆ d ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 4 ┆ 1 │
│ 2 ┆ 5 ┆ 3 │
│ 3 ┆ 6 ┆ 2 │
└─────┴─────┴─────┘
"""
return get_df_item_by_key(self, key)
def __setitem__(
self,
key: str | Sequence[int] | Sequence[str] | tuple[Any, str | int],
value: Any,
) -> None: # pragma: no cover
"""
Modify DataFrame elements in place, using assignment syntax.
Parameters
----------
key : str | Sequence[int] | Sequence[str] | tuple[Any, str | int]
Specifies the location(s) within the DataFrame to assign new values.
The behavior varies based on the type of `key`:
- Str: `df["a"] = value`:
Not supported. Raises a `TypeError`. Use `df.with_columns(...)`
to add or modify columns.
- Sequence[str]: `df[["a", "b"]] = value`:
Assigns multiple columns at once. `value` must be a 2D array-like
structure with the same number of columns as the list
of column names provided.
- tuple[Any, str | int]: `df[row_idx, "a"] = value`:
Assigns a new value to a specific element in the DataFrame, where
`row_idx` specifies the row and `"a"` specifies the column.
- `df[row_idx, col_idx] = value`:
Similar to the above, but `col_idx` is the integer index of the column.
value : Any
The new value(s) to assign. The expected structure of `value` depends on the
form of `key`:
- For multiple column assignment (`df[["a", "b"]] = value`), `value` should
be a 2D array-like object with shape (n_rows, n_columns).
- For single element assignment (`df[row_idx, "a"] = value`), `value` should
be a scalar.
Raises
------
TypeError
If an unsupported assignment is attempted, such as assigning a Series
directly to a column using `df["a"] = series`.
ValueError
If the shape of `value` does not match the expected shape based on `key`.
Examples
--------
Sequence[str] : `df[["a", "b"]] = value`:
>>> import numpy as np
>>> df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
>>> df[["a", "b"]] = np.array([[10, 40], [20, 50], [30, 60]])
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 10 ┆ 40 │
│ 20 ┆ 50 │
│ 30 ┆ 60 │
└─────┴─────┘
tuple[Any, str | int] : `df[row_idx, "a"] = value`:
>>> df[1, "a"] = 100
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 10 ┆ 40 │
│ 100 ┆ 50 │
│ 30 ┆ 60 │
└─────┴─────┘
`df[row_idx, col_idx] = value`:
>>> df[0, 1] = 30
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 10 ┆ 30 │
│ 100 ┆ 50 │
│ 30 ┆ 60 │
└─────┴─────┘
"""
# df["foo"] = series
if isinstance(key, str):
msg = (
"DataFrame object does not support `Series` assignment by index"
"\n\nUse `DataFrame.with_columns`."
)
raise TypeError(msg)
# df[["C", "D"]]
elif isinstance(key, list):
# TODO: Use python sequence constructors
value = np.array(value)
if value.ndim != 2:
msg = "can only set multiple columns with 2D matrix"
raise ValueError(msg)
if value.shape[1] != len(key):
msg = "matrix columns should be equal to list used to determine column names"
raise ValueError(msg)
# TODO: we can parallelize this by calling from_numpy
columns = []
for i, name in enumerate(key):
columns.append(pl.Series(name, value[:, i]))
self._df = self.with_columns(columns)._df
# df[a, b]
elif isinstance(key, tuple):
row_selection, col_selection = key
if (
isinstance(row_selection, pl.Series) and row_selection.dtype == Boolean
) or is_bool_sequence(row_selection):
msg = (
"not allowed to set DataFrame by boolean mask in the row position"
"\n\nConsider using `DataFrame.with_columns`."
)
raise TypeError(msg)
# get series column selection
if isinstance(col_selection, str):
s = self.__getitem__(col_selection)
elif isinstance(col_selection, int):
s = self[:, col_selection]
else:
msg = f"unexpected column selection {col_selection!r}"
raise TypeError(msg)
# dispatch to __setitem__ of Series to do modification
s[row_selection] = value
# now find the location to place series
# df[idx]
if isinstance(col_selection, int):
self.replace_column(col_selection, s)
# df["foo"]
elif isinstance(col_selection, str):
self._replace(col_selection, s)
else:
msg = (
f"cannot use `__setitem__` on DataFrame"
f" with key {key!r} of type {type(key).__name__!r}"
f" and value {value!r} of type {type(value).__name__!r}"
)
raise TypeError(msg)
def __len__(self) -> int:
return self.height
def __copy__(self) -> DataFrame:
return self.clone()
def __deepcopy__(self, memo: None = None) -> DataFrame:
return self.clone()
def _ipython_key_completions_(self) -> list[str]:
return self.columns
def __arrow_c_stream__(self, requested_schema: object | None = None) -> object:
"""
Export a DataFrame via the Arrow PyCapsule Interface.
https://arrow.apache.org/docs/dev/format/CDataInterface/PyCapsuleInterface.html
"""
return self._df.__arrow_c_stream__(requested_schema)
def _repr_html_(self, *, _from_series: bool = False) -> str:
"""
Format output data in HTML for display in Jupyter Notebooks.
Output rows and columns can be modified by setting the following ENVIRONMENT
variables:
* POLARS_FMT_MAX_COLS: set the number of columns
* POLARS_FMT_MAX_ROWS: set the number of rows
"""
max_cols = int(os.environ.get("POLARS_FMT_MAX_COLS", default=75))
if max_cols < 0:
max_cols = self.width
max_rows = int(os.environ.get("POLARS_FMT_MAX_ROWS", default=10))
if max_rows < 0:
max_rows = self.height
return "".join(
NotebookFormatter(
self,
max_cols=max_cols,
max_rows=max_rows,
from_series=_from_series,
).render()
)
def collect_schema(self) -> Schema:
"""
Get an ordered mapping of column names to their data type.
This is an alias for the :attr:`schema` property.
See Also
--------
schema
Notes
-----
This method is included to facilitate writing code that is generic for both
DataFrame and LazyFrame.
Examples
--------
Determine the schema.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.collect_schema()
Schema({'foo': Int64, 'bar': Float64, 'ham': String})
Access various properties of the schema using the :class:`Schema` object.
>>> schema = df.collect_schema()
>>> schema["bar"]
Float64
>>> schema.names()
['foo', 'bar', 'ham']
>>> schema.dtypes()
[Int64, Float64, String]
>>> schema.len()
3
"""
return self.schema
def item(self, row: int | None = None, column: int | str | None = None) -> Any:
"""
Return the DataFrame as a scalar, or return the element at the given row/column.
Parameters
----------
row
Optional row index.
column
Optional column index or name.
See Also
--------
row : Get the values of a single row, either by index or by predicate.
Notes
-----
If row/col not provided, this is equivalent to `df[0,0]`, with a check that
the shape is (1,1). With row/col, this is equivalent to `df[row,col]`.
Examples
--------
>>> df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
>>> df.select((pl.col("a") * pl.col("b")).sum()).item()
32
>>> df.item(1, 1)
5
>>> df.item(2, "b")
6
"""
if row is None and column is None:
if self.shape != (1, 1):
msg = (
'can only call `.item()` without "row" or "column" values if the '
f"DataFrame has a single element; shape={self.shape!r}"
)
raise ValueError(msg)
return self._df.to_series(0).get_index(0)
elif row is None or column is None:
msg = "cannot call `.item()` with only one of `row` or `column`"
raise ValueError(msg)
s = (
self._df.to_series(column)
if isinstance(column, int)
else self._df.get_column(column)
)
return s.get_index_signed(row)
@deprecate_renamed_parameter("future", "compat_level", version="1.1")
def to_arrow(self, *, compat_level: CompatLevel | None = None) -> pa.Table:
"""
Collect the underlying arrow arrays in an Arrow Table.
This operation is mostly zero copy.
Data types that do copy:
- CategoricalType
.. versionchanged:: 1.1
The `future` parameter was renamed `compat_level`.
Parameters
----------
compat_level
Use a specific compatibility level
when exporting Polars' internal data structures.
Examples
--------
>>> df = pl.DataFrame(
... {"foo": [1, 2, 3, 4, 5, 6], "bar": ["a", "b", "c", "d", "e", "f"]}
... )
>>> df.to_arrow()
pyarrow.Table
foo: int64
bar: large_string
----
foo: [[1,2,3,4,5,6]]
bar: [["a","b","c","d","e","f"]]
"""
if not self.width: # 0x0 dataframe, cannot infer schema from batches
return pa.table({})
compat_level_py: int | bool
if compat_level is None:
compat_level_py = False
elif isinstance(compat_level, CompatLevel):
compat_level_py = compat_level._version
record_batches = self._df.to_arrow(compat_level_py)
return pa.Table.from_batches(record_batches)
@overload
def to_dict(self, *, as_series: Literal[True] = ...) -> dict[str, Series]: ...
@overload
def to_dict(self, *, as_series: Literal[False]) -> dict[str, list[Any]]: ...
@overload
def to_dict(
self, *, as_series: bool
) -> dict[str, Series] | dict[str, list[Any]]: ...
def to_dict(
self, *, as_series: bool = True
) -> dict[str, Series] | dict[str, list[Any]]:
"""
Convert DataFrame to a dictionary mapping column name to values.
Parameters
----------
as_series
True -> Values are Series
False -> Values are List[Any]
See Also
--------
rows_by_key
to_dicts
Examples
--------
>>> df = pl.DataFrame(
... {
... "A": [1, 2, 3, 4, 5],
... "fruits": ["banana", "banana", "apple", "apple", "banana"],
... "B": [5, 4, 3, 2, 1],
... "cars": ["beetle", "audi", "beetle", "beetle", "beetle"],
... "optional": [28, 300, None, 2, -30],
... }
... )
>>> df
shape: (5, 5)
┌─────┬────────┬─────┬────────┬──────────┐
│ A ┆ fruits ┆ B ┆ cars ┆ optional │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ i64 ┆ str ┆ i64 │
╞═════╪════════╪═════╪════════╪══════════╡
│ 1 ┆ banana ┆ 5 ┆ beetle ┆ 28 │
│ 2 ┆ banana ┆ 4 ┆ audi ┆ 300 │
│ 3 ┆ apple ┆ 3 ┆ beetle ┆ null │
│ 4 ┆ apple ┆ 2 ┆ beetle ┆ 2 │
│ 5 ┆ banana ┆ 1 ┆ beetle ┆ -30 │
└─────┴────────┴─────┴────────┴──────────┘
>>> df.to_dict(as_series=False)
{'A': [1, 2, 3, 4, 5],
'fruits': ['banana', 'banana', 'apple', 'apple', 'banana'],
'B': [5, 4, 3, 2, 1],
'cars': ['beetle', 'audi', 'beetle', 'beetle', 'beetle'],
'optional': [28, 300, None, 2, -30]}
>>> df.to_dict(as_series=True)
{'A': shape: (5,)
Series: 'A' [i64]
[
1
2
3
4
5
], 'fruits': shape: (5,)
Series: 'fruits' [str]
[
"banana"
"banana"
"apple"
"apple"
"banana"
], 'B': shape: (5,)
Series: 'B' [i64]
[
5
4
3
2
1
], 'cars': shape: (5,)
Series: 'cars' [str]
[
"beetle"
"audi"
"beetle"
"beetle"
"beetle"
], 'optional': shape: (5,)
Series: 'optional' [i64]
[
28
300
null
2
-30
]}
"""
if as_series:
return {s.name: s for s in self}
else:
return {s.name: s.to_list() for s in self}
def to_dicts(self) -> list[dict[str, Any]]:
"""
Convert every row to a dictionary of Python-native values.
Notes
-----
If you have `ns`-precision temporal values you should be aware that Python
natively only supports up to `μs`-precision; `ns`-precision values will be
truncated to microseconds on conversion to Python. If this matters to your
use-case you should export to a different format (such as Arrow or NumPy).
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
>>> df.to_dicts()
[{'foo': 1, 'bar': 4}, {'foo': 2, 'bar': 5}, {'foo': 3, 'bar': 6}]
"""
return self.rows(named=True)
def to_numpy(
self,
*,
order: IndexOrder = "fortran",
writable: bool = False,
allow_copy: bool = True,
structured: bool = False,
use_pyarrow: bool | None = None,
) -> np.ndarray[Any, Any]:
"""
Convert this DataFrame to a NumPy ndarray.
This operation copies data only when necessary. The conversion is zero copy when
all of the following hold:
- The DataFrame is fully contiguous in memory, with all Series back-to-back and
all Series consisting of a single chunk.
- The data type is an integer or float.
- The DataFrame contains no null values.
- The `order` parameter is set to `fortran` (default).
- The `writable` parameter is set to `False` (default).
Parameters
----------
order
The index order of the returned NumPy array, either C-like or
Fortran-like. In general, using the Fortran-like index order is faster.
However, the C-like order might be more appropriate to use for downstream
applications to prevent cloning data, e.g. when reshaping into a
one-dimensional array.
writable
Ensure the resulting array is writable. This will force a copy of the data
if the array was created without copy, as the underlying Arrow data is
immutable.
allow_copy
Allow memory to be copied to perform the conversion. If set to `False`,
causes conversions that are not zero-copy to fail.
structured
Return a `structured array`_ with a data type that corresponds to the
DataFrame schema. If set to `False` (default), a 2D ndarray is
returned instead.
.. _structured array: https://numpy.org/doc/stable/user/basics.rec.html
use_pyarrow
Use `pyarrow.Array.to_numpy
<https://arrow.apache.org/docs/python/generated/pyarrow.Array.html#pyarrow.Array.to_numpy>`_
function for the conversion to NumPy if necessary.
.. deprecated:: 0.20.28
Polars now uses its native engine by default for conversion to NumPy.
Examples
--------
Numeric data without nulls can be converted without copying data in some cases.
The resulting array will not be writable.
>>> df = pl.DataFrame({"a": [1, 2, 3]})
>>> arr = df.to_numpy()
>>> arr
array([[1],
[2],
[3]])
>>> arr.flags.writeable
False
Set `writable=True` to force data copy to make the array writable.
>>> df.to_numpy(writable=True).flags.writeable
True
If the DataFrame contains different numeric data types, the resulting data type
will be the supertype. This requires data to be copied. Integer types with
nulls are cast to a float type with `nan` representing a null value.
>>> df = pl.DataFrame({"a": [1, 2, None], "b": [4.0, 5.0, 6.0]})
>>> df.to_numpy()
array([[ 1., 4.],
[ 2., 5.],
[nan, 6.]])
Set `allow_copy=False` to raise an error if data would be copied.
>>> s.to_numpy(allow_copy=False) # doctest: +SKIP
Traceback (most recent call last):
...
RuntimeError: copy not allowed: cannot convert to a NumPy array without copying data
Polars defaults to F-contiguous order. Use `order="c"` to force the resulting
array to be C-contiguous.
>>> df.to_numpy(order="c").flags.c_contiguous
True
DataFrames with mixed types will result in an array with an object dtype.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.5, 7.0, 8.5],
... "ham": ["a", "b", "c"],
... },
... schema_overrides={"foo": pl.UInt8, "bar": pl.Float32},
... )
>>> df.to_numpy()
array([[1, 6.5, 'a'],
[2, 7.0, 'b'],
[3, 8.5, 'c']], dtype=object)
Set `structured=True` to convert to a structured array, which can better
preserve individual column data such as name and data type.
>>> df.to_numpy(structured=True)
array([(1, 6.5, 'a'), (2, 7. , 'b'), (3, 8.5, 'c')],
dtype=[('foo', 'u1'), ('bar', '<f4'), ('ham', '<U1')])
""" # noqa: W505
if use_pyarrow is not None:
issue_deprecation_warning(
"the `use_pyarrow` parameter for `DataFrame.to_numpy` is deprecated."
" Polars now uses its native engine by default for conversion to NumPy.",
version="0.20.28",
)
if structured:
if not allow_copy and not self.is_empty():
msg = "copy not allowed: cannot create structured array without copying data"
raise RuntimeError(msg)
arrays = []
struct_dtype = []
for s in self.iter_columns():
if s.dtype == Struct:
arr = s.struct.unnest().to_numpy(
structured=True,
allow_copy=True,
use_pyarrow=use_pyarrow,
)
else:
arr = s.to_numpy(use_pyarrow=use_pyarrow)
if s.dtype == String and not s.has_nulls():
arr = arr.astype(str, copy=False)
arrays.append(arr)
struct_dtype.append((s.name, arr.dtype, arr.shape[1:]))
out = np.empty(self.height, dtype=struct_dtype)
for idx, c in enumerate(self.columns):
out[c] = arrays[idx]
return out
return self._df.to_numpy(order, writable=writable, allow_copy=allow_copy)
@overload
def to_jax(
self,
return_type: Literal["array"] = ...,
*,
device: jax.Device | str | None = ...,
label: str | Expr | Sequence[str | Expr] | None = ...,
features: str | Expr | Sequence[str | Expr] | None = ...,
dtype: PolarsDataType | None = ...,
order: IndexOrder = ...,
) -> jax.Array: ...
@overload
def to_jax(
self,
return_type: Literal["dict"],
*,
device: jax.Device | str | None = ...,
label: str | Expr | Sequence[str | Expr] | None = ...,
features: str | Expr | Sequence[str | Expr] | None = ...,
dtype: PolarsDataType | None = ...,
order: IndexOrder = ...,
) -> dict[str, jax.Array]: ...
@unstable()
def to_jax(
self,
return_type: JaxExportType = "array",
*,
device: jax.Device | str | None = None,
label: str | Expr | Sequence[str | Expr] | None = None,
features: str | Expr | Sequence[str | Expr] | None = None,
dtype: PolarsDataType | None = None,
order: IndexOrder = "fortran",
) -> jax.Array | dict[str, jax.Array]:
"""
Convert DataFrame to a Jax Array, or dict of Jax Arrays.
.. versionadded:: 0.20.27
.. warning::
This functionality is currently considered **unstable**. It may be
changed at any point without it being considered a breaking change.
Parameters
----------
return_type : {"array", "dict"}
Set return type; a Jax Array, or dict of Jax Arrays.
device
Specify the jax `Device` on which the array will be created; can provide
a string (such as "cpu", "gpu", or "tpu") in which case the device is
retrieved as `jax.devices(string)[0]`. For more specific control you
can supply the instantiated `Device` directly. If None, arrays are
created on the default device.
label
One or more column names, expressions, or selectors that label the feature
data; results in a `{"label": ..., "features": ...}` dict being returned
when `return_type` is "dict" instead of a `{"col": array, }` dict.
features
One or more column names, expressions, or selectors that contain the feature
data; if omitted, all columns that are not designated as part of the label
are used. Only applies when `return_type` is "dict".
dtype
Unify the dtype of all returned arrays; this casts any column that is
not already of the required dtype before converting to Array. Note that
export will be single-precision (32bit) unless the Jax config/environment
directs otherwise (eg: "jax_enable_x64" was set True in the config object
at startup, or "JAX_ENABLE_X64" is set to "1" in the environment).
order : {"c", "fortran"}
The index order of the returned Jax array, either C-like (row-major) or
Fortran-like (column-major).
See Also
--------
to_dummies
to_numpy
to_torch
Examples
--------
>>> df = pl.DataFrame(
... {
... "lbl": [0, 1, 2, 3],
... "feat1": [1, 0, 0, 1],
... "feat2": [1.5, -0.5, 0.0, -2.25],
... }
... )
Standard return type (2D Array), on the standard device:
>>> df.to_jax()
Array([[ 0. , 1. , 1.5 ],
[ 1. , 0. , -0.5 ],
[ 2. , 0. , 0. ],
[ 3. , 1. , -2.25]], dtype=float32)
Create the Array on the default GPU device:
>>> a = df.to_jax(device="gpu") # doctest: +SKIP
>>> a.device() # doctest: +SKIP
GpuDevice(id=0, process_index=0)
Create the Array on a specific GPU device:
>>> gpu_device = jax.devices("gpu")[1] # doctest: +SKIP
>>> a = df.to_jax(device=gpu_device) # doctest: +SKIP
>>> a.device() # doctest: +SKIP
GpuDevice(id=1, process_index=0)
As a dictionary of individual Arrays:
>>> df.to_jax("dict")
{'lbl': Array([0, 1, 2, 3], dtype=int32),
'feat1': Array([1, 0, 0, 1], dtype=int32),
'feat2': Array([ 1.5 , -0.5 , 0. , -2.25], dtype=float32)}
As a "label" and "features" dictionary; note that as "features" is not
declared, it defaults to all the columns that are not in "label":
>>> df.to_jax("dict", label="lbl")
{'label': Array([[0],
[1],
[2],
[3]], dtype=int32),
'features': Array([[ 1. , 1.5 ],
[ 0. , -0.5 ],
[ 0. , 0. ],
[ 1. , -2.25]], dtype=float32)}
As a "label" and "features" dictionary where each is designated using
a col or selector expression (which can also be used to cast the data
if the label and features are better-represented with different dtypes):
>>> import polars.selectors as cs
>>> df.to_jax(
... return_type="dict",
... features=cs.float(),
... label=pl.col("lbl").cast(pl.UInt8),
... )
{'label': Array([[0],
[1],
[2],
[3]], dtype=uint8),
'features': Array([[ 1.5 ],
[-0.5 ],
[ 0. ],
[-2.25]], dtype=float32)}
"""
if return_type != "dict" and (label is not None or features is not None):
msg = "`label` and `features` only apply when `return_type` is 'dict'"
raise ValueError(msg)
elif return_type == "dict" and label is None and features is not None:
msg = "`label` is required if setting `features` when `return_type='dict'"
raise ValueError(msg)
jx = import_optional(
"jax",
install_message="Please see `https://jax.readthedocs.io/en/latest/installation.html` "
"for specific installation recommendations for the Jax package",
)
enabled_double_precision = jx.config.jax_enable_x64 or bool(
int(os.environ.get("JAX_ENABLE_X64", "0"))
)
if dtype:
frame = self.cast(dtype)
elif not enabled_double_precision:
# enforce single-precision unless environment/config directs otherwise
frame = self.cast({Float64: Float32, Int64: Int32, UInt64: UInt32})
else:
frame = self
if isinstance(device, str):
device = jx.devices(device)[0]
with contextlib.nullcontext() if device is None else jx.default_device(device):
if return_type == "array":
# note: jax arrays are immutable, so can avoid a copy (vs torch)
from polars.ml.utilities import frame_to_numpy
arr = frame_to_numpy(
df=frame,
order=order,
writable=False,
target="Jax Array",
)
return jx.numpy.asarray(a=arr, order="K")
elif return_type == "dict":
if label is not None:
# return a {"label": array(s), "features": array(s)} dict
label_frame = frame.select(label)
features_frame = (
frame.select(features)
if features is not None
else frame.drop(*label_frame.columns)
)
return {
"label": label_frame.to_jax(),
"features": features_frame.to_jax(),
}
else:
# return a {"col": array} dict
return {srs.name: srs.to_jax() for srs in frame}
else:
valid_jax_types = ", ".join(get_args(JaxExportType))
msg = f"invalid `return_type`: {return_type!r}\nExpected one of: {valid_jax_types}"
raise ValueError(msg)
@overload
def to_torch(
self,
return_type: Literal["tensor"] = ...,
*,
label: str | Expr | Sequence[str | Expr] | None = ...,
features: str | Expr | Sequence[str | Expr] | None = ...,
dtype: PolarsDataType | None = ...,
) -> torch.Tensor: ...
@overload
def to_torch(
self,
return_type: Literal["dataset"],
*,
label: str | Expr | Sequence[str | Expr] | None = ...,
features: str | Expr | Sequence[str | Expr] | None = ...,
dtype: PolarsDataType | None = ...,
) -> PolarsDataset: ...
@overload
def to_torch(
self,
return_type: Literal["dict"],
*,
label: str | Expr | Sequence[str | Expr] | None = ...,
features: str | Expr | Sequence[str | Expr] | None = ...,
dtype: PolarsDataType | None = ...,
) -> dict[str, torch.Tensor]: ...
@unstable()
def to_torch(
self,
return_type: TorchExportType = "tensor",
*,
label: str | Expr | Sequence[str | Expr] | None = None,
features: str | Expr | Sequence[str | Expr] | None = None,
dtype: PolarsDataType | None = None,
) -> torch.Tensor | dict[str, torch.Tensor] | PolarsDataset:
"""
Convert DataFrame to a PyTorch Tensor, Dataset, or dict of Tensors.
.. versionadded:: 0.20.23
.. warning::
This functionality is currently considered **unstable**. It may be
changed at any point without it being considered a breaking change.
Parameters
----------
return_type : {"tensor", "dataset", "dict"}
Set return type; a PyTorch Tensor, PolarsDataset (a frame-specialized
TensorDataset), or dict of Tensors.
label
One or more column names, expressions, or selectors that label the feature
data; when `return_type` is "dataset", the PolarsDataset will return
`(features, label)` tensor tuples for each row. Otherwise, it returns
`(features,)` tensor tuples where the feature contains all the row data.
features
One or more column names, expressions, or selectors that contain the feature
data; if omitted, all columns that are not designated as part of the label
are used.
dtype
Unify the dtype of all returned tensors; this casts any column that is
not of the required dtype before converting to Tensor. This includes
the label column *unless* the label is an expression (such as
`pl.col("label_column").cast(pl.Int16)`).
See Also
--------
to_dummies
to_jax
to_numpy
Examples
--------
>>> df = pl.DataFrame(
... {
... "lbl": [0, 1, 2, 3],
... "feat1": [1, 0, 0, 1],
... "feat2": [1.5, -0.5, 0.0, -2.25],
... }
... )
Standard return type (Tensor), with f32 supertype:
>>> df.to_torch(dtype=pl.Float32)
tensor([[ 0.0000, 1.0000, 1.5000],
[ 1.0000, 0.0000, -0.5000],
[ 2.0000, 0.0000, 0.0000],
[ 3.0000, 1.0000, -2.2500]])
As a dictionary of individual Tensors:
>>> df.to_torch("dict")
{'lbl': tensor([0, 1, 2, 3]),
'feat1': tensor([1, 0, 0, 1]),
'feat2': tensor([ 1.5000, -0.5000, 0.0000, -2.2500], dtype=torch.float64)}
As a "label" and "features" dictionary; note that as "features" is not
declared, it defaults to all the columns that are not in "label":
>>> df.to_torch("dict", label="lbl", dtype=pl.Float32)
{'label': tensor([[0.],
[1.],
[2.],
[3.]]),
'features': tensor([[ 1.0000, 1.5000],
[ 0.0000, -0.5000],
[ 0.0000, 0.0000],
[ 1.0000, -2.2500]])}
As a PolarsDataset, with f64 supertype:
>>> ds = df.to_torch("dataset", dtype=pl.Float64)
>>> ds[3]
(tensor([ 3.0000, 1.0000, -2.2500], dtype=torch.float64),)
>>> ds[:2]
(tensor([[ 0.0000, 1.0000, 1.5000],
[ 1.0000, 0.0000, -0.5000]], dtype=torch.float64),)
>>> ds[[0, 3]]
(tensor([[ 0.0000, 1.0000, 1.5000],
[ 3.0000, 1.0000, -2.2500]], dtype=torch.float64),)
As a convenience the PolarsDataset can opt in to half-precision data
for experimentation (usually this would be set on the model/pipeline):
>>> list(ds.half())
[(tensor([0.0000, 1.0000, 1.5000], dtype=torch.float16),),
(tensor([ 1.0000, 0.0000, -0.5000], dtype=torch.float16),),
(tensor([2., 0., 0.], dtype=torch.float16),),
(tensor([ 3.0000, 1.0000, -2.2500], dtype=torch.float16),)]
Pass PolarsDataset to a DataLoader, designating the label:
>>> from torch.utils.data import DataLoader
>>> ds = df.to_torch("dataset", label="lbl")
>>> dl = DataLoader(ds, batch_size=2)
>>> batches = list(dl)
>>> batches[0]
[tensor([[ 1.0000, 1.5000],
[ 0.0000, -0.5000]], dtype=torch.float64), tensor([0, 1])]
Note that labels can be given as expressions, allowing them to have
a dtype independent of the feature columns (multi-column labels are
supported).
>>> ds = df.to_torch(
... return_type="dataset",
... dtype=pl.Float32,
... label=pl.col("lbl").cast(pl.Int16),
... )
>>> ds[:2]
(tensor([[ 1.0000, 1.5000],
[ 0.0000, -0.5000]]), tensor([0, 1], dtype=torch.int16))
Easily integrate with (for example) scikit-learn and other datasets:
>>> from sklearn.datasets import fetch_california_housing # doctest: +SKIP
>>> housing = fetch_california_housing() # doctest: +SKIP
>>> df = pl.DataFrame(
... data=housing.data,
... schema=housing.feature_names,
... ).with_columns(
... Target=housing.target,
... ) # doctest: +SKIP
>>> train = df.to_torch("dataset", label="Target") # doctest: +SKIP
>>> loader = DataLoader(
... train,
... shuffle=True,
... batch_size=64,
... ) # doctest: +SKIP
"""
if return_type not in ("dataset", "dict") and (
label is not None or features is not None
):
msg = "`label` and `features` only apply when `return_type` is 'dataset' or 'dict'"
raise ValueError(msg)
elif return_type == "dict" and label is None and features is not None:
msg = "`label` is required if setting `features` when `return_type='dict'"
raise ValueError(msg)
torch = import_optional("torch")
# Cast columns.
if dtype in (UInt16, UInt32, UInt64):
msg = f"PyTorch does not support u16, u32, or u64 dtypes; given {dtype}"
raise ValueError(msg)
to_dtype = dtype or {UInt16: Int32, UInt32: Int64, UInt64: Int64}
if label is not None:
label_frame = self.select(label)
# Avoid casting the label if it's an expression.
if not isinstance(label, pl.Expr):
label_frame = label_frame.cast(to_dtype) # type: ignore[arg-type]
features_frame = (
self.select(features)
if features is not None
else self.drop(*label_frame.columns)
).cast(to_dtype) # type: ignore[arg-type]
frame = F.concat([label_frame, features_frame], how="horizontal")
else:
frame = (self.select(features) if features is not None else self).cast(
to_dtype # type: ignore[arg-type]
)
if return_type == "tensor":
# note: torch tensors are not immutable, so we must consider them writable
from polars.ml.utilities import frame_to_numpy
arr = frame_to_numpy(frame, writable=True, target="Tensor")
return torch.from_numpy(arr)
elif return_type == "dict":
if label is not None:
# return a {"label": tensor(s), "features": tensor(s)} dict
return {
"label": label_frame.to_torch(),
"features": features_frame.to_torch(),
}
else:
# return a {"col": tensor} dict
return {srs.name: srs.to_torch() for srs in frame}
elif return_type == "dataset":
# return a torch Dataset object
from polars.ml.torch import PolarsDataset
pds_label = None if label is None else label_frame.columns
return PolarsDataset(frame, label=pds_label, features=features)
else:
valid_torch_types = ", ".join(get_args(TorchExportType))
msg = f"invalid `return_type`: {return_type!r}\nExpected one of: {valid_torch_types}"
raise ValueError(msg)
def to_pandas(
self,
*,
use_pyarrow_extension_array: bool = False,
**kwargs: Any,
) -> pd.DataFrame:
"""
Convert this DataFrame to a pandas DataFrame.
This operation copies data if `use_pyarrow_extension_array` is not enabled.
Parameters
----------
use_pyarrow_extension_array
Use PyArrow-backed extension arrays instead of NumPy arrays for the columns
of the pandas DataFrame. This allows zero copy operations and preservation
of null values. Subsequent operations on the resulting pandas DataFrame may
trigger conversion to NumPy if those operations are not supported by PyArrow
compute functions.
**kwargs
Additional keyword arguments to be passed to
:meth:`pyarrow.Table.to_pandas`.
Returns
-------
:class:`pandas.DataFrame`
Notes
-----
This operation requires that both :mod:`pandas` and :mod:`pyarrow` are
installed.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.to_pandas()
foo bar ham
0 1 6.0 a
1 2 7.0 b
2 3 8.0 c
Null values in numeric columns are converted to `NaN`.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, None],
... "bar": [6.0, None, 8.0],
... "ham": [None, "b", "c"],
... }
... )
>>> df.to_pandas()
foo bar ham
0 1.0 6.0 None
1 2.0 NaN b
2 NaN 8.0 c
Pass `use_pyarrow_extension_array=True` to get a pandas DataFrame with columns
backed by PyArrow extension arrays. This will preserve null values.
>>> df.to_pandas(use_pyarrow_extension_array=True)
foo bar ham
0 1 6.0 <NA>
1 2 <NA> b
2 <NA> 8.0 c
>>> _.dtypes
foo int64[pyarrow]
bar double[pyarrow]
ham large_string[pyarrow]
dtype: object
"""
if use_pyarrow_extension_array:
if parse_version(pd.__version__) < (1, 5):
msg = f'pandas>=1.5.0 is required for `to_pandas("use_pyarrow_extension_array=True")`, found Pandas {pd.__version__!r}'
raise ModuleUpgradeRequiredError(msg)
if not _PYARROW_AVAILABLE or parse_version(pa.__version__) < (8, 0):
msg = "pyarrow>=8.0.0 is required for `to_pandas(use_pyarrow_extension_array=True)`"
if _PYARROW_AVAILABLE:
msg += f", found pyarrow {pa.__version__!r}."
raise ModuleUpgradeRequiredError(msg)
else:
raise ModuleNotFoundError(msg)
# handle Object columns separately (Arrow does not convert them correctly)
if Object in self.dtypes:
return self._to_pandas_with_object_columns(
use_pyarrow_extension_array=use_pyarrow_extension_array, **kwargs
)
return self._to_pandas_without_object_columns(
self, use_pyarrow_extension_array=use_pyarrow_extension_array, **kwargs
)
def _to_pandas_with_object_columns(
self,
*,
use_pyarrow_extension_array: bool,
**kwargs: Any,
) -> pd.DataFrame:
# Find which columns are of type pl.Object, and which aren't:
object_columns = []
not_object_columns = []
for i, dtype in enumerate(self.dtypes):
if dtype.is_object():
object_columns.append(i)
else:
not_object_columns.append(i)
# Export columns that aren't pl.Object, in the same order:
if not_object_columns:
df_without_objects = self[:, not_object_columns]
pandas_df = self._to_pandas_without_object_columns(
df_without_objects,
use_pyarrow_extension_array=use_pyarrow_extension_array,
**kwargs,
)
else:
pandas_df = pd.DataFrame()
# Add columns that are pl.Object, using Series' custom to_pandas()
# logic for this case. We do this in order, so the original index for
# the next column in this dataframe is correct for the partially
# constructed Pandas dataframe, since there are no additional or
# missing columns to the inserted column's left.
for i in object_columns:
name = self.columns[i]
pandas_df.insert(i, name, self.to_series(i).to_pandas())
return pandas_df
def _to_pandas_without_object_columns(
self,
df: DataFrame,
*,
use_pyarrow_extension_array: bool,
**kwargs: Any,
) -> pd.DataFrame:
if not df.width: # Empty dataframe, cannot infer schema from batches
return pd.DataFrame()
record_batches = df._df.to_pandas()
tbl = pa.Table.from_batches(record_batches)
if use_pyarrow_extension_array:
return tbl.to_pandas(
self_destruct=True,
split_blocks=True,
types_mapper=lambda pa_dtype: pd.ArrowDtype(pa_dtype),
**kwargs,
)
date_as_object = kwargs.pop("date_as_object", False)
return tbl.to_pandas(date_as_object=date_as_object, **kwargs)
def to_series(self, index: int = 0) -> Series:
"""
Select column as Series at index location.
Parameters
----------
index
Location of selection.
See Also
--------
get_column
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.to_series(1)
shape: (3,)
Series: 'bar' [i64]
[
6
7
8
]
"""
return wrap_s(self._df.to_series(index))
def to_init_repr(self, n: int = 1000) -> str:
"""
Convert DataFrame to instantiable string representation.
Parameters
----------
n
Only use first n rows.
See Also
--------
polars.Series.to_init_repr
polars.from_repr
Examples
--------
>>> df = pl.DataFrame(
... [
... pl.Series("foo", [1, 2, 3], dtype=pl.UInt8),
... pl.Series("bar", [6.0, 7.0, 8.0], dtype=pl.Float32),
... pl.Series("ham", ["a", "b", "c"], dtype=pl.String),
... ]
... )
>>> print(df.to_init_repr())
pl.DataFrame(
[
pl.Series('foo', [1, 2, 3], dtype=pl.UInt8),
pl.Series('bar', [6.0, 7.0, 8.0], dtype=pl.Float32),
pl.Series('ham', ['a', 'b', 'c'], dtype=pl.String),
]
)
>>> df_from_str_repr = eval(df.to_init_repr())
>>> df_from_str_repr
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ u8 ┆ f32 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6.0 ┆ a │
│ 2 ┆ 7.0 ┆ b │
│ 3 ┆ 8.0 ┆ c │
└─────┴─────┴─────┘
"""
output = StringIO()
output.write("pl.DataFrame(\n [\n")
for i in range(self.width):
output.write(" ")
output.write(self.to_series(i).to_init_repr(n))
output.write(",\n")
output.write(" ]\n)\n")
return output.getvalue()
@overload
def serialize(
self, file: None = ..., *, format: Literal["binary"] = ...
) -> bytes: ...
@overload
def serialize(self, file: None = ..., *, format: Literal["json"]) -> str: ...
@overload
def serialize(
self, file: IOBase | str | Path, *, format: SerializationFormat = ...
) -> None: ...
def serialize(
self,
file: IOBase | str | Path | None = None,
*,
format: SerializationFormat = "binary",
) -> bytes | str | None:
r"""
Serialize this DataFrame to a file or string in JSON format.
Parameters
----------
file
File path or writable file-like object to which the result will be written.
If set to `None` (default), the output is returned as a string instead.
format
The format in which to serialize. Options:
- `"binary"`: Serialize to binary format (bytes). This is the default.
- `"json"`: Serialize to JSON format (string).
Notes
-----
Serialization is not stable across Polars versions: a LazyFrame serialized
in one Polars version may not be deserializable in another Polars version.
Examples
--------
Serialize the DataFrame into a binary representation.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... }
... )
>>> bytes = df.serialize()
>>> type(bytes)
<class 'bytes'>
The bytes can later be deserialized back into a DataFrame.
>>> import io
>>> pl.DataFrame.deserialize(io.BytesIO(bytes))
shape: (3, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 6 │
│ 2 ┆ 7 │
│ 3 ┆ 8 │
└─────┴─────┘
"""
if format == "binary":
serializer = self._df.serialize_binary
elif format == "json":
serializer = self._df.serialize_json
else:
msg = f"`format` must be one of {{'binary', 'json'}}, got {format!r}"
raise ValueError(msg)
return serialize_polars_object(serializer, file, format)
@overload
def write_json(self, file: None = ...) -> str: ...
@overload
def write_json(self, file: IOBase | str | Path) -> None: ...
def write_json(self, file: IOBase | str | Path | None = None) -> str | None:
"""
Serialize to JSON representation.
Parameters
----------
file
File path or writable file-like object to which the result will be written.
If set to `None` (default), the output is returned as a string instead.
See Also
--------
DataFrame.write_ndjson
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... }
... )
>>> df.write_json()
'[{"foo":1,"bar":6},{"foo":2,"bar":7},{"foo":3,"bar":8}]'
"""
def write_json_to_string() -> str:
with BytesIO() as buf:
self._df.write_json(buf)
json_bytes = buf.getvalue()
return json_bytes.decode("utf8")
if file is None:
return write_json_to_string()
elif isinstance(file, StringIO):
json_str = write_json_to_string()
file.write(json_str)
return None
elif isinstance(file, (str, Path)):
file = normalize_filepath(file)
self._df.write_json(file)
return None
else:
self._df.write_json(file)
return None
@overload
def write_ndjson(self, file: None = None) -> str: ...
@overload
def write_ndjson(self, file: str | Path | IO[bytes] | IO[str]) -> None: ...
def write_ndjson(
self, file: str | Path | IO[bytes] | IO[str] | None = None
) -> str | None:
r"""
Serialize to newline delimited JSON representation.
Parameters
----------
file
File path or writable file-like object to which the result will be written.
If set to `None` (default), the output is returned as a string instead.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... }
... )
>>> df.write_ndjson()
'{"foo":1,"bar":6}\n{"foo":2,"bar":7}\n{"foo":3,"bar":8}\n'
"""
should_return_buffer = False
target: str | Path | IO[bytes] | IO[str]
if file is None:
target = cast("IO[bytes]", BytesIO())
should_return_buffer = True
elif isinstance(file, (str, os.PathLike)):
target = normalize_filepath(file)
else:
target = file
engine: EngineType = "in-memory"
from polars.lazyframe.opt_flags import QueryOptFlags
self.lazy().sink_ndjson(
target,
optimizations=QueryOptFlags._eager(),
engine=engine,
)
if should_return_buffer:
return str(target.getvalue(), encoding="utf-8") # type: ignore[union-attr]
return None
@overload
def write_csv(
self,
file: None = None,
*,
include_bom: bool = ...,
include_header: bool = ...,
separator: str = ...,
line_terminator: str = ...,
quote_char: str = ...,
batch_size: int = ...,
datetime_format: str | None = ...,
date_format: str | None = ...,
time_format: str | None = ...,
float_scientific: bool | None = ...,
float_precision: int | None = ...,
decimal_comma: bool = ...,
null_value: str | None = ...,
quote_style: CsvQuoteStyle | None = ...,
storage_options: dict[str, Any] | None = ...,
credential_provider: CredentialProviderFunction | Literal["auto"] | None = ...,
retries: int = ...,
) -> str: ...
@overload
def write_csv(
self,
file: str | Path | IO[str] | IO[bytes],
*,
include_bom: bool = ...,
include_header: bool = ...,
separator: str = ...,
line_terminator: str = ...,
quote_char: str = ...,
batch_size: int = ...,
datetime_format: str | None = ...,
date_format: str | None = ...,
time_format: str | None = ...,
float_scientific: bool | None = ...,
float_precision: int | None = ...,
decimal_comma: bool = ...,
null_value: str | None = ...,
quote_style: CsvQuoteStyle | None = ...,
storage_options: dict[str, Any] | None = ...,
credential_provider: CredentialProviderFunction | Literal["auto"] | None = ...,
retries: int = ...,
) -> None: ...
def write_csv(
self,
file: str | Path | IO[str] | IO[bytes] | None = None,
*,
include_bom: bool = False,
include_header: bool = True,
separator: str = ",",
line_terminator: str = "\n",
quote_char: str = '"',
batch_size: int = 1024,
datetime_format: str | None = None,
date_format: str | None = None,
time_format: str | None = None,
float_scientific: bool | None = None,
float_precision: int | None = None,
decimal_comma: bool = False,
null_value: str | None = None,
quote_style: CsvQuoteStyle | None = None,
storage_options: dict[str, Any] | None = None,
credential_provider: (
CredentialProviderFunction | Literal["auto"] | None
) = "auto",
retries: int = 2,
) -> str | None:
"""
Write to comma-separated values (CSV) file.
Parameters
----------
file
File path or writable file-like object to which the result will be written.
If set to `None` (default), the output is returned as a string instead.
include_bom
Whether to include UTF-8 BOM in the CSV output.
include_header
Whether to include header in the CSV output.
separator
Separate CSV fields with this symbol.
line_terminator
String used to end each row.
quote_char
Byte to use as quoting character.
batch_size
Number of rows that will be processed per thread.
datetime_format
A format string, with the specifiers defined by the
`chrono <https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
Rust crate. If no format specified, the default fractional-second
precision is inferred from the maximum timeunit found in the frame's
Datetime cols (if any).
date_format
A format string, with the specifiers defined by the
`chrono <https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
Rust crate.
time_format
A format string, with the specifiers defined by the
`chrono <https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
Rust crate.
float_scientific
Whether to use scientific form always (true), never (false), or
automatically (None) for floating-point datatypes.
float_precision
Number of decimal places to write, applied to both floating-point
data types.
decimal_comma
Use a comma as the decimal separator instead of a point in standard
notation. Floats will be encapsulated in quotes if necessary; set the
field separator to override.
null_value
A string representing null values (defaulting to the empty string).
quote_style : {'necessary', 'always', 'non_numeric', 'never'}
Determines the quoting strategy used.
- necessary (default): This puts quotes around fields only when necessary.
They are necessary when fields contain a quote,
separator or record terminator.
Quotes are also necessary when writing an empty record
(which is indistinguishable from a record with one empty field).
This is the default.
- always: This puts quotes around every field. Always.
- never: This never puts quotes around fields, even if that results in
invalid CSV data (e.g.: by not quoting strings containing the separator).
- non_numeric: This puts quotes around all fields that are non-numeric.
Namely, when writing a field that does not parse as a valid float
or integer, then quotes will be used even if they aren`t strictly
necessary.
storage_options
Options that indicate how to connect to a cloud provider.
The cloud providers currently supported are AWS, GCP, and Azure.
See supported keys here:
* `aws <https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html>`_
* `gcp <https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html>`_
* `azure <https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html>`_
* Hugging Face (`hf://`): Accepts an API key under the `token` parameter: \
`{'token': '...'}`, or by setting the `HF_TOKEN` environment variable.
If `storage_options` is not provided, Polars will try to infer the
information from environment variables.
credential_provider
Provide a function that can be called to provide cloud storage
credentials. The function is expected to return a dictionary of
credential keys along with an optional credential expiry time.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
retries
Number of retries if accessing a cloud instance fails.
Examples
--------
>>> import pathlib
>>>
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> path: pathlib.Path = dirpath / "new_file.csv"
>>> df.write_csv(path, separator=",")
"""
from polars.io.csv._utils import _check_arg_is_1byte
_check_arg_is_1byte("separator", separator, can_be_empty=False)
_check_arg_is_1byte("quote_char", quote_char, can_be_empty=True)
if not null_value:
null_value = None
should_return_buffer = False
target: str | Path | IO[bytes] | IO[str]
if file is None:
target = cast("IO[bytes]", BytesIO())
should_return_buffer = True
elif isinstance(file, (str, os.PathLike)):
target = normalize_filepath(file)
else:
target = file
engine: EngineType = "in-memory"
from polars.lazyframe.opt_flags import QueryOptFlags
self.lazy().sink_csv(
target,
include_bom=include_bom,
include_header=include_header,
separator=separator,
line_terminator=line_terminator,
quote_char=quote_char,
batch_size=batch_size,
datetime_format=datetime_format,
date_format=date_format,
time_format=time_format,
float_scientific=float_scientific,
float_precision=float_precision,
decimal_comma=decimal_comma,
null_value=null_value,
quote_style=quote_style,
storage_options=storage_options,
credential_provider=credential_provider,
retries=retries,
optimizations=QueryOptFlags._eager(),
engine=engine,
)
if should_return_buffer:
return str(target.getvalue(), encoding="utf-8") # type: ignore[union-attr]
return None
def write_clipboard(self, *, separator: str = "\t", **kwargs: Any) -> None:
"""
Copy `DataFrame` in csv format to the system clipboard with `write_csv`.
Useful for pasting into Excel or other similar spreadsheet software.
Parameters
----------
separator
Separate CSV fields with this symbol.
kwargs
Additional arguments to pass to `write_csv`.
See Also
--------
polars.read_clipboard: Read a DataFrame from the clipboard.
write_csv: Write to comma-separated values (CSV) file.
"""
result: str = self.write_csv(file=None, separator=separator, **kwargs)
_write_clipboard_string(result)
def write_avro(
self,
file: str | Path | IO[bytes],
compression: AvroCompression = "uncompressed",
name: str = "",
) -> None:
"""
Write to Apache Avro file.
Parameters
----------
file
File path or writable file-like object to which the data will be written.
compression : {'uncompressed', 'snappy', 'deflate'}
Compression method. Defaults to "uncompressed".
name
Schema name. Defaults to empty string.
Examples
--------
>>> import pathlib
>>>
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> path: pathlib.Path = dirpath / "new_file.avro"
>>> df.write_avro(path)
"""
if compression is None:
compression = "uncompressed"
if isinstance(file, (str, Path)):
file = normalize_filepath(file)
if name is None:
name = ""
self._df.write_avro(file, compression, name)
def write_excel(
self,
workbook: str | Workbook | IO[bytes] | Path | None = None,
worksheet: str | Worksheet | None = None,
*,
position: tuple[int, int] | str = "A1",
table_style: str | dict[str, Any] | None = None,
table_name: str | None = None,
column_formats: ColumnFormatDict | None = None,
dtype_formats: dict[OneOrMoreDataTypes, str] | None = None,
conditional_formats: ConditionalFormatDict | None = None,
header_format: dict[str, Any] | None = None,
column_totals: ColumnTotalsDefinition | None = None,
column_widths: ColumnWidthsDefinition | None = None,
row_totals: RowTotalsDefinition | None = None,
row_heights: dict[int | tuple[int, ...], int] | int | None = None,
sparklines: dict[str, Sequence[str] | dict[str, Any]] | None = None,
formulas: dict[str, str | dict[str, str]] | None = None,
float_precision: int = 3,
include_header: bool = True,
autofilter: bool = True,
autofit: bool = False,
hidden_columns: Sequence[str] | SelectorType | None = None,
hide_gridlines: bool = False,
sheet_zoom: int | None = None,
freeze_panes: (
str
| tuple[int, int]
| tuple[str, int, int]
| tuple[int, int, int, int]
| None
) = None,
) -> Workbook:
"""
Write frame data to a table in an Excel workbook/worksheet.
Parameters
----------
workbook : {str, Workbook}
String name or path of the workbook to create, BytesIO object, file opened
in binary-mode, or an `xlsxwriter.Workbook` object that has not been closed.
If None, writes to `dataframe.xlsx` in the working directory.
worksheet : {str, Worksheet}
Name of target worksheet or an `xlsxwriter.Worksheet` object (in which
case `workbook` must be the parent `xlsxwriter.Workbook` object); if None,
writes to "Sheet1" when creating a new workbook (note that writing to an
existing workbook requires a valid existing -or new- worksheet name).
position : {str, tuple}
Table position in Excel notation (eg: "A1"), or a (row,col) integer tuple.
table_style : {str, dict}
A named Excel table style, such as "Table Style Medium 4", or a dictionary
of `{"key":value,}` options containing one or more of the following keys:
"style", "first_column", "last_column", "banded_columns, "banded_rows".
table_name : str
Name of the output table object in the worksheet; can then be referred to
in the sheet by formulae/charts, or by subsequent `xlsxwriter` operations.
column_formats : dict
A `{colname(s):str,}` or `{selector:str,}` dictionary for applying an
Excel format string to the given columns. Formats defined here (such as
"dd/mm/yyyy", "0.00%", etc) will override any defined in `dtype_formats`.
dtype_formats : dict
A `{dtype:str,}` dictionary that sets the default Excel format for the
given dtype. (This can be overridden on a per-column basis by the
`column_formats` param).
conditional_formats : dict
A dictionary of colname (or selector) keys to a format str, dict, or list
that defines conditional formatting options for the specified columns.
* If supplying a string typename, should be one of the valid `xlsxwriter`
types such as "3_color_scale", "data_bar", etc.
* If supplying a dictionary you can make use of any/all `xlsxwriter`
supported options, including icon sets, formulae, etc.
* Supplying multiple columns as a tuple/key will apply a single format
across all columns - this is effective in creating a heatmap, as the
min/max values will be determined across the entire range, not per-column.
* Finally, you can also supply a list made up from the above options
in order to apply *more* than one conditional format to the same range.
header_format : dict
A `{key:value,}` dictionary of `xlsxwriter` format options to apply
to the table header row, such as `{"bold":True, "font_color":"#702963"}`.
column_totals : {bool, list, dict}
Add a column-total row to the exported table.
* If True, all numeric columns will have an associated total using "sum".
* If passing a string, it must be one of the valid total function names
and all numeric columns will have an associated total using that function.
* If passing a list of colnames, only those given will have a total.
* For more control, pass a `{colname:funcname,}` dict.
Valid column-total function names are "average", "count_nums", "count",
"max", "min", "std_dev", "sum", and "var".
column_widths : {dict, int}
A `{colname:int,}` or `{selector:int,}` dict or a single integer that
sets (or overrides if autofitting) table column widths, in integer pixel
units. If given as an integer the same value is used for all table columns.
row_totals : {dict, list, bool}
Add a row-total column to the right-hand side of the exported table.
* If True, a column called "total" will be added at the end of the table
that applies a "sum" function row-wise across all numeric columns.
* If passing a list/sequence of column names, only the matching columns
will participate in the sum.
* Can also pass a `{colname:columns,}` dictionary to create one or
more total columns with distinct names, referencing different columns.
row_heights : {dict, int}
An int or `{row_index:int,}` dictionary that sets the height of the given
rows (if providing a dictionary) or all rows (if providing an integer) that
intersect with the table body (including any header and total row) in
integer pixel units. Note that `row_index` starts at zero and will be
the header row (unless `include_header` is False).
sparklines : dict
A `{colname:list,}` or `{colname:dict,}` dictionary defining one or more
sparklines to be written into a new column in the table.
* If passing a list of colnames (used as the source of the sparkline data)
the default sparkline settings are used (eg: line chart with no markers).
* For more control an `xlsxwriter`-compliant options dict can be supplied,
in which case three additional polars-specific keys are available:
"columns", "insert_before", and "insert_after". These allow you to define
the source columns and position the sparkline(s) with respect to other
table columns. If no position directive is given, sparklines are added to
the end of the table (eg: to the far right) in the order they are given.
formulas : dict
A `{colname:formula,}` or `{colname:dict,}` dictionary defining one or
more formulas to be written into a new column in the table. Note that you
are strongly advised to use structured references in your formulae wherever
possible to make it simple to reference columns by name.
* If providing a string formula (such as "=[@colx]*[@coly]") the column will
be added to the end of the table (eg: to the far right), after any default
sparklines and before any row_totals.
* For the most control supply an options dictionary with the following keys:
"formula" (mandatory), one of "insert_before" or "insert_after", and
optionally "return_dtype". The latter is used to appropriately format the
output of the formula and allow it to participate in row/column totals.
float_precision : int
Default number of decimals displayed for floating point columns (note that
this is purely a formatting directive; the actual values are not rounded).
include_header : bool
Indicate if the table should be created with a header row.
autofilter : bool
If the table has headers, provide autofilter capability.
autofit : bool
Calculate individual column widths from the data.
hidden_columns : str | list
A column name, list of column names, or a selector representing table
columns to mark as hidden in the output worksheet.
hide_gridlines : bool
Do not display any gridlines on the output worksheet.
sheet_zoom : int
Set the default zoom level of the output worksheet.
freeze_panes : str | (str, int, int) | (int, int) | (int, int, int, int)
Freeze workbook panes.
* If (row, col) is supplied, panes are split at the top-left corner of the
specified cell, which are 0-indexed. Thus, to freeze only the top row,
supply (1, 0).
* Alternatively, cell notation can be used to supply the cell. For example,
"A2" indicates the split occurs at the top-left of cell A2, which is the
equivalent of (1, 0).
* If (row, col, top_row, top_col) are supplied, the panes are split based on
the `row` and `col`, and the scrolling region is initialized to begin at
the `top_row` and `top_col`. Thus, to freeze only the top row and have the
scrolling region begin at row 10, column D (5th col), supply (1, 0, 9, 4).
Using cell notation for (row, col), supplying ("A2", 9, 4) is equivalent.
Notes
-----
* A list of compatible `xlsxwriter` format property names can be found here:
https://xlsxwriter.readthedocs.io/format.html#format-methods-and-format-properties
* Conditional formatting dictionaries should provide xlsxwriter-compatible
definitions; polars will take care of how they are applied on the worksheet
with respect to the relative sheet/column position. For supported options,
see: https://xlsxwriter.readthedocs.io/working_with_conditional_formats.html
* Similarly, sparkline option dictionaries should contain xlsxwriter-compatible
key/values, as well as a mandatory polars "columns" key that defines the
sparkline source data; these source columns should all be adjacent. Two other
polars-specific keys are available to help define where the sparkline appears
in the table: "insert_after", and "insert_before". The value associated with
these keys should be the name of a column in the exported table.
https://xlsxwriter.readthedocs.io/working_with_sparklines.html
* Formula dictionaries *must* contain a key called "formula", and then optional
"insert_after", "insert_before", and/or "return_dtype" keys. These additional
keys allow the column to be injected into the table at a specific location,
and/or to define the return type of the formula (eg: "Int64", "Float64", etc).
Formulas that refer to table columns should use Excel's structured references
syntax to ensure the formula is applied correctly and is table-relative.
https://support.microsoft.com/en-us/office/using-structured-references-with-excel-tables-f5ed2452-2337-4f71-bed3-c8ae6d2b276e
* If you want unformatted output, you can use a selector to apply the "General"
format to all columns (or all *non-temporal* columns to preserve formatting
of date/datetime columns), eg: `column_formats={~cs.temporal(): "General"}`.
Examples
--------
Instantiate a basic DataFrame:
>>> from random import uniform
>>> from datetime import date
>>>
>>> df = pl.DataFrame(
... {
... "dtm": [date(2023, 1, 1), date(2023, 1, 2), date(2023, 1, 3)],
... "num": [uniform(-500, 500), uniform(-500, 500), uniform(-500, 500)],
... "val": [10_000, 20_000, 30_000],
... }
... )
Export to "dataframe.xlsx" (the default workbook name, if not specified) in the
working directory, add column totals on all numeric columns ("sum" by default),
then autofit:
>>> df.write_excel(column_totals=True, autofit=True) # doctest: +SKIP
Write frame to a specific location on the sheet, set a named table style,
apply US-style date formatting, increase floating point formatting precision,
apply a non-default column total function to a specific column, autofit:
>>> df.write_excel( # doctest: +SKIP
... position="B4",
... table_style="Table Style Light 16",
... dtype_formats={pl.Date: "mm/dd/yyyy"},
... column_totals={"num": "average"},
... float_precision=6,
... autofit=True,
... )
Write the same frame to a named worksheet twice, applying different styles
and conditional formatting to each table, adding custom-formatted table
titles using explicit `xlsxwriter` integration:
>>> from xlsxwriter import Workbook
>>> with Workbook("multi_frame.xlsx") as wb: # doctest: +SKIP
... # basic/default conditional formatting
... df.write_excel(
... workbook=wb,
... worksheet="data",
... position=(3, 1), # specify position as (row,col) coordinates
... conditional_formats={"num": "3_color_scale", "val": "data_bar"},
... table_style="Table Style Medium 4",
... )
...
... # advanced conditional formatting, custom styles
... df.write_excel(
... workbook=wb,
... worksheet="data",
... position=(df.height + 7, 1),
... table_style={
... "style": "Table Style Light 4",
... "first_column": True,
... },
... conditional_formats={
... "num": {
... "type": "3_color_scale",
... "min_color": "#76933c",
... "mid_color": "#c4d79b",
... "max_color": "#ebf1de",
... },
... "val": {
... "type": "data_bar",
... "data_bar_2010": True,
... "bar_color": "#9bbb59",
... "bar_negative_color_same": True,
... "bar_negative_border_color_same": True,
... },
... },
... column_formats={"num": "#,##0.000;[White]-#,##0.000"},
... column_widths={"val": 125},
... autofit=True,
... )
...
... # add some table titles (with a custom format)
... ws = wb.get_worksheet_by_name("data")
... fmt_title = wb.add_format(
... {
... "font_color": "#4f6228",
... "font_size": 12,
... "italic": True,
... "bold": True,
... }
... )
... ws.write(2, 1, "Basic/default conditional formatting", fmt_title)
... ws.write(df.height + 6, 1, "Custom conditional formatting", fmt_title)
Export a table containing two different types of sparklines. Use default
options for the "trend" sparkline and customized options (and positioning)
for the "+/-" `win_loss` sparkline, with non-default integer formatting,
column totals, a subtle two-tone heatmap and hidden worksheet gridlines:
>>> df = pl.DataFrame(
... {
... "id": ["aaa", "bbb", "ccc", "ddd", "eee"],
... "q1": [100, 55, -20, 0, 35],
... "q2": [30, -10, 15, 60, 20],
... "q3": [-50, 0, 40, 80, 80],
... "q4": [75, 55, 25, -10, -55],
... }
... )
>>> df.write_excel( # doctest: +SKIP
... table_style="Table Style Light 2",
... # apply accounting format to all flavours of integer
... dtype_formats={dt: "#,##0_);(#,##0)" for dt in [pl.Int32, pl.Int64]},
... sparklines={
... # default options; just provide source cols
... "trend": ["q1", "q2", "q3", "q4"],
... # customized sparkline type, with positioning directive
... "+/-": {
... "columns": ["q1", "q2", "q3", "q4"],
... "insert_after": "id",
... "type": "win_loss",
... },
... },
... conditional_formats={
... # create a unified multi-column heatmap
... ("q1", "q2", "q3", "q4"): {
... "type": "2_color_scale",
... "min_color": "#95b3d7",
... "max_color": "#ffffff",
... },
... },
... column_totals=["q1", "q2", "q3", "q4"],
... row_totals=True,
... hide_gridlines=True,
... )
Export a table containing an Excel formula-based column that calculates a
standardised Z-score, showing use of structured references in conjunction
with positioning directives, column totals, and custom formatting.
>>> df = pl.DataFrame(
... {
... "id": ["a123", "b345", "c567", "d789", "e101"],
... "points": [99, 45, 50, 85, 35],
... }
... )
>>> df.write_excel( # doctest: +SKIP
... table_style={
... "style": "Table Style Medium 15",
... "first_column": True,
... },
... column_formats={
... "id": {"font": "Consolas"},
... "points": {"align": "center"},
... "z-score": {"align": "center"},
... },
... column_totals="average",
... formulas={
... "z-score": {
... # use structured references to refer to the table columns and 'totals' row
... "formula": "=STANDARDIZE([@points], [[#Totals],[points]], STDEV([points]))",
... "insert_after": "points",
... "return_dtype": pl.Float64,
... }
... },
... hide_gridlines=True,
... sheet_zoom=125,
... )
Create and reference a Worksheet object directly, adding a basic chart.
Taking advantage of structured references to set chart series values and
categories is *strongly* recommended so you do not have to calculate
cell positions with respect to the frame data and worksheet:
>>> with Workbook("basic_chart.xlsx") as wb: # doctest: +SKIP
... # create worksheet object and write frame data to it
... ws = wb.add_worksheet("demo")
... df.write_excel(
... workbook=wb,
... worksheet=ws,
... table_name="DataTable",
... table_style="Table Style Medium 26",
... hide_gridlines=True,
... )
... # create chart object, point to the written table
... # data using structured references, and style it
... chart = wb.add_chart({"type": "column"})
... chart.set_title({"name": "Example Chart"})
... chart.set_legend({"none": True})
... chart.set_style(38)
... chart.add_series(
... { # note the use of structured references
... "values": "=DataTable[points]",
... "categories": "=DataTable[id]",
... "data_labels": {"value": True},
... }
... )
... # add chart to the worksheet
... ws.insert_chart("D1", chart)
Export almost entirely unformatted data (no numeric styling or standardised
floating point precision), omit autofilter, but keep date/datetime formatting:
>>> import polars.selectors as cs
>>> df = pl.DataFrame(
... {
... "n1": [-100, None, 200, 555],
... "n2": [987.4321, -200, 44.444, 555.5],
... }
... )
>>> df.write_excel( # doctest: +SKIP
... column_formats={~cs.temporal(): "General"},
... autofilter=False,
... )
""" # noqa: W505
from polars.io.spreadsheet._write_utils import (
_unpack_multi_column_dict,
_xl_apply_conditional_formats,
_xl_inject_sparklines,
_xl_setup_table_columns,
_xl_setup_table_options,
_xl_setup_workbook,
_xl_unique_table_name,
_XLFormatCache,
)
xlsxwriter = import_optional("xlsxwriter", err_prefix="Excel export requires")
from xlsxwriter.utility import xl_cell_to_rowcol
# setup workbook/worksheet
wb, ws, can_close = _xl_setup_workbook(workbook, worksheet)
df, is_empty = self, self.is_empty()
# note: `_xl_setup_table_columns` converts nested data (List, Struct, etc.) to
# string, so we keep a reference to the original so that column selection with
# selectors that target such types remains correct
df_original = df
# setup table format/columns
fmt_cache = _XLFormatCache(wb)
column_formats = column_formats or {}
table_style, table_options = _xl_setup_table_options(table_style)
table_name = table_name or _xl_unique_table_name(wb)
table_columns, column_formats, df = _xl_setup_table_columns( # type: ignore[assignment]
df=df,
format_cache=fmt_cache,
column_formats=column_formats,
column_totals=column_totals,
dtype_formats=dtype_formats,
header_format=header_format,
float_precision=float_precision,
table_style=table_style,
row_totals=row_totals,
sparklines=sparklines,
formulas=formulas,
)
# normalise cell refs (eg: "B3" => (2,1)) and establish table start/finish,
# accounting for potential presence/absence of headers and a totals row.
table_start = (
xl_cell_to_rowcol(position) if isinstance(position, str) else position
)
table_finish = (
table_start[0]
+ df.height
+ int(is_empty)
- int(not include_header)
+ int(bool(column_totals)),
table_start[1] + df.width - 1,
)
excel_max_valid_rows = 1048575
excel_max_valid_cols = 16384
if (
table_finish[0] > excel_max_valid_rows
or table_finish[1] > excel_max_valid_cols
):
msg = f"writing {df.height}x{df.width} frame at {position!r} does not fit worksheet dimensions of {excel_max_valid_rows} rows and {excel_max_valid_cols} columns"
raise InvalidOperationError(msg)
# write table structure and formats into the target sheet
if not is_empty or include_header:
ws.add_table(
*table_start,
*table_finish,
{
"data": df.rows(),
"style": table_style,
"columns": table_columns,
"header_row": include_header,
"autofilter": autofilter,
"total_row": bool(column_totals) and not is_empty,
"name": table_name,
**table_options,
},
)
# apply conditional formats
if conditional_formats:
_xl_apply_conditional_formats(
df=df,
ws=ws,
conditional_formats=conditional_formats,
table_start=table_start,
include_header=include_header,
format_cache=fmt_cache,
)
# additional column-level properties
if hidden_columns is None:
hidden = set()
elif isinstance(hidden_columns, str):
hidden = {hidden_columns}
else:
hidden = set(_expand_selectors(df_original, hidden_columns))
# Autofit section needs to be present above column_widths section
# to ensure that parameters provided in the column_widths section
# are not overwritten by autofit
#
# table/rows all written; apply (optional) autofit
if autofit and not is_empty:
xlv = xlsxwriter.__version__
if parse_version(xlv) < (3, 0, 8):
msg = f"`autofit=True` requires xlsxwriter 3.0.8 or higher, found {xlv}"
raise ModuleUpgradeRequiredError(msg)
ws.autofit()
if isinstance(column_widths, int):
column_widths = dict.fromkeys(df.columns, column_widths)
else:
column_widths = _expand_selector_dicts( # type: ignore[assignment]
df_original, column_widths, expand_keys=True, expand_values=False
)
column_widths = _unpack_multi_column_dict(column_widths or {}) # type: ignore[assignment]
for column in df.columns:
options = {"hidden": True} if column in hidden else {}
col_idx = table_start[1] + df.get_column_index(column)
if column in column_widths: # type: ignore[operator]
ws.set_column_pixels(
col_idx,
col_idx,
column_widths[column], # type: ignore[index]
None,
options,
)
elif options:
ws.set_column(col_idx, col_idx, None, None, options)
# finally, inject any sparklines into the table
for column, params in (sparklines or {}).items():
_xl_inject_sparklines(
ws,
df,
table_start,
column,
include_header=include_header,
params=params,
)
# worksheet options
if hide_gridlines:
ws.hide_gridlines(2)
if sheet_zoom:
ws.set_zoom(sheet_zoom)
if row_heights:
if isinstance(row_heights, int):
for idx in range(table_start[0], table_finish[0] + 1):
ws.set_row_pixels(idx, row_heights)
elif isinstance(row_heights, dict):
for idx, height in _unpack_multi_column_dict(row_heights).items(): # type: ignore[assignment]
ws.set_row_pixels(idx, height)
if freeze_panes:
if isinstance(freeze_panes, str):
ws.freeze_panes(freeze_panes)
else:
ws.freeze_panes(*freeze_panes)
if can_close:
wb.close()
return wb
@overload
def write_ipc(
self,
file: None,
*,
compression: IpcCompression = "uncompressed",
compat_level: CompatLevel | None = None,
storage_options: dict[str, Any] | None = None,
credential_provider: (
CredentialProviderFunction | Literal["auto"] | None
) = "auto",
retries: int = 2,
) -> BytesIO: ...
@overload
def write_ipc(
self,
file: str | Path | IO[bytes],
*,
compression: IpcCompression = "uncompressed",
compat_level: CompatLevel | None = None,
storage_options: dict[str, Any] | None = None,
credential_provider: (
CredentialProviderFunction | Literal["auto"] | None
) = "auto",
retries: int = 2,
) -> None: ...
@deprecate_renamed_parameter("future", "compat_level", version="1.1")
def write_ipc(
self,
file: str | Path | IO[bytes] | None,
*,
compression: IpcCompression = "uncompressed",
compat_level: CompatLevel | None = None,
storage_options: dict[str, Any] | None = None,
credential_provider: (
CredentialProviderFunction | Literal["auto"] | None
) = "auto",
retries: int = 2,
) -> BytesIO | None:
"""
Write to Arrow IPC binary stream or Feather file.
See "File or Random Access format" in https://arrow.apache.org/docs/python/ipc.html.
.. versionchanged:: 1.1
The `future` parameter was renamed `compat_level`.
Parameters
----------
file
Path or writable file-like object to which the IPC data will be
written. If set to `None`, the output is returned as a BytesIO object.
compression : {'uncompressed', 'lz4', 'zstd'}
Compression method. Defaults to "uncompressed".
compat_level
Use a specific compatibility level
when exporting Polars' internal data structures.
storage_options
Options that indicate how to connect to a cloud provider.
The cloud providers currently supported are AWS, GCP, and Azure.
See supported keys here:
* `aws <https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html>`_
* `gcp <https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html>`_
* `azure <https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html>`_
* Hugging Face (`hf://`): Accepts an API key under the `token` parameter: \
`{'token': '...'}`, or by setting the `HF_TOKEN` environment variable.
If `storage_options` is not provided, Polars will try to infer the
information from environment variables.
credential_provider
Provide a function that can be called to provide cloud storage
credentials. The function is expected to return a dictionary of
credential keys along with an optional credential expiry time.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
retries
Number of retries if accessing a cloud instance fails.
Examples
--------
>>> import pathlib
>>>
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> path: pathlib.Path = dirpath / "new_file.arrow"
>>> df.write_ipc(path)
"""
return_bytes = file is None
target: str | Path | IO[bytes]
if file is None:
target = BytesIO()
else:
target = file
from polars.lazyframe.opt_flags import QueryOptFlags
with contextlib.suppress(UnstableWarning):
self.lazy().sink_ipc(
target,
compression=compression,
compat_level=compat_level,
storage_options=storage_options,
credential_provider=credential_provider,
retries=retries,
optimizations=QueryOptFlags._eager(),
engine="streaming",
)
return target if return_bytes else None # type: ignore[return-value]
@overload
def write_ipc_stream(
self,
file: None,
*,
compression: IpcCompression = "uncompressed",
compat_level: CompatLevel | None = None,
) -> BytesIO: ...
@overload
def write_ipc_stream(
self,
file: str | Path | IO[bytes],
*,
compression: IpcCompression = "uncompressed",
compat_level: CompatLevel | None = None,
) -> None: ...
@deprecate_renamed_parameter("future", "compat_level", version="1.1")
def write_ipc_stream(
self,
file: str | Path | IO[bytes] | None,
*,
compression: IpcCompression = "uncompressed",
compat_level: CompatLevel | None = None,
) -> BytesIO | None:
"""
Write to Arrow IPC record batch stream.
See "Streaming format" in https://arrow.apache.org/docs/python/ipc.html.
.. versionchanged:: 1.1
The `future` parameter was renamed `compat_level`.
Parameters
----------
file
Path or writable file-like object to which the IPC record batch data will
be written. If set to `None`, the output is returned as a BytesIO object.
compression : {'uncompressed', 'lz4', 'zstd'}
Compression method. Defaults to "uncompressed".
compat_level
Use a specific compatibility level
when exporting Polars' internal data structures.
Examples
--------
>>> import pathlib
>>>
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> path: pathlib.Path = dirpath / "new_file.arrow"
>>> df.write_ipc_stream(path)
"""
return_bytes = file is None
if return_bytes:
file = BytesIO()
elif isinstance(file, (str, Path)):
file = normalize_filepath(file)
compat_level_py: int | bool
if compat_level is None:
compat_level_py = True
elif isinstance(compat_level, CompatLevel):
compat_level_py = compat_level._version
if compression is None:
compression = "uncompressed"
self._df.write_ipc_stream(file, compression, compat_level_py)
return file if return_bytes else None # type: ignore[return-value]
def write_parquet(
self,
file: str | Path | IO[bytes],
*,
compression: ParquetCompression = "zstd",
compression_level: int | None = None,
statistics: bool | str | dict[str, bool] = True,
row_group_size: int | None = None,
data_page_size: int | None = None,
use_pyarrow: bool = False,
pyarrow_options: dict[str, Any] | None = None,
partition_by: str | Sequence[str] | None = None,
partition_chunk_size_bytes: int = 4_294_967_296,
storage_options: dict[str, Any] | None = None,
credential_provider: (
CredentialProviderFunction | Literal["auto"] | None
) = "auto",
retries: int = 2,
metadata: ParquetMetadata | None = None,
mkdir: bool = False,
) -> None:
"""
Write to Apache Parquet file.
Parameters
----------
file
File path or writable file-like object to which the result will be written.
This should be a path to a directory if writing a partitioned dataset.
compression : {'lz4', 'uncompressed', 'snappy', 'gzip', 'brotli', 'zstd'}
Choose "zstd" for good compression performance.
Choose "lz4" for fast compression/decompression.
Choose "snappy" for more backwards compatibility guarantees
when you deal with older parquet readers.
compression_level
The level of compression to use. Higher compression means smaller files on
disk.
- "gzip" : min-level: 0, max-level: 9, default: 6.
- "brotli" : min-level: 0, max-level: 11, default: 1.
- "zstd" : min-level: 1, max-level: 22, default: 3.
statistics
Write statistics to the parquet headers. This is the default behavior.
Possible values:
- `True`: enable default set of statistics (default). Some
statistics may be disabled.
- `False`: disable all statistics
- "full": calculate and write all available statistics. Cannot be
combined with `use_pyarrow`.
- `{ "statistic-key": True / False, ... }`. Cannot be combined with
`use_pyarrow`. Available keys:
- "min": column minimum value (default: `True`)
- "max": column maximum value (default: `True`)
- "distinct_count": number of unique column values (default: `False`)
- "null_count": number of null values in column (default: `True`)
row_group_size
Size of the row groups in number of rows. Defaults to 512^2 rows.
data_page_size
Size of the data page in bytes. Defaults to 1024^2 bytes.
use_pyarrow
Use C++ parquet implementation vs Rust parquet implementation.
At the moment C++ supports more features.
pyarrow_options
Arguments passed to `pyarrow.parquet.write_table`.
If you pass `partition_cols` here, the dataset will be written
using `pyarrow.parquet.write_to_dataset`.
The `partition_cols` parameter leads to write the dataset to a directory.
Similar to Spark's partitioned datasets.
partition_by
Column(s) to partition by. A partitioned dataset will be written if this is
specified. This parameter is considered unstable and is subject to change.
partition_chunk_size_bytes
Approximate size to split DataFrames within a single partition when
writing. Note this is calculated using the size of the DataFrame in
memory - the size of the output file may differ depending on the
file format / compression.
storage_options
Options that indicate how to connect to a cloud provider.
The cloud providers currently supported are AWS, GCP, and Azure.
See supported keys here:
* `aws <https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html>`_
* `gcp <https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html>`_
* `azure <https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html>`_
* Hugging Face (`hf://`): Accepts an API key under the `token` parameter: \
`{'token': '...'}`, or by setting the `HF_TOKEN` environment variable.
If `storage_options` is not provided, Polars will try to infer the
information from environment variables.
credential_provider
Provide a function that can be called to provide cloud storage
credentials. The function is expected to return a dictionary of
credential keys along with an optional credential expiry time.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
retries
Number of retries if accessing a cloud instance fails.
metadata
A dictionary or callback to add key-values to the file-level Parquet
metadata.
.. warning::
This functionality is considered **experimental**. It may be removed or
changed at any point without it being considered a breaking change.
mkdir: bool
Recursively create all the directories in the path.
.. warning::
This functionality is considered **unstable**. It may be changed at any
point without it being considered a breaking change.
Examples
--------
>>> import pathlib
>>>
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> path: pathlib.Path = dirpath / "new_file.parquet"
>>> df.write_parquet(path)
We can use pyarrow with use_pyarrow_write_to_dataset=True
to write partitioned datasets. The following example will
write the first row to ../watermark=1/*.parquet and the
other rows to ../watermark=2/*.parquet.
>>> df = pl.DataFrame({"a": [1, 2, 3], "watermark": [1, 2, 2]})
>>> path: pathlib.Path = dirpath / "partitioned_object"
>>> df.write_parquet(
... path,
... use_pyarrow=True,
... pyarrow_options={"partition_cols": ["watermark"]},
... )
"""
if compression is None:
compression = "uncompressed"
if isinstance(file, (str, Path)):
if partition_by is not None or (
pyarrow_options is not None and pyarrow_options.get("partition_cols")
):
file = normalize_filepath(file, check_not_directory=False)
else:
file = normalize_filepath(file)
if use_pyarrow:
if statistics == "full" or isinstance(statistics, dict):
msg = "write_parquet with `use_pyarrow=True` allows only boolean values for `statistics`"
raise ValueError(msg)
if metadata is not None:
msg = "write_parquet with `use_pyarrow=True` cannot be combined with `metadata`"
raise ValueError(msg)
if mkdir:
msg = "write_parquet with `use_pyarrow=True` cannot be combined with `mkdir`"
raise ValueError(msg)
tbl = self.to_arrow()
data = {}
for i, column in enumerate(tbl):
# extract the name before casting
name = f"column_{i}" if column._name is None else column._name
data[name] = column
tbl = pa.table(data)
# do not remove this import!
# needed below
import pyarrow.parquet # noqa: F401
if pyarrow_options is None:
pyarrow_options = {}
pyarrow_options["compression"] = (
None if compression == "uncompressed" else compression
)
pyarrow_options["compression_level"] = compression_level
pyarrow_options["write_statistics"] = statistics
pyarrow_options["row_group_size"] = row_group_size
pyarrow_options["data_page_size"] = data_page_size
if pyarrow_options.get("partition_cols"):
pa.parquet.write_to_dataset(
table=tbl,
root_path=file,
**(pyarrow_options or {}),
)
else:
pa.parquet.write_table(
table=tbl,
where=file,
**(pyarrow_options or {}),
)
return
target: str | Path | IO[bytes] | _SinkDirectory = file
engine: EngineType = "streaming"
if partition_by is not None:
if not isinstance(file, str):
msg = "expected file to be a `str` since partition-by is set"
raise TypeError(msg)
from polars.io import PartitionByKey
target = PartitionByKey(file, by=partition_by)
mkdir = True
from polars.lazyframe.opt_flags import QueryOptFlags
self.lazy().sink_parquet(
target,
compression=compression,
compression_level=compression_level,
statistics=statistics,
row_group_size=row_group_size,
data_page_size=data_page_size,
storage_options=storage_options,
credential_provider=credential_provider,
retries=retries,
metadata=metadata,
engine=engine,
mkdir=mkdir,
optimizations=QueryOptFlags._eager(),
)
def write_database(
self,
table_name: str,
connection: ConnectionOrCursor | str,
*,
if_table_exists: DbWriteMode = "fail",
engine: DbWriteEngine | None = None,
engine_options: dict[str, Any] | None = None,
) -> int:
"""
Write the data in a Polars DataFrame to a database.
.. versionadded:: 0.20.26
Support for instantiated connection objects in addition to URI strings, and
a new `engine_options` parameter.
Parameters
----------
table_name
Schema-qualified name of the table to create or append to in the target
SQL database. If your table name contains special characters, it should
be quoted.
connection
An existing SQLAlchemy or ADBC connection against the target database, or
a URI string that will be used to instantiate such a connection, such as:
* "postgresql://user:pass@server:port/database"
* "sqlite:////path/to/database.db"
if_table_exists : {'append', 'replace', 'fail'}
The insert mode:
* 'replace' will create a new database table, overwriting an existing one.
* 'append' will append to an existing table.
* 'fail' will fail if table already exists.
engine : {'sqlalchemy', 'adbc'}
Select the engine to use for writing frame data; only necessary when
supplying a URI string (defaults to 'sqlalchemy' if unset)
engine_options
Additional options to pass to the insert method associated with the engine
specified by the option `engine`.
* Setting `engine` to "sqlalchemy" currently inserts using Pandas' `to_sql`
method (though this will eventually be phased out in favor of a native
solution).
* Setting `engine` to "adbc" inserts using the ADBC cursor's `adbc_ingest`
method. Note that when passing an instantiated connection object, PyArrow
is required for SQLite and Snowflake drivers.
Examples
--------
Insert into a temporary table using a PostgreSQL URI and the ADBC engine:
>>> df.write_database(
... table_name="target_table",
... connection="postgresql://user:pass@server:port/database",
... engine="adbc",
... engine_options={"temporary": True},
... ) # doctest: +SKIP
Insert into a table using a `pyodbc` SQLAlchemy connection to SQL Server
that was instantiated with "fast_executemany=True" to improve performance:
>>> pyodbc_uri = (
... "mssql+pyodbc://user:pass@server:1433/test?"
... "driver=ODBC+Driver+18+for+SQL+Server"
... )
>>> engine = create_engine(pyodbc_uri, fast_executemany=True) # doctest: +SKIP
>>> df.write_database(
... table_name="target_table",
... connection=engine,
... ) # doctest: +SKIP
Returns
-------
int
The number of rows affected, if the driver provides this information.
Otherwise, returns -1.
"""
if if_table_exists not in (valid_write_modes := get_args(DbWriteMode)):
allowed = ", ".join(repr(m) for m in valid_write_modes)
msg = f"write_database `if_table_exists` must be one of {{{allowed}}}, got {if_table_exists!r}"
raise ValueError(msg)
connection_module_root = type(connection).__module__.split(".", 1)[0]
if engine is None:
if isinstance(connection, str) or connection_module_root == "sqlalchemy":
engine = "sqlalchemy"
elif connection_module_root.startswith("adbc"):
engine = "adbc"
def unpack_table_name(name: str) -> tuple[str | None, str | None, str]:
"""Unpack optionally qualified table name to catalog/schema/table tuple."""
from csv import reader as delimited_read
components: list[str | None] = next(delimited_read([name], delimiter=".")) # type: ignore[arg-type]
if len(components) > 3:
msg = f"`table_name` appears to be invalid: '{name}'"
raise ValueError(msg)
catalog, schema, tbl = ([None] * (3 - len(components))) + components
return catalog, schema, tbl # type: ignore[return-value]
if engine == "adbc":
from polars.io.database._utils import (
_get_adbc_module_name_from_uri,
_import_optional_adbc_driver,
_is_adbc_snowflake_conn,
_open_adbc_connection,
)
conn, can_close_conn = (
(_open_adbc_connection(connection), True)
if isinstance(connection, str)
else (connection, False)
)
driver_manager = import_optional("adbc_driver_manager")
# base class for ADBC connections
if not isinstance(conn, driver_manager.dbapi.Connection):
msg = (
f"unrecognised connection type {qualified_type_name(connection)!r}"
)
raise TypeError(msg)
driver_manager_str_version = getattr(driver_manager, "__version__", "0.0")
driver_manager_version = parse_version(driver_manager_str_version)
if if_table_exists == "fail":
# if the table exists, 'create' will raise an error,
# resulting in behaviour equivalent to 'fail'
mode = "create"
elif if_table_exists == "replace":
if driver_manager_version < (0, 7):
msg = (
"`if_table_exists = 'replace'` requires ADBC version >= 0.7, "
f"found {driver_manager_str_version}"
)
raise ModuleUpgradeRequiredError(msg)
mode = "replace"
elif if_table_exists == "append":
mode = "append"
else:
msg = (
f"unexpected value for `if_table_exists`: {if_table_exists!r}"
f"\n\nChoose one of {{'fail', 'replace', 'append'}}"
)
raise ValueError(msg)
with (
conn if can_close_conn else contextlib.nullcontext(),
conn.cursor() as cursor,
):
catalog, db_schema, unpacked_table_name = unpack_table_name(table_name)
n_rows: int
# We can reliably introspect the underlying driver from a URI
# We can also introspect instantiated connections when PyArrow is
# installed. Otherwise, the underlying driver is unknown
# Ref: https://github.com/apache/arrow-adbc/issues/2828
if isinstance(connection, str):
adbc_module_name = _get_adbc_module_name_from_uri(connection)
elif _PYARROW_AVAILABLE:
adbc_module_name = (
f"adbc_driver_{conn.adbc_get_info()['vendor_name'].lower()}"
)
else:
adbc_module_name = "Unknown"
if adbc_module_name != "Unknown":
adbc_driver = _import_optional_adbc_driver(
adbc_module_name, dbapi_submodule=False
)
adbc_driver_str_version = getattr(adbc_driver, "__version__", "0.0")
else:
adbc_driver = "Unknown"
# If we can't introspect the driver, guess that it has the same
# version as the driver manager. This is what happens by default
# when installed
adbc_driver_str_version = driver_manager_str_version
adbc_driver_version = parse_version(adbc_driver_str_version)
if adbc_module_name.split("_")[-1] == "sqlite":
catalog, db_schema = db_schema, None
# note: ADBC didnt't support 'replace' until adbc-driver-sqlite
# version 0.11 (it was released for other drivers in version 0.7)
if (
driver_manager_version >= (0, 7)
and adbc_driver_version < (0, 11)
and if_table_exists == "replace"
):
cursor.execute(f"DROP TABLE IF EXISTS {table_name}")
mode = "create"
# For Snowflake, we convert to PyArrow until string_view columns can be
# written. Ref: https://github.com/apache/arrow-adbc/issues/3420
is_snowflake_driver = (
"snowflake" in adbc_module_name
if _PYARROW_AVAILABLE
else _is_adbc_snowflake_conn(conn)
)
if is_snowflake_driver and not _PYARROW_AVAILABLE:
msg = (
"write_database with Snowflake driver requires 'pyarrow'.\n"
"Please install using the command `pip install pyarrow`."
)
raise ModuleNotFoundError(msg)
# As of adbc_driver_manager 1.6.0, adbc_ingest can take a Polars
# DataFrame via the PyCapsule interface
data = (
self
if (driver_manager_version >= (1, 6)) and not is_snowflake_driver
else self.to_arrow()
)
# use of schema-qualified table names was released in
# adbc-driver-manager 0.7.0 and is working without bugs from driver
# version (e.g., adbc-driver-postgresql) version 0.8.0
if driver_manager_version >= (0, 7) and adbc_driver_version >= (0, 8):
n_rows = cursor.adbc_ingest(
unpacked_table_name,
data=data,
mode=mode,
catalog_name=catalog,
db_schema_name=db_schema,
**(engine_options or {}),
)
elif db_schema is not None:
adbc_driver_pypi_name = (
adbc_module_name.replace("_", "-")
if adbc_module_name != "Unknown"
else "adbc-driver-<driver>"
)
msg = (
"use of schema-qualified table names requires "
"adbc-driver-manager version >= 0.7.0, found "
f"{driver_manager_str_version} and {adbc_driver_pypi_name} "
f"version >= 0.8.0, found {adbc_driver_str_version}"
)
raise ModuleUpgradeRequiredError(
# https://github.com/apache/arrow-adbc/issues/1000
# https://github.com/apache/arrow-adbc/issues/1109
msg
)
else:
n_rows = cursor.adbc_ingest(
table_name=unpacked_table_name,
data=data,
mode=mode,
**(engine_options or {}),
)
conn.commit()
return n_rows
elif engine == "sqlalchemy":
if not _PANDAS_AVAILABLE:
msg = "writing with 'sqlalchemy' engine currently requires pandas.\n\nInstall with: pip install pandas"
raise ModuleNotFoundError(msg)
elif (pd_version := parse_version(pd.__version__)) < (1, 5):
msg = f"writing with 'sqlalchemy' engine requires pandas >= 1.5; found {pd.__version__!r}"
raise ModuleUpgradeRequiredError(msg)
import_optional(
module_name="sqlalchemy",
min_version=("2.0" if pd_version >= (2, 2) else "1.4"),
min_err_prefix="pandas >= 2.2 requires",
)
# note: the catalog (database) should be a part of the connection string
from sqlalchemy.engine import Connectable, create_engine
from sqlalchemy.orm import Session
sa_object: Connectable
if isinstance(connection, str):
sa_object = create_engine(connection)
elif isinstance(connection, Session):
sa_object = connection.connection()
elif isinstance(connection, Connectable):
sa_object = connection
else:
msg = (
f"unrecognised connection type {qualified_type_name(connection)!r}"
)
raise TypeError(msg)
catalog, db_schema, unpacked_table_name = unpack_table_name(table_name)
if catalog:
msg = f"Unexpected three-part table name; provide the database/catalog ({catalog!r}) on the connection URI"
raise ValueError(msg)
# ensure conversion to pandas uses the pyarrow extension array option
# so that we can make use of the sql/db export *without* copying data
res: int | None = self.to_pandas(
use_pyarrow_extension_array=True,
).to_sql(
name=unpacked_table_name,
schema=db_schema,
con=sa_object,
if_exists=if_table_exists,
index=False,
**(engine_options or {}),
)
return -1 if res is None else res
elif isinstance(engine, str):
msg = f"engine {engine!r} is not supported"
raise ValueError(msg)
else:
msg = f"unrecognised connection type {qualified_type_name(connection)!r}"
raise TypeError(msg)
@unstable()
def write_iceberg(
self,
target: str | pyiceberg.table.Table,
mode: Literal["append", "overwrite"],
) -> None:
"""
Write DataFrame to an Iceberg table.
.. warning::
This functionality is currently considered **unstable**. It may be
changed at any point without it being considered a breaking change.
Parameters
----------
target
Name of the table or the Table object representing an Iceberg table.
mode : {'append', 'overwrite'}
How to handle existing data.
- If 'append', will add new data.
- If 'overwrite', will replace table with new data.
"""
from pyiceberg.catalog import load_catalog
if isinstance(target, str):
catalog = load_catalog()
table = catalog.load_table(target)
else:
table = target
data = self.to_arrow(compat_level=CompatLevel.oldest())
if mode == "append":
table.append(data)
else:
table.overwrite(data)
@overload
def write_delta(
self,
target: str | Path | deltalake.DeltaTable,
*,
mode: Literal["error", "append", "overwrite", "ignore"] = ...,
overwrite_schema: bool | None = ...,
storage_options: dict[str, str] | None = ...,
credential_provider: CredentialProviderFunction | Literal["auto"] | None = ...,
delta_write_options: dict[str, Any] | None = ...,
) -> None: ...
@overload
def write_delta(
self,
target: str | Path | deltalake.DeltaTable,
*,
mode: Literal["merge"],
overwrite_schema: bool | None = ...,
storage_options: dict[str, str] | None = ...,
credential_provider: CredentialProviderFunction | Literal["auto"] | None = ...,
delta_merge_options: dict[str, Any],
) -> deltalake.table.TableMerger: ...
def write_delta(
self,
target: str | Path | deltalake.DeltaTable,
*,
mode: Literal["error", "append", "overwrite", "ignore", "merge"] = "error",
overwrite_schema: bool | None = None,
storage_options: dict[str, str] | None = None,
credential_provider: CredentialProviderFunction
| Literal["auto"]
| None = "auto",
delta_write_options: dict[str, Any] | None = None,
delta_merge_options: dict[str, Any] | None = None,
) -> deltalake.table.TableMerger | None:
"""
Write DataFrame as delta table.
Parameters
----------
target
URI of a table or a DeltaTable object.
mode : {'error', 'append', 'overwrite', 'ignore', 'merge'}
How to handle existing data.
- If 'error', throw an error if the table already exists (default).
- If 'append', will add new data.
- If 'overwrite', will replace table with new data.
- If 'ignore', will not write anything if table already exists.
- If 'merge', return a `TableMerger` object to merge data from the DataFrame
with the existing data.
overwrite_schema
If True, allows updating the schema of the table.
.. deprecated:: 0.20.14
Use the parameter `delta_write_options` instead and pass
`{"schema_mode": "overwrite"}`.
storage_options
Extra options for the storage backends supported by `deltalake`.
For cloud storages, this may include configurations for authentication etc.
- See a list of supported storage options for S3 `here <https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants>`__.
- See a list of supported storage options for GCS `here <https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html#variants>`__.
- See a list of supported storage options for Azure `here <https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants>`__.
credential_provider
Provide a function that can be called to provide cloud storage
credentials. The function is expected to return a dictionary of
credential keys along with an optional credential expiry time.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
delta_write_options
Additional keyword arguments while writing a Delta lake Table.
See a list of supported write options `here <https://delta-io.github.io/delta-rs/api/delta_writer/#deltalake.write_deltalake>`__.
delta_merge_options
Keyword arguments which are required to `MERGE` a Delta lake Table.
See a list of supported merge options `here <https://delta-io.github.io/delta-rs/api/delta_table/#deltalake.DeltaTable.merge>`__.
Raises
------
TypeError
If the DataFrame contains unsupported data types.
ArrowInvalidError
If the DataFrame contains data types that could not be cast to their
primitive type.
TableNotFoundError
If the delta table doesn't exist and MERGE action is triggered
Notes
-----
The Polars data types :class:`Null` and :class:`Time` are not supported
by the delta protocol specification and will raise a TypeError. Columns
using The :class:`Categorical` data type will be converted to
normal (non-categorical) strings when written.
Polars columns are always nullable. To write data to a delta table with
non-nullable columns, a custom pyarrow schema has to be passed to the
`delta_write_options`. See the last example below.
Examples
--------
Write a dataframe to the local filesystem as a Delta Lake table.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> table_path = "/path/to/delta-table/"
>>> df.write_delta(table_path) # doctest: +SKIP
Append data to an existing Delta Lake table on the local filesystem.
Note that this will fail if the schema of the new data does not match the
schema of the existing table.
>>> df.write_delta(table_path, mode="append") # doctest: +SKIP
Overwrite a Delta Lake table as a new version.
If the schemas of the new and old data are the same, specifying the
`schema_mode` is not required.
>>> existing_table_path = "/path/to/delta-table/"
>>> df.write_delta(
... existing_table_path,
... mode="overwrite",
... delta_write_options={"schema_mode": "overwrite"},
... ) # doctest: +SKIP
Write a DataFrame as a Delta Lake table to a cloud object store like S3.
>>> table_path = "s3://bucket/prefix/to/delta-table/"
>>> df.write_delta(
... table_path,
... storage_options={
... "AWS_REGION": "THE_AWS_REGION",
... "AWS_ACCESS_KEY_ID": "THE_AWS_ACCESS_KEY_ID",
... "AWS_SECRET_ACCESS_KEY": "THE_AWS_SECRET_ACCESS_KEY",
... },
... ) # doctest: +SKIP
Write DataFrame as a Delta Lake table with non-nullable columns.
>>> import pyarrow as pa
>>> existing_table_path = "/path/to/delta-table/"
>>> df.write_delta(
... existing_table_path,
... delta_write_options={
... "schema": pa.schema([pa.field("foo", pa.int64(), nullable=False)])
... },
... ) # doctest: +SKIP
Write DataFrame as a Delta Lake table with zstd compression.
For all `delta_write_options` keyword arguments, check the deltalake docs
`here
<https://delta-io.github.io/delta-rs/api/delta_writer/#deltalake.write_deltalake>`__,
and for Writer Properties in particular `here
<https://delta-io.github.io/delta-rs/api/delta_writer/#deltalake.WriterProperties>`__.
>>> import deltalake
>>> df.write_delta(
... table_path,
... delta_write_options={
... "writer_properties": deltalake.WriterProperties(compression="zstd"),
... },
... ) # doctest: +SKIP
Merge the DataFrame with an existing Delta Lake table.
For all `TableMerger` methods, check the deltalake docs
`here <https://delta-io.github.io/delta-rs/api/delta_table/delta_table_merger/>`__.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> table_path = "/path/to/delta-table/"
>>> (
... df.write_delta(
... "table_path",
... mode="merge",
... delta_merge_options={
... "predicate": "s.foo = t.foo",
... "source_alias": "s",
... "target_alias": "t",
... },
... )
... .when_matched_update_all()
... .when_not_matched_insert_all()
... .execute()
... ) # doctest: +SKIP
"""
if overwrite_schema is not None:
issue_deprecation_warning(
"the parameter `overwrite_schema` for `write_delta` is deprecated."
' Use the parameter `delta_write_options` instead and pass `{"schema_mode": "overwrite"}`.',
version="0.20.14",
)
from polars.io.delta import (
_check_for_unsupported_types,
_check_if_delta_available,
_resolve_delta_lake_uri,
)
_check_if_delta_available()
from deltalake import DeltaTable, write_deltalake
_check_for_unsupported_types(self.dtypes)
if isinstance(target, (str, Path)):
target = _resolve_delta_lake_uri(str(target), strict=False)
from polars.io.cloud.credential_provider._builder import (
_init_credential_provider_builder,
)
from polars.io.cloud.credential_provider._providers import (
_get_credentials_from_provider_expiry_aware,
)
if not isinstance(target, DeltaTable):
credential_provider_builder = _init_credential_provider_builder(
credential_provider, target, storage_options, "write_delta"
)
elif credential_provider is not None and credential_provider != "auto":
msg = "cannot use credential_provider when passing a DeltaTable object"
raise ValueError(msg)
else:
credential_provider_builder = None
del credential_provider
credential_provider_creds = {}
if credential_provider_builder and (
provider := credential_provider_builder.build_credential_provider()
):
credential_provider_creds = (
_get_credentials_from_provider_expiry_aware(provider) or {}
)
# We aren't calling into polars-native write functions so we just update
# the storage_options here.
storage_options = (
{**(storage_options or {}), **credential_provider_creds}
if storage_options is not None or credential_provider_builder is not None
else None
)
if mode == "merge":
if delta_merge_options is None:
msg = "you need to pass delta_merge_options with at least a given predicate for `MERGE` to work."
raise ValueError(msg)
if isinstance(target, str):
dt = DeltaTable(table_uri=target, storage_options=storage_options)
else:
dt = target
return dt.merge(self, **delta_merge_options)
else:
if delta_write_options is None:
delta_write_options = {}
if overwrite_schema:
delta_write_options["schema_mode"] = "overwrite"
write_deltalake(
table_or_uri=target,
data=self,
mode=mode,
storage_options=storage_options,
**delta_write_options,
)
return None
def estimated_size(self, unit: SizeUnit = "b") -> int | float:
"""
Return an estimation of the total (heap) allocated size of the `DataFrame`.
Estimated size is given in the specified unit (bytes by default).
This estimation is the sum of the size of its buffers, validity, including
nested arrays. Multiple arrays may share buffers and bitmaps. Therefore, the
size of 2 arrays is not the sum of the sizes computed from this function. In
particular, [`StructArray`]'s size is an upper bound.
When an array is sliced, its allocated size remains constant because the buffer
unchanged. However, this function will yield a smaller number. This is because
this function returns the visible size of the buffer, not its total capacity.
FFI buffers are included in this estimation.
Notes
-----
For data with Object dtype, the estimated size only reports the pointer
size, which is a huge underestimation.
Parameters
----------
unit : {'b', 'kb', 'mb', 'gb', 'tb'}
Scale the returned size to the given unit.
Examples
--------
>>> df = pl.DataFrame(
... {
... "x": list(reversed(range(1_000_000))),
... "y": [v / 1000 for v in range(1_000_000)],
... "z": [str(v) for v in range(1_000_000)],
... },
... schema=[("x", pl.UInt32), ("y", pl.Float64), ("z", pl.String)],
... )
>>> df.estimated_size()
17888890
>>> df.estimated_size("mb")
17.0601749420166
"""
sz = self._df.estimated_size()
return scale_bytes(sz, unit)
def transpose(
self,
*,
include_header: bool = False,
header_name: str = "column",
column_names: str | Iterable[str] | None = None,
) -> DataFrame:
"""
Transpose a DataFrame over the diagonal.
Parameters
----------
include_header
If set, the column names will be added as first column.
header_name
If `include_header` is set, this determines the name of the column that will
be inserted.
column_names
Optional iterable yielding strings or a string naming an existing column.
These will name the value (non-header) columns in the transposed data.
Notes
-----
This is a very expensive operation. Perhaps you can do it differently.
Returns
-------
DataFrame
Examples
--------
>>> df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
>>> df.transpose(include_header=True)
shape: (2, 4)
┌────────┬──────────┬──────────┬──────────┐
│ column ┆ column_0 ┆ column_1 ┆ column_2 │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞════════╪══════════╪══════════╪══════════╡
│ a ┆ 1 ┆ 2 ┆ 3 │
│ b ┆ 4 ┆ 5 ┆ 6 │
└────────┴──────────┴──────────┴──────────┘
Replace the auto-generated column names with a list
>>> df.transpose(include_header=False, column_names=["x", "y", "z"])
shape: (2, 3)
┌─────┬─────┬─────┐
│ x ┆ y ┆ z │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 2 ┆ 3 │
│ 4 ┆ 5 ┆ 6 │
└─────┴─────┴─────┘
Include the header as a separate column
>>> df.transpose(
... include_header=True, header_name="foo", column_names=["x", "y", "z"]
... )
shape: (2, 4)
┌─────┬─────┬─────┬─────┐
│ foo ┆ x ┆ y ┆ z │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╡
│ a ┆ 1 ┆ 2 ┆ 3 │
│ b ┆ 4 ┆ 5 ┆ 6 │
└─────┴─────┴─────┴─────┘
Replace the auto-generated column with column names from a generator function
>>> def name_generator():
... base_name = "my_column_"
... count = 0
... while True:
... yield f"{base_name}{count}"
... count += 1
>>> df.transpose(include_header=False, column_names=name_generator())
shape: (2, 3)
┌─────────────┬─────────────┬─────────────┐
│ my_column_0 ┆ my_column_1 ┆ my_column_2 │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════════════╪═════════════╪═════════════╡
│ 1 ┆ 2 ┆ 3 │
│ 4 ┆ 5 ┆ 6 │
└─────────────┴─────────────┴─────────────┘
Use an existing column as the new column names
>>> df = pl.DataFrame(dict(id=["i", "j", "k"], a=[1, 2, 3], b=[4, 5, 6]))
>>> df.transpose(column_names="id")
shape: (2, 3)
┌─────┬─────┬─────┐
│ i ┆ j ┆ k │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 2 ┆ 3 │
│ 4 ┆ 5 ┆ 6 │
└─────┴─────┴─────┘
>>> df.transpose(include_header=True, header_name="new_id", column_names="id")
shape: (2, 4)
┌────────┬─────┬─────┬─────┐
│ new_id ┆ i ┆ j ┆ k │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞════════╪═════╪═════╪═════╡
│ a ┆ 1 ┆ 2 ┆ 3 │
│ b ┆ 4 ┆ 5 ┆ 6 │
└────────┴─────┴─────┴─────┘
"""
keep_names_as = header_name if include_header else None
column_names_: Sequence[str] | None
if isinstance(column_names, Generator):
column_names_ = [next(column_names) for _ in range(self.height)]
else:
column_names_ = column_names # type: ignore[assignment]
return self._from_pydf(self._df.transpose(keep_names_as, column_names_))
def reverse(self) -> DataFrame:
"""
Reverse the DataFrame.
Examples
--------
>>> df = pl.DataFrame(
... {
... "key": ["a", "b", "c"],
... "val": [1, 2, 3],
... }
... )
>>> df.reverse()
shape: (3, 2)
┌─────┬─────┐
│ key ┆ val │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ c ┆ 3 │
│ b ┆ 2 │
│ a ┆ 1 │
└─────┴─────┘
"""
return self.select(F.col("*").reverse())
def rename(
self, mapping: Mapping[str, str] | Callable[[str], str], *, strict: bool = True
) -> DataFrame:
"""
Rename column names.
Parameters
----------
mapping
Key value pairs that map from old name to new name, or a function
that takes the old name as input and returns the new name.
strict
Validate that all column names exist in the current schema,
and throw an exception if any do not. (Note that this parameter
is a no-op when passing a function to `mapping`).
See Also
--------
Expr.name.replace
Examples
--------
>>> df = pl.DataFrame(
... {"foo": [1, 2, 3], "bar": [6, 7, 8], "ham": ["a", "b", "c"]}
... )
>>> df.rename({"foo": "apple"})
shape: (3, 3)
┌───────┬─────┬─────┐
│ apple ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═══════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└───────┴─────┴─────┘
>>> df.rename(lambda column_name: "c" + column_name[1:])
shape: (3, 3)
┌─────┬─────┬─────┐
│ coo ┆ car ┆ cam │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└─────┴─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.rename(mapping, strict=strict)
.collect(optimizations=QueryOptFlags._eager())
)
def insert_column(self, index: int, column: IntoExprColumn) -> DataFrame:
"""
Insert a Series (or expression) at a certain column index.
This operation is in place.
Parameters
----------
index
Index at which to insert the new column.
column
`Series` or expression to insert.
Examples
--------
Insert a new Series column at the given index:
>>> df = pl.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
>>> s = pl.Series("baz", [97, 98, 99])
>>> df.insert_column(1, s)
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ baz ┆ bar │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 97 ┆ 4 │
│ 2 ┆ 98 ┆ 5 │
│ 3 ┆ 99 ┆ 6 │
└─────┴─────┴─────┘
Insert a new expression column at the given index:
>>> df = pl.DataFrame(
... {"a": [2, 4, 2], "b": [0.5, 4, 10], "c": ["xx", "yy", "zz"]}
... )
>>> expr = (pl.col("b") / pl.col("a")).alias("b_div_a")
>>> df.insert_column(2, expr)
shape: (3, 4)
┌─────┬──────┬─────────┬─────┐
│ a ┆ b ┆ b_div_a ┆ c │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ str │
╞═════╪══════╪═════════╪═════╡
│ 2 ┆ 0.5 ┆ 0.25 ┆ xx │
│ 4 ┆ 4.0 ┆ 1.0 ┆ yy │
│ 2 ┆ 10.0 ┆ 5.0 ┆ zz │
└─────┴──────┴─────────┴─────┘
"""
if (original_index := index) < 0:
index = self.width + index
if index < 0:
msg = f"column index {original_index} is out of range (frame has {self.width} columns)"
raise IndexError(msg)
elif index > self.width:
msg = f"column index {original_index} is out of range (frame has {self.width} columns)"
raise IndexError(msg)
if isinstance(column, pl.Series):
self._df.insert_column(index, column._s)
else:
if isinstance(column, str):
column = F.col(column)
if isinstance(column, pl.Expr):
cols = self.columns
cols.insert(index, column) # type: ignore[arg-type]
self._df = self.select(cols)._df
else:
msg = f"column must be a Series or Expr, got {column!r} (type={qualified_type_name(column)})"
raise TypeError(msg)
return self
def filter(
self,
*predicates: (
IntoExprColumn
| Iterable[IntoExprColumn]
| bool
| list[bool]
| np.ndarray[Any, Any]
),
**constraints: Any,
) -> DataFrame:
"""
Filter rows, retaining those that match the given predicate expression(s).
The original order of the remaining rows is preserved.
Only rows where the predicate resolves as True are retained; when the
predicate result is False (or null), the row is discarded.
Parameters
----------
predicates
Expression(s) that evaluate to a boolean Series.
constraints
Column filters; use `name = value` to filter columns by the supplied value.
Each constraint will behave the same as `pl.col(name).eq(value)`, and
be implicitly joined with the other filter conditions using `&`.
Notes
-----
If you are transitioning from Pandas, and performing filter operations based on
the comparison of two or more columns, please note that in Polars any comparison
involving `null` values will result in a `null` result, *not* boolean True or
False. As a result, these rows will not be retained. Ensure that null values
are handled appropriately to avoid unexpected behaviour (see examples below).
See Also
--------
remove
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, None, 4, None, 0],
... "bar": [6, 7, 8, None, None, 9, 0],
... "ham": ["a", "b", "c", None, "d", "e", "f"],
... }
... )
Filter rows matching a condition:
>>> df.filter(pl.col("foo") > 1)
shape: (3, 3)
┌─────┬──────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪══════╪═════╡
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
│ 4 ┆ null ┆ d │
└─────┴──────┴─────┘
Filter on multiple conditions, combined with and/or operators:
>>> df.filter(
... (pl.col("foo") < 3) & (pl.col("ham") == "a"),
... )
shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
└─────┴─────┴─────┘
>>> df.filter(
... (pl.col("foo") == 1) | (pl.col("ham") == "c"),
... )
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 3 ┆ 8 ┆ c │
└─────┴─────┴─────┘
Provide multiple filters using `*args` syntax:
>>> df.filter(
... pl.col("foo") <= 2,
... ~pl.col("ham").is_in(["b", "c"]),
... )
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 0 ┆ 0 ┆ f │
└─────┴─────┴─────┘
Provide multiple filters using `**kwargs` syntax:
>>> df.filter(foo=2, ham="b")
shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 2 ┆ 7 ┆ b │
└─────┴─────┴─────┘
Filter by comparing two columns against each other:
>>> df.filter(
... pl.col("foo") == pl.col("bar"),
... )
shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 0 ┆ 0 ┆ f │
└─────┴─────┴─────┘
>>> df.filter(
... pl.col("foo") != pl.col("bar"),
... )
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└─────┴─────┴─────┘
Notice how the row with `None` values is filtered out. In order to keep the
same behavior as pandas, use:
>>> df.filter(
... pl.col("foo").ne_missing(pl.col("bar")),
... )
shape: (5, 3)
┌──────┬──────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞══════╪══════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
│ 4 ┆ null ┆ d │
│ null ┆ 9 ┆ e │
└──────┴──────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.filter(*predicates, **constraints)
.collect(optimizations=QueryOptFlags._eager())
)
def remove(
self,
*predicates: (
IntoExprColumn
| Iterable[IntoExprColumn]
| bool
| list[bool]
| np.ndarray[Any, Any]
),
**constraints: Any,
) -> DataFrame:
"""
Remove rows, dropping those that match the given predicate expression(s).
The original order of the remaining rows is preserved.
Rows where the filter predicate does not evaluate to True are retained
(this includes rows where the predicate evaluates as `null`).
Parameters
----------
predicates
Expression that evaluates to a boolean Series.
constraints
Column filters; use `name = value` to filter columns using the supplied
value. Each constraint behaves the same as `pl.col(name).eq(value)`,
and is implicitly joined with the other filter conditions using `&`.
Notes
-----
If you are transitioning from Pandas, and performing filter operations based on
the comparison of two or more columns, please note that in Polars any comparison
involving `null` values will result in a `null` result, *not* boolean True or
False. As a result, these rows will not be removed. Ensure that null values
are handled appropriately to avoid unexpected behaviour (see examples below).
See Also
--------
filter
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [2, 3, None, 4, 0],
... "bar": [5, 6, None, None, 0],
... "ham": ["a", "b", None, "c", "d"],
... }
... )
Remove rows matching a condition:
>>> df.remove(pl.col("bar") >= 5)
shape: (3, 3)
┌──────┬──────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞══════╪══════╪══════╡
│ null ┆ null ┆ null │
│ 4 ┆ null ┆ c │
│ 0 ┆ 0 ┆ d │
└──────┴──────┴──────┘
Discard rows based on multiple conditions, combined with and/or operators:
>>> df.remove(
... (pl.col("foo") >= 0) & (pl.col("bar") >= 0),
... )
shape: (2, 3)
┌──────┬──────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞══════╪══════╪══════╡
│ null ┆ null ┆ null │
│ 4 ┆ null ┆ c │
└──────┴──────┴──────┘
>>> df.remove(
... (pl.col("foo") >= 0) | (pl.col("bar") >= 0),
... )
shape: (1, 3)
┌──────┬──────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞══════╪══════╪══════╡
│ null ┆ null ┆ null │
└──────┴──────┴──────┘
Provide multiple constraints using `*args` syntax:
>>> df.remove(
... pl.col("ham").is_not_null(),
... pl.col("bar") >= 0,
... )
shape: (2, 3)
┌──────┬──────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞══════╪══════╪══════╡
│ null ┆ null ┆ null │
│ 4 ┆ null ┆ c │
└──────┴──────┴──────┘
Provide constraints(s) using `**kwargs` syntax:
>>> df.remove(foo=0, bar=0)
shape: (4, 3)
┌──────┬──────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞══════╪══════╪══════╡
│ 2 ┆ 5 ┆ a │
│ 3 ┆ 6 ┆ b │
│ null ┆ null ┆ null │
│ 4 ┆ null ┆ c │
└──────┴──────┴──────┘
Remove rows by comparing two columns against each other:
>>> df.remove(
... pl.col("foo").ne_missing(pl.col("bar")),
... )
shape: (2, 3)
┌──────┬──────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞══════╪══════╪══════╡
│ null ┆ null ┆ null │
│ 0 ┆ 0 ┆ d │
└──────┴──────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.remove(*predicates, **constraints)
.collect(optimizations=QueryOptFlags._eager())
)
@overload
def glimpse(
self,
*,
max_items_per_column: int = ...,
max_colname_length: int = ...,
return_type: None = ...,
) -> None: ...
@overload
def glimpse(
self,
*,
max_items_per_column: int = ...,
max_colname_length: int = ...,
return_type: Literal["string"],
) -> str: ...
@overload
def glimpse(
self,
*,
max_items_per_column: int = ...,
max_colname_length: int = ...,
return_type: Literal["frame", "self"],
) -> DataFrame: ...
@deprecate_renamed_parameter("return_as_string", "return_type", version="1.35.0")
def glimpse(
self,
*,
max_items_per_column: int = 10,
max_colname_length: int = 50,
return_type: Literal["frame", "self", "string"] | None = None,
) -> str | DataFrame | None:
"""
Return a dense preview of the DataFrame.
The formatting shows one line per column so that wide dataframes display
cleanly. Each line shows the column name, the data type, and the first
few values.
.. versionchanged:: 1.35.0
The `return_as_string` parameter was renamed `return_type` and now accepts
string values `'string'` and `'frame'` instead of boolean True or False.
Parameters
----------
max_items_per_column
Maximum number of items to show per column.
max_colname_length
Maximum length of the displayed column names; values that exceed
this value are truncated with a trailing ellipsis.
return_type
Modify the return format:
- `None` (default): Print the glimpse output to stdout, returning `None`.
- `"self"`: Print the glimpse output to stdout, returning the *original* frame.
- `"frame"`: Return the glimpse output as a new DataFrame.
- `"string"`: Return the glimpse output as a string.
See Also
--------
describe, head, tail
Examples
--------
>>> from datetime import date
>>> df = pl.DataFrame(
... {
... "a": [1.0, 2.8, 3.0],
... "b": [4, 5, None],
... "c": [True, False, True],
... "d": [None, "b", "c"],
... "e": ["usd", "eur", None],
... "f": [date(2020, 1, 1), date(2021, 1, 2), date(2022, 1, 1)],
... }
... )
Print glimpse-formatted output to stdout, returning `None`:
>>> res = df.glimpse()
Rows: 3
Columns: 6
$ a <f64> 1.0, 2.8, 3.0
$ b <i64> 4, 5, null
$ c <bool> True, False, True
$ d <str> null, 'b', 'c'
$ e <str> 'usd', 'eur', null
$ f <date> 2020-01-01, 2021-01-02, 2022-01-01
>>> res is None
True
Return the glimpse output as a string:
>>> res = df.glimpse(return_type="string")
>>> isinstance(res, str)
True
Return the glimpse output as a DataFrame:
>>> df.glimpse(return_type="frame")
shape: (6, 3)
┌────────┬───────┬─────────────────────────────────┐
│ column ┆ dtype ┆ values │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ list[str] │
╞════════╪═══════╪═════════════════════════════════╡
│ a ┆ f64 ┆ ["1.0", "2.8", "3.0"] │
│ b ┆ i64 ┆ ["4", "5", null] │
│ c ┆ bool ┆ ["True", "False", "True"] │
│ d ┆ str ┆ [null, "'b'", "'c'"] │
│ e ┆ str ┆ ["'usd'", "'eur'", null] │
│ f ┆ date ┆ ["2020-01-01", "2021-01-02", "… │
└────────┴───────┴─────────────────────────────────┘
Print glimpse-formatted output to stdout, returning the *original* frame:
>>> res = df.glimpse(return_type="self")
Rows: 3
Columns: 6
$ a <f64> 1.0, 2.8, 3.0
$ b <i64> 4, 5, null
$ c <bool> True, False, True
$ d <str> null, 'b', 'c'
$ e <str> 'usd', 'eur', null
$ f <date> 2020-01-01, 2021-01-02, 2022-01-01
>>> res
shape: (3, 6)
┌─────┬──────┬───────┬──────┬──────┬────────────┐
│ a ┆ b ┆ c ┆ d ┆ e ┆ f │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ i64 ┆ bool ┆ str ┆ str ┆ date │
╞═════╪══════╪═══════╪══════╪══════╪════════════╡
│ 1.0 ┆ 4 ┆ true ┆ null ┆ usd ┆ 2020-01-01 │
│ 2.8 ┆ 5 ┆ false ┆ b ┆ eur ┆ 2021-01-02 │
│ 3.0 ┆ null ┆ true ┆ c ┆ null ┆ 2022-01-01 │
└─────┴──────┴───────┴──────┴──────┴────────────┘
""" # noqa: W505
# handle boolean value from now-deprecated `return_as_string` parameter
if isinstance(return_type, bool) or return_type is None: # type: ignore[redundant-expr]
return_type = "string" if return_type else None # type: ignore[redundant-expr]
return_frame = False
else:
return_frame = return_type == "frame"
if not return_frame and return_type not in ("self", "string"):
msg = f"invalid `return_type`; found {return_type!r}, expected one of 'string', 'frame', 'self', or None"
raise ValueError(msg)
# always print at most this number of values (mainly ensures that
# we do not cast long arrays to strings, which would be slow)
max_n_values = min(max_items_per_column, self.height)
schema = self.schema
def _column_to_row_output(
col_name: str, dtype: PolarsDataType
) -> tuple[str, str, list[str | None]]:
fn = repr if schema[col_name] == String else str
values = self[:max_n_values, col_name].to_list()
if len(col_name) > max_colname_length:
col_name = col_name[: (max_colname_length - 1)] + "…"
dtype_str = _dtype_str_repr(dtype)
if not return_frame:
dtype_str = f"<{dtype_str}>"
return (
col_name,
dtype_str,
[(fn(v) if v is not None else v) for v in values],
)
data = [_column_to_row_output(s, dtype) for s, dtype in self.schema.items()]
# output one row per column
if return_frame:
return pl.DataFrame(
data=data,
orient="row",
schema={"column": String, "dtype": String, "values": List(String)},
)
else:
# determine column layout widths
max_col_name = max((len(col_name) for col_name, _, _ in data))
max_col_dtype = max((len(dtype_str) for _, dtype_str, _ in data))
# write column headers and data to the buffer
output = StringIO()
output.write(f"Rows: {self.height}\nColumns: {self.width}\n")
for col_name, dtype_str, values in data:
val_str = ", ".join(("null" if v is None else v) for v in values)
output.write(
f"$ {col_name:<{max_col_name}} {dtype_str:>{max_col_dtype}} {val_str}\n"
)
s = output.getvalue()
if return_type == "string":
return s
print(s, end=None)
if return_type == "self":
return self
return None
def describe(
self,
percentiles: Sequence[float] | float | None = (0.25, 0.50, 0.75),
*,
interpolation: QuantileMethod = "nearest",
) -> DataFrame:
"""
Summary statistics for a DataFrame.
Parameters
----------
percentiles
One or more percentiles to include in the summary statistics.
All values must be in the range `[0, 1]`.
interpolation : {'nearest', 'higher', 'lower', 'midpoint', 'linear', 'equiprobable'}
Interpolation method used when calculating percentiles.
Notes
-----
The median is included by default as the 50% percentile.
Warnings
--------
We do not guarantee the output of `describe` to be stable. It will show
statistics that we deem informative, and may be updated in the future.
Using `describe` programmatically (versus interactive exploration) is
not recommended for this reason.
See Also
--------
glimpse
Examples
--------
>>> from datetime import date, time
>>> df = pl.DataFrame(
... {
... "float": [1.0, 2.8, 3.0],
... "int": [40, 50, None],
... "bool": [True, False, True],
... "str": ["zz", "xx", "yy"],
... "date": [date(2020, 1, 1), date(2021, 7, 5), date(2022, 12, 31)],
... "time": [time(10, 20, 30), time(14, 45, 50), time(23, 15, 10)],
... }
... )
Show default frame statistics:
>>> df.describe()
shape: (9, 7)
┌────────────┬──────────┬──────────┬──────────┬──────┬─────────────────────┬──────────┐
│ statistic ┆ float ┆ int ┆ bool ┆ str ┆ date ┆ time │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ str ┆ str ┆ str │
╞════════════╪══════════╪══════════╪══════════╪══════╪═════════════════════╪══════════╡
│ count ┆ 3.0 ┆ 2.0 ┆ 3.0 ┆ 3 ┆ 3 ┆ 3 │
│ null_count ┆ 0.0 ┆ 1.0 ┆ 0.0 ┆ 0 ┆ 0 ┆ 0 │
│ mean ┆ 2.266667 ┆ 45.0 ┆ 0.666667 ┆ null ┆ 2021-07-02 16:00:00 ┆ 16:07:10 │
│ std ┆ 1.101514 ┆ 7.071068 ┆ null ┆ null ┆ null ┆ null │
│ min ┆ 1.0 ┆ 40.0 ┆ 0.0 ┆ xx ┆ 2020-01-01 ┆ 10:20:30 │
│ 25% ┆ 2.8 ┆ 40.0 ┆ null ┆ null ┆ 2021-07-05 ┆ 14:45:50 │
│ 50% ┆ 2.8 ┆ 50.0 ┆ null ┆ null ┆ 2021-07-05 ┆ 14:45:50 │
│ 75% ┆ 3.0 ┆ 50.0 ┆ null ┆ null ┆ 2022-12-31 ┆ 23:15:10 │
│ max ┆ 3.0 ┆ 50.0 ┆ 1.0 ┆ zz ┆ 2022-12-31 ┆ 23:15:10 │
└────────────┴──────────┴──────────┴──────────┴──────┴─────────────────────┴──────────┘
Customize which percentiles are displayed, applying linear interpolation:
>>> with pl.Config(tbl_rows=12):
... df.describe(
... percentiles=[0.1, 0.3, 0.5, 0.7, 0.9],
... interpolation="linear",
... )
shape: (11, 7)
┌────────────┬──────────┬──────────┬──────────┬──────┬─────────────────────┬──────────┐
│ statistic ┆ float ┆ int ┆ bool ┆ str ┆ date ┆ time │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ str ┆ str ┆ str │
╞════════════╪══════════╪══════════╪══════════╪══════╪═════════════════════╪══════════╡
│ count ┆ 3.0 ┆ 2.0 ┆ 3.0 ┆ 3 ┆ 3 ┆ 3 │
│ null_count ┆ 0.0 ┆ 1.0 ┆ 0.0 ┆ 0 ┆ 0 ┆ 0 │
│ mean ┆ 2.266667 ┆ 45.0 ┆ 0.666667 ┆ null ┆ 2021-07-02 16:00:00 ┆ 16:07:10 │
│ std ┆ 1.101514 ┆ 7.071068 ┆ null ┆ null ┆ null ┆ null │
│ min ┆ 1.0 ┆ 40.0 ┆ 0.0 ┆ xx ┆ 2020-01-01 ┆ 10:20:30 │
│ 10% ┆ 1.36 ┆ 41.0 ┆ null ┆ null ┆ 2020-04-20 ┆ 11:13:34 │
│ 30% ┆ 2.08 ┆ 43.0 ┆ null ┆ null ┆ 2020-11-26 ┆ 12:59:42 │
│ 50% ┆ 2.8 ┆ 45.0 ┆ null ┆ null ┆ 2021-07-05 ┆ 14:45:50 │
│ 70% ┆ 2.88 ┆ 47.0 ┆ null ┆ null ┆ 2022-02-07 ┆ 18:09:34 │
│ 90% ┆ 2.96 ┆ 49.0 ┆ null ┆ null ┆ 2022-09-13 ┆ 21:33:18 │
│ max ┆ 3.0 ┆ 50.0 ┆ 1.0 ┆ zz ┆ 2022-12-31 ┆ 23:15:10 │
└────────────┴──────────┴──────────┴──────────┴──────┴─────────────────────┴──────────┘
""" # noqa: W505
if not self.columns:
msg = "cannot describe a DataFrame that has no columns"
raise TypeError(msg)
return self.lazy().describe(
percentiles=percentiles, interpolation=interpolation
)
def get_column_index(self, name: str) -> int:
"""
Find the index of a column by name.
Parameters
----------
name
Name of the column to find.
Examples
--------
>>> df = pl.DataFrame(
... {"foo": [1, 2, 3], "bar": [6, 7, 8], "ham": ["a", "b", "c"]}
... )
>>> df.get_column_index("ham")
2
>>> df.get_column_index("sandwich") # doctest: +SKIP
ColumnNotFoundError: sandwich
"""
return self._df.get_column_index(name)
def replace_column(self, index: int, column: Series) -> DataFrame:
"""
Replace a column at an index location.
This operation is in place.
Parameters
----------
index
Column index.
column
Series that will replace the column.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> s = pl.Series("apple", [10, 20, 30])
>>> df.replace_column(0, s)
shape: (3, 3)
┌───────┬─────┬─────┐
│ apple ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═══════╪═════╪═════╡
│ 10 ┆ 6 ┆ a │
│ 20 ┆ 7 ┆ b │
│ 30 ┆ 8 ┆ c │
└───────┴─────┴─────┘
"""
if index < 0:
index = self.width + index
self._df.replace_column(index, column._s)
return self
def sort(
self,
by: IntoExpr | Iterable[IntoExpr],
*more_by: IntoExpr,
descending: bool | Sequence[bool] = False,
nulls_last: bool | Sequence[bool] = False,
multithreaded: bool = True,
maintain_order: bool = False,
) -> DataFrame:
"""
Sort the dataframe by the given columns.
Parameters
----------
by
Column(s) to sort by. Accepts expression input, including selectors. Strings
are parsed as column names.
*more_by
Additional columns to sort by, specified as positional arguments.
descending
Sort in descending order. When sorting by multiple columns, can be specified
per column by passing a sequence of booleans.
nulls_last
Place null values last; can specify a single boolean applying to all columns
or a sequence of booleans for per-column control.
multithreaded
Sort using multiple threads.
maintain_order
Whether the order should be maintained if elements are equal.
Examples
--------
Pass a single column name to sort by that column.
>>> df = pl.DataFrame(
... {
... "a": [1, 2, None],
... "b": [6.0, 5.0, 4.0],
... "c": ["a", "c", "b"],
... }
... )
>>> df.sort("a")
shape: (3, 3)
┌──────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞══════╪═════╪═════╡
│ null ┆ 4.0 ┆ b │
│ 1 ┆ 6.0 ┆ a │
│ 2 ┆ 5.0 ┆ c │
└──────┴─────┴─────┘
Sorting by expressions is also supported.
>>> df.sort(pl.col("a") + pl.col("b") * 2, nulls_last=True)
shape: (3, 3)
┌──────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞══════╪═════╪═════╡
│ 2 ┆ 5.0 ┆ c │
│ 1 ┆ 6.0 ┆ a │
│ null ┆ 4.0 ┆ b │
└──────┴─────┴─────┘
Sort by multiple columns by passing a list of columns.
>>> df.sort(["c", "a"], descending=True)
shape: (3, 3)
┌──────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞══════╪═════╪═════╡
│ 2 ┆ 5.0 ┆ c │
│ null ┆ 4.0 ┆ b │
│ 1 ┆ 6.0 ┆ a │
└──────┴─────┴─────┘
Or use positional arguments to sort by multiple columns in the same way.
>>> df.sort("c", "a", descending=[False, True])
shape: (3, 3)
┌──────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞══════╪═════╪═════╡
│ 1 ┆ 6.0 ┆ a │
│ null ┆ 4.0 ┆ b │
│ 2 ┆ 5.0 ┆ c │
└──────┴─────┴─────┘
"""
from polars.lazyframe import QueryOptFlags
return (
self.lazy()
.sort(
by,
*more_by,
descending=descending,
nulls_last=nulls_last,
multithreaded=multithreaded,
maintain_order=maintain_order,
)
.collect(optimizations=QueryOptFlags._eager())
)
def sql(self, query: str, *, table_name: str = "self") -> DataFrame:
"""
Execute a SQL query against the DataFrame.
.. versionadded:: 0.20.24
.. warning::
This functionality is considered **unstable**, although it is close to
being considered stable. It may be changed at any point without it being
considered a breaking change.
Parameters
----------
query
SQL query to execute.
table_name
Optionally provide an explicit name for the table that represents the
calling frame (defaults to "self").
Notes
-----
* The calling frame is automatically registered as a table in the SQL context
under the name "self". If you want access to the DataFrames and LazyFrames
found in the current globals, use the top-level :meth:`pl.sql <polars.sql>`.
* More control over registration and execution behaviour is available by
using the :class:`SQLContext` object.
* The SQL query executes in lazy mode before being collected and returned
as a DataFrame.
See Also
--------
SQLContext
Examples
--------
>>> from datetime import date
>>> df1 = pl.DataFrame(
... {
... "a": [1, 2, 3],
... "b": ["zz", "yy", "xx"],
... "c": [date(1999, 12, 31), date(2010, 10, 10), date(2077, 8, 8)],
... }
... )
Query the DataFrame using SQL:
>>> df1.sql("SELECT c, b FROM self WHERE a > 1")
shape: (2, 2)
┌────────────┬─────┐
│ c ┆ b │
│ --- ┆ --- │
│ date ┆ str │
╞════════════╪═════╡
│ 2010-10-10 ┆ yy │
│ 2077-08-08 ┆ xx │
└────────────┴─────┘
Apply transformations to a DataFrame using SQL, aliasing "self" to "frame".
>>> df1.sql(
... query='''
... SELECT
... a,
... (a % 2 == 0) AS a_is_even,
... CONCAT_WS(':', b, b) AS b_b,
... EXTRACT(year FROM c) AS year,
... 0::float4 AS "zero",
... FROM frame
... ''',
... table_name="frame",
... )
shape: (3, 5)
┌─────┬───────────┬───────┬──────┬──────┐
│ a ┆ a_is_even ┆ b_b ┆ year ┆ zero │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ bool ┆ str ┆ i32 ┆ f32 │
╞═════╪═══════════╪═══════╪══════╪══════╡
│ 1 ┆ false ┆ zz:zz ┆ 1999 ┆ 0.0 │
│ 2 ┆ true ┆ yy:yy ┆ 2010 ┆ 0.0 │
│ 3 ┆ false ┆ xx:xx ┆ 2077 ┆ 0.0 │
└─────┴───────────┴───────┴──────┴──────┘
"""
from polars.sql import SQLContext
issue_unstable_warning(
"`sql` is considered **unstable** (although it is close to being considered stable)."
)
with SQLContext(register_globals=False, eager=True) as ctx:
name = table_name if table_name else "self"
ctx.register(name=name, frame=self)
return ctx.execute(query)
@deprecate_renamed_parameter("descending", "reverse", version="1.0.0")
def top_k(
self,
k: int,
*,
by: IntoExpr | Iterable[IntoExpr],
reverse: bool | Sequence[bool] = False,
) -> DataFrame:
"""
Return the `k` largest rows.
Non-null elements are always preferred over null elements, regardless of
the value of `reverse`. The output is not guaranteed to be in any
particular order, call :func:`sort` after this function if you wish the
output to be sorted.
.. versionchanged:: 1.0.0
The `descending` parameter was renamed `reverse`.
Parameters
----------
k
Number of rows to return.
by
Column(s) used to determine the top rows.
Accepts expression input. Strings are parsed as column names.
reverse
Consider the `k` smallest elements of the `by` column(s) (instead of the `k`
largest). This can be specified per column by passing a sequence of
booleans.
See Also
--------
bottom_k
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": ["a", "b", "a", "b", "b", "c"],
... "b": [2, 1, 1, 3, 2, 1],
... }
... )
Get the rows which contain the 4 largest values in column b.
>>> df.top_k(4, by="b")
shape: (4, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ b ┆ 3 │
│ a ┆ 2 │
│ b ┆ 2 │
│ b ┆ 1 │
└─────┴─────┘
Get the rows which contain the 4 largest values when sorting on column b and a.
>>> df.top_k(4, by=["b", "a"])
shape: (4, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ b ┆ 3 │
│ b ┆ 2 │
│ a ┆ 2 │
│ c ┆ 1 │
└─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.top_k(k, by=by, reverse=reverse)
.collect(
optimizations=QueryOptFlags(
projection_pushdown=False,
predicate_pushdown=False,
comm_subplan_elim=False,
slice_pushdown=True,
)
)
)
@deprecate_renamed_parameter("descending", "reverse", version="1.0.0")
def bottom_k(
self,
k: int,
*,
by: IntoExpr | Iterable[IntoExpr],
reverse: bool | Sequence[bool] = False,
) -> DataFrame:
"""
Return the `k` smallest rows.
Non-null elements are always preferred over null elements, regardless of
the value of `reverse`. The output is not guaranteed to be in any
particular order, call :func:`sort` after this function if you wish the
output to be sorted.
.. versionchanged:: 1.0.0
The `descending` parameter was renamed `reverse`.
Parameters
----------
k
Number of rows to return.
by
Column(s) used to determine the bottom rows.
Accepts expression input. Strings are parsed as column names.
reverse
Consider the `k` largest elements of the `by` column(s) (instead of the `k`
smallest). This can be specified per column by passing a sequence of
booleans.
See Also
--------
top_k
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": ["a", "b", "a", "b", "b", "c"],
... "b": [2, 1, 1, 3, 2, 1],
... }
... )
Get the rows which contain the 4 smallest values in column b.
>>> df.bottom_k(4, by="b")
shape: (4, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ b ┆ 1 │
│ a ┆ 1 │
│ c ┆ 1 │
│ a ┆ 2 │
└─────┴─────┘
Get the rows which contain the 4 smallest values when sorting on column a and b.
>>> df.bottom_k(4, by=["a", "b"])
shape: (4, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ a ┆ 1 │
│ a ┆ 2 │
│ b ┆ 1 │
│ b ┆ 2 │
└─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.bottom_k(k, by=by, reverse=reverse)
.collect(
optimizations=QueryOptFlags(
projection_pushdown=False,
predicate_pushdown=False,
comm_subplan_elim=False,
slice_pushdown=True,
)
)
)
def equals(self, other: DataFrame, *, null_equal: bool = True) -> bool:
"""
Check whether the DataFrame is equal to another DataFrame.
Parameters
----------
other
DataFrame to compare with.
null_equal
Consider null values as equal.
See Also
--------
polars.testing.assert_frame_equal
Examples
--------
>>> df1 = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df2 = pl.DataFrame(
... {
... "foo": [3, 2, 1],
... "bar": [8.0, 7.0, 6.0],
... "ham": ["c", "b", "a"],
... }
... )
>>> df1.equals(df1)
True
>>> df1.equals(df2)
False
"""
require_same_type(self, other)
return self._df.equals(other._df, null_equal=null_equal)
def slice(self, offset: int, length: int | None = None) -> DataFrame:
"""
Get a slice of this DataFrame.
Parameters
----------
offset
Start index. Negative indexing is supported.
length
Length of the slice. If set to `None`, all rows starting at the offset
will be selected.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.slice(1, 2)
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞═════╪═════╪═════╡
│ 2 ┆ 7.0 ┆ b │
│ 3 ┆ 8.0 ┆ c │
└─────┴─────┴─────┘
"""
if (length is not None) and length < 0:
length = self.height - offset + length
return self._from_pydf(self._df.slice(offset, length))
def head(self, n: int = 5) -> DataFrame:
"""
Get the first `n` rows.
Parameters
----------
n
Number of rows to return. If a negative value is passed, return all rows
except the last `abs(n)`.
See Also
--------
tail, glimpse, slice
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> df.head(3)
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└─────┴─────┴─────┘
Pass a negative value to get all rows `except` the last `abs(n)`.
>>> df.head(-3)
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
└─────┴─────┴─────┘
"""
if n < 0:
n = max(0, self.height + n)
return self._from_pydf(self._df.head(n))
def tail(self, n: int = 5) -> DataFrame:
"""
Get the last `n` rows.
Parameters
----------
n
Number of rows to return. If a negative value is passed, return all rows
except the first `abs(n)`.
See Also
--------
head, slice
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> df.tail(3)
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 3 ┆ 8 ┆ c │
│ 4 ┆ 9 ┆ d │
│ 5 ┆ 10 ┆ e │
└─────┴─────┴─────┘
Pass a negative value to get all rows `except` the first `abs(n)`.
>>> df.tail(-3)
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 4 ┆ 9 ┆ d │
│ 5 ┆ 10 ┆ e │
└─────┴─────┴─────┘
"""
if n < 0:
n = max(0, self.height + n)
return self._from_pydf(self._df.tail(n))
def limit(self, n: int = 5) -> DataFrame:
"""
Get the first `n` rows.
Alias for :func:`DataFrame.head`.
Parameters
----------
n
Number of rows to return. If a negative value is passed, return all rows
except the last `abs(n)`.
See Also
--------
head
Examples
--------
Get the first 3 rows of a DataFrame.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 4, 5],
... "bar": [6, 7, 8, 9, 10],
... "ham": ["a", "b", "c", "d", "e"],
... }
... )
>>> df.limit(3)
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└─────┴─────┴─────┘
"""
return self.head(n)
def drop_nans(
self,
subset: ColumnNameOrSelector | Collection[ColumnNameOrSelector] | None = None,
) -> DataFrame:
"""
Drop all rows that contain one or more NaN values.
The original order of the remaining rows is preserved.
Parameters
----------
subset
Column name(s) for which NaN values are considered; if set to `None`
(default), use all columns (note that only floating-point columns
can contain NaNs).
See Also
--------
drop_nulls
Notes
-----
A NaN value is not the same as a null value.
To drop null values, use :func:`drop_nulls`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [-20.5, float("nan"), 80.0],
... "bar": [float("nan"), 110.0, 25.5],
... "ham": ["xxx", "yyy", None],
... }
... )
The default behavior of this method is to drop rows where any single
value in the row is NaN:
>>> df.drop_nans()
shape: (1, 3)
┌──────┬──────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str │
╞══════╪══════╪══════╡
│ 80.0 ┆ 25.5 ┆ null │
└──────┴──────┴──────┘
This behaviour can be constrained to consider only a subset of columns, as
defined by name, or with a selector. For example, dropping rows only if
there is a NaN in the "bar" column:
>>> df.drop_nans(subset=["bar"])
shape: (2, 3)
┌──────┬───────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str │
╞══════╪═══════╪══════╡
│ NaN ┆ 110.0 ┆ yyy │
│ 80.0 ┆ 25.5 ┆ null │
└──────┴───────┴──────┘
Dropping a row only if *all* values are NaN requires a different formulation:
>>> df = pl.DataFrame(
... {
... "a": [float("nan"), float("nan"), float("nan"), float("nan")],
... "b": [10.0, 2.5, float("nan"), 5.25],
... "c": [65.75, float("nan"), float("nan"), 10.5],
... }
... )
>>> df.filter(~pl.all_horizontal(pl.all().is_nan()))
shape: (3, 3)
┌─────┬──────┬───────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 │
╞═════╪══════╪═══════╡
│ NaN ┆ 10.0 ┆ 65.75 │
│ NaN ┆ 2.5 ┆ NaN │
│ NaN ┆ 5.25 ┆ 10.5 │
└─────┴──────┴───────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy().drop_nans(subset).collect(optimizations=QueryOptFlags._eager())
)
def drop_nulls(
self,
subset: ColumnNameOrSelector | Collection[ColumnNameOrSelector] | None = None,
) -> DataFrame:
"""
Drop all rows that contain one or more null values.
The original order of the remaining rows is preserved.
Parameters
----------
subset
Column name(s) for which null values are considered.
If set to `None` (default), use all columns.
See Also
--------
drop_nans
Notes
-----
A null value is not the same as a NaN value.
To drop NaN values, use :func:`drop_nans`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, None, 8],
... "ham": ["a", "b", None],
... }
... )
The default behavior of this method is to drop rows where any single
value of the row is null.
>>> df.drop_nulls()
shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
└─────┴─────┴─────┘
This behaviour can be constrained to consider only a subset of columns, as
defined by name or with a selector. For example, dropping rows if there is
a null in any of the integer columns:
>>> import polars.selectors as cs
>>> df.drop_nulls(subset=cs.integer())
shape: (2, 3)
┌─────┬─────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪══════╡
│ 1 ┆ 6 ┆ a │
│ 3 ┆ 8 ┆ null │
└─────┴─────┴──────┘
Below are some additional examples that show how to drop null
values based on other conditions.
>>> df = pl.DataFrame(
... {
... "a": [None, None, None, None],
... "b": [1, 2, None, 1],
... "c": [1, None, None, 1],
... }
... )
>>> df
shape: (4, 3)
┌──────┬──────┬──────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ null ┆ i64 ┆ i64 │
╞══════╪══════╪══════╡
│ null ┆ 1 ┆ 1 │
│ null ┆ 2 ┆ null │
│ null ┆ null ┆ null │
│ null ┆ 1 ┆ 1 │
└──────┴──────┴──────┘
Drop a row only if all values are null:
>>> df.filter(~pl.all_horizontal(pl.all().is_null()))
shape: (3, 3)
┌──────┬─────┬──────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ null ┆ i64 ┆ i64 │
╞══════╪═════╪══════╡
│ null ┆ 1 ┆ 1 │
│ null ┆ 2 ┆ null │
│ null ┆ 1 ┆ 1 │
└──────┴─────┴──────┘
Drop a column if all values are null:
>>> df[[s.name for s in df if not (s.null_count() == df.height)]]
shape: (4, 2)
┌──────┬──────┐
│ b ┆ c │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪══════╡
│ 1 ┆ 1 │
│ 2 ┆ null │
│ null ┆ null │
│ 1 ┆ 1 │
└──────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy().drop_nulls(subset).collect(optimizations=QueryOptFlags._eager())
)
def pipe(
self,
function: Callable[Concatenate[DataFrame, P], T],
*args: P.args,
**kwargs: P.kwargs,
) -> T:
"""
Offers a structured way to apply a sequence of user-defined functions (UDFs).
Parameters
----------
function
Callable; will receive the frame as the first parameter,
followed by any given args/kwargs.
*args
Arguments to pass to the UDF.
**kwargs
Keyword arguments to pass to the UDF.
Notes
-----
It is recommended to use LazyFrame when piping operations, in order
to fully take advantage of query optimization and parallelization.
See :meth:`df.lazy() <polars.DataFrame.lazy>`.
Examples
--------
>>> def cast_str_to_int(data, col_name):
... return data.with_columns(pl.col(col_name).cast(pl.Int64))
>>> df = pl.DataFrame({"a": [1, 2, 3, 4], "b": ["10", "20", "30", "40"]})
>>> df.pipe(cast_str_to_int, col_name="b")
shape: (4, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 10 │
│ 2 ┆ 20 │
│ 3 ┆ 30 │
│ 4 ┆ 40 │
└─────┴─────┘
>>> df = pl.DataFrame({"b": [1, 2], "a": [3, 4]})
>>> df
shape: (2, 2)
┌─────┬─────┐
│ b ┆ a │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 3 │
│ 2 ┆ 4 │
└─────┴─────┘
>>> df.pipe(lambda tdf: tdf.select(sorted(tdf.columns)))
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 3 ┆ 1 │
│ 4 ┆ 2 │
└─────┴─────┘
"""
return function(self, *args, **kwargs)
def map_columns(
self,
column_names: str | Sequence[str] | pl.Selector,
function: Callable[[Series], Series],
*args: P.args,
**kwargs: P.kwargs,
) -> DataFrame:
"""
Apply eager functions to columns of a DataFrame.
Users should always prefer :meth:`with_columns` unless they are using
expressions that are only possible on `Series` and not on `Expr`. This is almost
never the case, except for a very select few functions that cannot know the
output datatype without looking at the data.
Parameters
----------
column_names
The columns to apply the UDF to.
function
Callable; will receive a column series as the first parameter,
followed by any given args/kwargs.
*args
Arguments to pass to the UDF.
**kwargs
Keyword arguments to pass to the UDF.
Examples
--------
>>> df = pl.DataFrame({"a": [1, 2, 3, 4], "b": ["10", "20", "30", "40"]})
>>> df.map_columns("a", lambda s: s.shrink_dtype())
shape: (4, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i8 ┆ str │
╞═════╪═════╡
│ 1 ┆ 10 │
│ 2 ┆ 20 │
│ 3 ┆ 30 │
│ 4 ┆ 40 │
└─────┴─────┘
>>> df = pl.DataFrame(
... {
... "a": ['{"x":"a"}', None, '{"x":"b"}', None],
... "b": ['{"a":1, "b": true}', None, '{"a":2, "b": false}', None],
... }
... )
>>> df.map_columns(["a", "b"], lambda s: s.str.json_decode())
shape: (4, 2)
┌───────────┬───────────┐
│ a ┆ b │
│ --- ┆ --- │
│ struct[1] ┆ struct[2] │
╞═══════════╪═══════════╡
│ {"a"} ┆ {1,true} │
│ null ┆ null │
│ {"b"} ┆ {2,false} │
│ null ┆ null │
└───────────┴───────────┘
>>> import polars.selectors as cs
>>> df.map_columns(cs.all(), lambda s: s.str.json_decode())
shape: (4, 2)
┌───────────┬───────────┐
│ a ┆ b │
│ --- ┆ --- │
│ struct[1] ┆ struct[2] │
╞═══════════╪═══════════╡
│ {"a"} ┆ {1,true} │
│ null ┆ null │
│ {"b"} ┆ {2,false} │
│ null ┆ null │
└───────────┴───────────┘
See Also
--------
with_columns
"""
c_names: list[str]
if isinstance(column_names, (pl.Selector, pl.Expr)):
from polars.selectors import expand_selector
c_names = list(expand_selector(self, column_names))
elif isinstance(column_names, str):
c_names = [column_names]
else:
c_names = list(column_names)
return self.with_columns(
**{c: function(self[c], *args, **kwargs) for c in c_names}
)
def with_row_index(self, name: str = "index", offset: int = 0) -> DataFrame:
"""
Add a row index as the first column in the DataFrame.
Parameters
----------
name
Name of the index column.
offset
Start the index at this offset. Cannot be negative.
Notes
-----
The resulting column does not have any special properties. It is a regular
column of type `UInt32` (or `UInt64` in `polars[rt64]`).
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 3, 5],
... "b": [2, 4, 6],
... }
... )
>>> df.with_row_index()
shape: (3, 3)
┌───────┬─────┬─────┐
│ index ┆ a ┆ b │
│ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i64 │
╞═══════╪═════╪═════╡
│ 0 ┆ 1 ┆ 2 │
│ 1 ┆ 3 ┆ 4 │
│ 2 ┆ 5 ┆ 6 │
└───────┴─────┴─────┘
>>> df.with_row_index("id", offset=1000)
shape: (3, 3)
┌──────┬─────┬─────┐
│ id ┆ a ┆ b │
│ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i64 │
╞══════╪═════╪═════╡
│ 1000 ┆ 1 ┆ 2 │
│ 1001 ┆ 3 ┆ 4 │
│ 1002 ┆ 5 ┆ 6 │
└──────┴─────┴─────┘
An index column can also be created using the expressions :func:`int_range`
and :func:`len`.
>>> df.select(
... pl.int_range(pl.len(), dtype=pl.UInt32).alias("index"),
... pl.all(),
... )
shape: (3, 3)
┌───────┬─────┬─────┐
│ index ┆ a ┆ b │
│ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i64 │
╞═══════╪═════╪═════╡
│ 0 ┆ 1 ┆ 2 │
│ 1 ┆ 3 ┆ 4 │
│ 2 ┆ 5 ┆ 6 │
└───────┴─────┴─────┘
"""
try:
return self._from_pydf(self._df.with_row_index(name, offset))
except OverflowError:
issue = "negative" if offset < 0 else "greater than the maximum index value"
msg = f"`offset` input for `with_row_index` cannot be {issue}, got {offset}"
raise ValueError(msg) from None
@deprecated(
"`DataFrame.with_row_count` is deprecated; use `with_row_index` instead."
" Note that the default column name has changed from 'row_nr' to 'index'."
)
def with_row_count(self, name: str = "row_nr", offset: int = 0) -> DataFrame:
"""
Add a column at index 0 that counts the rows.
.. deprecated:: 0.20.4
Use the :meth:`with_row_index` method instead.
Note that the default column name has changed from 'row_nr' to 'index'.
Parameters
----------
name
Name of the column to add.
offset
Start the row count at this offset. Default = 0
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 3, 5],
... "b": [2, 4, 6],
... }
... )
>>> df.with_row_count() # doctest: +SKIP
shape: (3, 3)
┌────────┬─────┬─────┐
│ row_nr ┆ a ┆ b │
│ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i64 │
╞════════╪═════╪═════╡
│ 0 ┆ 1 ┆ 2 │
│ 1 ┆ 3 ┆ 4 │
│ 2 ┆ 5 ┆ 6 │
└────────┴─────┴─────┘
"""
return self.with_row_index(name, offset)
def group_by(
self,
*by: IntoExpr | Iterable[IntoExpr],
maintain_order: bool = False,
**named_by: IntoExpr,
) -> GroupBy:
"""
Start a group by operation.
Parameters
----------
*by
Column(s) to group by. Accepts expression input. Strings are parsed as
column names.
maintain_order
Ensure that the order of the groups is consistent with the input data.
This is slower than a default group by.
Settings this to `True` blocks the possibility
to run on the streaming engine.
.. note::
Within each group, the order of rows is always preserved, regardless
of this argument.
**named_by
Additional columns to group by, specified as keyword arguments.
The columns will be renamed to the keyword used.
Returns
-------
GroupBy
Object which can be used to perform aggregations.
Examples
--------
Group by one column and call `agg` to compute the grouped sum of another
column.
>>> df = pl.DataFrame(
... {
... "a": ["a", "b", "a", "b", "c"],
... "b": [1, 2, 1, 3, 3],
... "c": [5, 4, 3, 2, 1],
... }
... )
>>> df.group_by("a").agg(pl.col("b").sum()) # doctest: +IGNORE_RESULT
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ a ┆ 2 │
│ b ┆ 5 │
│ c ┆ 3 │
└─────┴─────┘
Set `maintain_order=True` to ensure the order of the groups is consistent with
the input.
>>> df.group_by("a", maintain_order=True).agg(pl.col("c"))
shape: (3, 2)
┌─────┬───────────┐
│ a ┆ c │
│ --- ┆ --- │
│ str ┆ list[i64] │
╞═════╪═══════════╡
│ a ┆ [5, 3] │
│ b ┆ [4, 2] │
│ c ┆ [1] │
└─────┴───────────┘
Group by multiple columns by passing a list of column names.
>>> df.group_by(["a", "b"]).agg(pl.max("c")) # doctest: +IGNORE_RESULT
shape: (4, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ a ┆ 1 ┆ 5 │
│ b ┆ 2 ┆ 4 │
│ b ┆ 3 ┆ 2 │
│ c ┆ 3 ┆ 1 │
└─────┴─────┴─────┘
Or use positional arguments to group by multiple columns in the same way.
Expressions are also accepted.
>>> df.group_by("a", pl.col("b") // 2).agg(pl.col("c").mean()) # doctest: +SKIP
shape: (3, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 │
╞═════╪═════╪═════╡
│ a ┆ 0 ┆ 4.0 │
│ b ┆ 1 ┆ 3.0 │
│ c ┆ 1 ┆ 1.0 │
└─────┴─────┴─────┘
The `GroupBy` object returned by this method is iterable, returning the name
and data of each group.
>>> for name, data in df.group_by("a"): # doctest: +SKIP
... print(name)
... print(data)
('a',)
shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ a ┆ 1 ┆ 5 │
│ a ┆ 1 ┆ 3 │
└─────┴─────┴─────┘
('b',)
shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ b ┆ 2 ┆ 4 │
│ b ┆ 3 ┆ 2 │
└─────┴─────┴─────┘
('c',)
shape: (1, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ c ┆ 3 ┆ 1 │
└─────┴─────┴─────┘
"""
for value in named_by.values():
if not isinstance(value, (str, pl.Expr, pl.Series)):
msg = (
f"Expected Polars expression or object convertible to one, got {type(value)}.\n\n"
"Hint: if you tried\n"
f" group_by(by={value!r})\n"
"then you probably want to use this instead:\n"
f" group_by({value!r})"
)
raise TypeError(msg)
return GroupBy(
self, *by, **named_by, maintain_order=maintain_order, predicates=None
)
@deprecate_renamed_parameter("by", "group_by", version="0.20.14")
def rolling(
self,
index_column: IntoExpr,
*,
period: str | timedelta,
offset: str | timedelta | None = None,
closed: ClosedInterval = "right",
group_by: IntoExpr | Iterable[IntoExpr] | None = None,
) -> RollingGroupBy:
"""
Create rolling groups based on a temporal or integer column.
Different from a `group_by_dynamic` the windows are now determined by the
individual values and are not of constant intervals. For constant intervals use
:func:`DataFrame.group_by_dynamic`.
If you have a time series `<t_0, t_1, ..., t_n>`, then by default the
windows created will be
* (t_0 - period, t_0]
* (t_1 - period, t_1]
* ...
* (t_n - period, t_n]
whereas if you pass a non-default `offset`, then the windows will be
* (t_0 + offset, t_0 + offset + period]
* (t_1 + offset, t_1 + offset + period]
* ...
* (t_n + offset, t_n + offset + period]
The `period` and `offset` arguments are created either from a timedelta, or
by using the following string language:
- 1ns (1 nanosecond)
- 1us (1 microsecond)
- 1ms (1 millisecond)
- 1s (1 second)
- 1m (1 minute)
- 1h (1 hour)
- 1d (1 calendar day)
- 1w (1 calendar week)
- 1mo (1 calendar month)
- 1q (1 calendar quarter)
- 1y (1 calendar year)
- 1i (1 index count)
Or combine them:
"3d12h4m25s" # 3 days, 12 hours, 4 minutes, and 25 seconds
By "calendar day", we mean the corresponding time on the next day (which may
not be 24 hours, due to daylight savings). Similarly for "calendar week",
"calendar month", "calendar quarter", and "calendar year".
.. versionchanged:: 0.20.14
The `by` parameter was renamed `group_by`.
Parameters
----------
index_column
Column used to group based on the time window.
Often of type Date/Datetime.
This column must be sorted in ascending order (or, if `group_by` is
specified, then it must be sorted in ascending order within each group).
In case of a rolling operation on indices, dtype needs to be one of
{UInt32, UInt64, Int32, Int64}. Note that the first three get temporarily
cast to Int64, so if performance matters use an Int64 column.
period
Length of the window - must be non-negative.
offset
Offset of the window. Default is `-period`.
closed : {'right', 'left', 'both', 'none'}
Define which sides of the temporal interval are closed (inclusive).
group_by
Also group by this column/these columns
Returns
-------
RollingGroupBy
Object you can call `.agg` on to aggregate by groups, the result
of which will be sorted by `index_column` (but note that if `group_by`
columns are passed, it will only be sorted within each group).
See Also
--------
group_by_dynamic
Examples
--------
>>> dates = [
... "2020-01-01 13:45:48",
... "2020-01-01 16:42:13",
... "2020-01-01 16:45:09",
... "2020-01-02 18:12:48",
... "2020-01-03 19:45:32",
... "2020-01-08 23:16:43",
... ]
>>> df = pl.DataFrame({"dt": dates, "a": [3, 7, 5, 9, 2, 1]}).with_columns(
... pl.col("dt").str.strptime(pl.Datetime).set_sorted()
... )
>>> out = df.rolling(index_column="dt", period="2d").agg(
... [
... pl.sum("a").alias("sum_a"),
... pl.min("a").alias("min_a"),
... pl.max("a").alias("max_a"),
... ]
... )
>>> assert out["sum_a"].to_list() == [3, 10, 15, 24, 11, 1]
>>> assert out["max_a"].to_list() == [3, 7, 7, 9, 9, 1]
>>> assert out["min_a"].to_list() == [3, 3, 3, 3, 2, 1]
>>> out
shape: (6, 4)
┌─────────────────────┬───────┬───────┬───────┐
│ dt ┆ sum_a ┆ min_a ┆ max_a │
│ --- ┆ --- ┆ --- ┆ --- │
│ datetime[μs] ┆ i64 ┆ i64 ┆ i64 │
╞═════════════════════╪═══════╪═══════╪═══════╡
│ 2020-01-01 13:45:48 ┆ 3 ┆ 3 ┆ 3 │
│ 2020-01-01 16:42:13 ┆ 10 ┆ 3 ┆ 7 │
│ 2020-01-01 16:45:09 ┆ 15 ┆ 3 ┆ 7 │
│ 2020-01-02 18:12:48 ┆ 24 ┆ 3 ┆ 9 │
│ 2020-01-03 19:45:32 ┆ 11 ┆ 2 ┆ 9 │
│ 2020-01-08 23:16:43 ┆ 1 ┆ 1 ┆ 1 │
└─────────────────────┴───────┴───────┴───────┘
If you use an index count in `period` or `offset`, then it's based on the
values in `index_column`:
>>> df = pl.DataFrame({"int": [0, 4, 5, 6, 8], "value": [1, 4, 2, 4, 1]})
>>> df.rolling("int", period="3i").agg(pl.col("int").alias("aggregated"))
shape: (5, 2)
┌─────┬────────────┐
│ int ┆ aggregated │
│ --- ┆ --- │
│ i64 ┆ list[i64] │
╞═════╪════════════╡
│ 0 ┆ [0] │
│ 4 ┆ [4] │
│ 5 ┆ [4, 5] │
│ 6 ┆ [4, 5, 6] │
│ 8 ┆ [6, 8] │
└─────┴────────────┘
If you want the index count to be based on row number, then you may want to
combine `rolling` with :meth:`.with_row_index`.
"""
return RollingGroupBy(
self,
index_column=index_column,
period=period,
offset=offset,
closed=closed,
group_by=group_by,
predicates=None,
)
@deprecate_renamed_parameter("by", "group_by", version="0.20.14")
def group_by_dynamic(
self,
index_column: IntoExpr,
*,
every: str | timedelta,
period: str | timedelta | None = None,
offset: str | timedelta | None = None,
include_boundaries: bool = False,
closed: ClosedInterval = "left",
label: Label = "left",
group_by: IntoExpr | Iterable[IntoExpr] | None = None,
start_by: StartBy = "window",
) -> DynamicGroupBy:
"""
Group based on a time value (or index value of type Int32, Int64).
Time windows are calculated and rows are assigned to windows. Different from a
normal group by is that a row can be member of multiple groups.
By default, the windows look like:
- [start, start + period)
- [start + every, start + every + period)
- [start + 2*every, start + 2*every + period)
- ...
where `start` is determined by `start_by`, `offset`, `every`, and the earliest
datapoint. See the `start_by` argument description for details.
.. warning::
The index column must be sorted in ascending order. If `group_by` is passed, then
the index column must be sorted in ascending order within each group.
.. versionchanged:: 0.20.14
The `by` parameter was renamed `group_by`.
Parameters
----------
index_column
Column used to group based on the time window.
Often of type Date/Datetime.
This column must be sorted in ascending order (or, if `group_by` is specified,
then it must be sorted in ascending order within each group).
In case of a dynamic group by on indices, dtype needs to be one of
{Int32, Int64}. Note that Int32 gets temporarily cast to Int64, so if
performance matters use an Int64 column.
every
interval of the window
period
length of the window, if None it will equal 'every'
offset
offset of the window, does not take effect if `start_by` is 'datapoint'.
Defaults to zero.
include_boundaries
Add the lower and upper bound of the window to the "_lower_boundary" and
"_upper_boundary" columns. This will impact performance because it's harder to
parallelize
closed : {'left', 'right', 'both', 'none'}
Define which sides of the temporal interval are closed (inclusive).
label : {'left', 'right', 'datapoint'}
Define which label to use for the window:
- 'left': lower boundary of the window
- 'right': upper boundary of the window
- 'datapoint': the first value of the index column in the given window.
If you don't need the label to be at one of the boundaries, choose this
option for maximum performance
group_by
Also group by this column/these columns
start_by : {'window', 'datapoint', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'}
The strategy to determine the start of the first window by.
* 'window': Start by taking the earliest timestamp, truncating it with
`every`, and then adding `offset`.
Note that weekly windows start on Monday.
* 'datapoint': Start from the first encountered data point.
* a day of the week (only takes effect if `every` contains `'w'`):
* 'monday': Start the window on the Monday before the first data point.
* 'tuesday': Start the window on the Tuesday before the first data point.
* ...
* 'sunday': Start the window on the Sunday before the first data point.
The resulting window is then shifted back until the earliest datapoint
is in or in front of it.
Returns
-------
DynamicGroupBy
Object you can call `.agg` on to aggregate by groups, the result
of which will be sorted by `index_column` (but note that if `group_by` columns are
passed, it will only be sorted within each group).
See Also
--------
rolling
Notes
-----
1) If you're coming from pandas, then
.. code-block:: python
# polars
df.group_by_dynamic("ts", every="1d").agg(pl.col("value").sum())
is equivalent to
.. code-block:: python
# pandas
df.set_index("ts").resample("D")["value"].sum().reset_index()
though note that, unlike pandas, polars doesn't add extra rows for empty
windows. If you need `index_column` to be evenly spaced, then please combine
with :func:`DataFrame.upsample`.
2) The `every`, `period` and `offset` arguments are created with
the following string language:
- 1ns (1 nanosecond)
- 1us (1 microsecond)
- 1ms (1 millisecond)
- 1s (1 second)
- 1m (1 minute)
- 1h (1 hour)
- 1d (1 calendar day)
- 1w (1 calendar week)
- 1mo (1 calendar month)
- 1q (1 calendar quarter)
- 1y (1 calendar year)
- 1i (1 index count)
Or combine them (except in `every`):
"3d12h4m25s" # 3 days, 12 hours, 4 minutes, and 25 seconds
By "calendar day", we mean the corresponding time on the next day (which may
not be 24 hours, due to daylight savings). Similarly for "calendar week",
"calendar month", "calendar quarter", and "calendar year".
In case of a group_by_dynamic on an integer column, the windows are defined by:
- "1i" # length 1
- "10i" # length 10
Examples
--------
>>> from datetime import datetime
>>> df = pl.DataFrame(
... {
... "time": pl.datetime_range(
... start=datetime(2021, 12, 16),
... end=datetime(2021, 12, 16, 3),
... interval="30m",
... eager=True,
... ),
... "n": range(7),
... }
... )
>>> df
shape: (7, 2)
┌─────────────────────┬─────┐
│ time ┆ n │
│ --- ┆ --- │
│ datetime[μs] ┆ i64 │
╞═════════════════════╪═════╡
│ 2021-12-16 00:00:00 ┆ 0 │
│ 2021-12-16 00:30:00 ┆ 1 │
│ 2021-12-16 01:00:00 ┆ 2 │
│ 2021-12-16 01:30:00 ┆ 3 │
│ 2021-12-16 02:00:00 ┆ 4 │
│ 2021-12-16 02:30:00 ┆ 5 │
│ 2021-12-16 03:00:00 ┆ 6 │
└─────────────────────┴─────┘
Group by windows of 1 hour.
>>> df.group_by_dynamic("time", every="1h", closed="right").agg(pl.col("n"))
shape: (4, 2)
┌─────────────────────┬───────────┐
│ time ┆ n │
│ --- ┆ --- │
│ datetime[μs] ┆ list[i64] │
╞═════════════════════╪═══════════╡
│ 2021-12-15 23:00:00 ┆ [0] │
│ 2021-12-16 00:00:00 ┆ [1, 2] │
│ 2021-12-16 01:00:00 ┆ [3, 4] │
│ 2021-12-16 02:00:00 ┆ [5, 6] │
└─────────────────────┴───────────┘
The window boundaries can also be added to the aggregation result
>>> df.group_by_dynamic(
... "time", every="1h", include_boundaries=True, closed="right"
... ).agg(pl.col("n").mean())
shape: (4, 4)
┌─────────────────────┬─────────────────────┬─────────────────────┬─────┐
│ _lower_boundary ┆ _upper_boundary ┆ time ┆ n │
│ --- ┆ --- ┆ --- ┆ --- │
│ datetime[μs] ┆ datetime[μs] ┆ datetime[μs] ┆ f64 │
╞═════════════════════╪═════════════════════╪═════════════════════╪═════╡
│ 2021-12-15 23:00:00 ┆ 2021-12-16 00:00:00 ┆ 2021-12-15 23:00:00 ┆ 0.0 │
│ 2021-12-16 00:00:00 ┆ 2021-12-16 01:00:00 ┆ 2021-12-16 00:00:00 ┆ 1.5 │
│ 2021-12-16 01:00:00 ┆ 2021-12-16 02:00:00 ┆ 2021-12-16 01:00:00 ┆ 3.5 │
│ 2021-12-16 02:00:00 ┆ 2021-12-16 03:00:00 ┆ 2021-12-16 02:00:00 ┆ 5.5 │
└─────────────────────┴─────────────────────┴─────────────────────┴─────┘
When closed="left", the window excludes the right end of interval:
[lower_bound, upper_bound)
>>> df.group_by_dynamic("time", every="1h", closed="left").agg(pl.col("n"))
shape: (4, 2)
┌─────────────────────┬───────────┐
│ time ┆ n │
│ --- ┆ --- │
│ datetime[μs] ┆ list[i64] │
╞═════════════════════╪═══════════╡
│ 2021-12-16 00:00:00 ┆ [0, 1] │
│ 2021-12-16 01:00:00 ┆ [2, 3] │
│ 2021-12-16 02:00:00 ┆ [4, 5] │
│ 2021-12-16 03:00:00 ┆ [6] │
└─────────────────────┴───────────┘
When closed="both" the time values at the window boundaries belong to 2 groups.
>>> df.group_by_dynamic("time", every="1h", closed="both").agg(pl.col("n"))
shape: (4, 2)
┌─────────────────────┬───────────┐
│ time ┆ n │
│ --- ┆ --- │
│ datetime[μs] ┆ list[i64] │
╞═════════════════════╪═══════════╡
│ 2021-12-16 00:00:00 ┆ [0, 1, 2] │
│ 2021-12-16 01:00:00 ┆ [2, 3, 4] │
│ 2021-12-16 02:00:00 ┆ [4, 5, 6] │
│ 2021-12-16 03:00:00 ┆ [6] │
└─────────────────────┴───────────┘
Dynamic group bys can also be combined with grouping on normal keys
>>> df = df.with_columns(groups=pl.Series(["a", "a", "a", "b", "b", "a", "a"]))
>>> df
shape: (7, 3)
┌─────────────────────┬─────┬────────┐
│ time ┆ n ┆ groups │
│ --- ┆ --- ┆ --- │
│ datetime[μs] ┆ i64 ┆ str │
╞═════════════════════╪═════╪════════╡
│ 2021-12-16 00:00:00 ┆ 0 ┆ a │
│ 2021-12-16 00:30:00 ┆ 1 ┆ a │
│ 2021-12-16 01:00:00 ┆ 2 ┆ a │
│ 2021-12-16 01:30:00 ┆ 3 ┆ b │
│ 2021-12-16 02:00:00 ┆ 4 ┆ b │
│ 2021-12-16 02:30:00 ┆ 5 ┆ a │
│ 2021-12-16 03:00:00 ┆ 6 ┆ a │
└─────────────────────┴─────┴────────┘
>>> df.group_by_dynamic(
... "time",
... every="1h",
... closed="both",
... group_by="groups",
... include_boundaries=True,
... ).agg(pl.col("n"))
shape: (6, 5)
┌────────┬─────────────────────┬─────────────────────┬─────────────────────┬───────────┐
│ groups ┆ _lower_boundary ┆ _upper_boundary ┆ time ┆ n │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ datetime[μs] ┆ datetime[μs] ┆ datetime[μs] ┆ list[i64] │
╞════════╪═════════════════════╪═════════════════════╪═════════════════════╪═══════════╡
│ a ┆ 2021-12-16 00:00:00 ┆ 2021-12-16 01:00:00 ┆ 2021-12-16 00:00:00 ┆ [0, 1, 2] │
│ a ┆ 2021-12-16 01:00:00 ┆ 2021-12-16 02:00:00 ┆ 2021-12-16 01:00:00 ┆ [2] │
│ a ┆ 2021-12-16 02:00:00 ┆ 2021-12-16 03:00:00 ┆ 2021-12-16 02:00:00 ┆ [5, 6] │
│ a ┆ 2021-12-16 03:00:00 ┆ 2021-12-16 04:00:00 ┆ 2021-12-16 03:00:00 ┆ [6] │
│ b ┆ 2021-12-16 01:00:00 ┆ 2021-12-16 02:00:00 ┆ 2021-12-16 01:00:00 ┆ [3, 4] │
│ b ┆ 2021-12-16 02:00:00 ┆ 2021-12-16 03:00:00 ┆ 2021-12-16 02:00:00 ┆ [4] │
└────────┴─────────────────────┴─────────────────────┴─────────────────────┴───────────┘
Dynamic group by on an index column
>>> df = pl.DataFrame(
... {
... "idx": pl.int_range(0, 6, eager=True),
... "A": ["A", "A", "B", "B", "B", "C"],
... }
... )
>>> (
... df.group_by_dynamic(
... "idx",
... every="2i",
... period="3i",
... include_boundaries=True,
... closed="right",
... ).agg(pl.col("A").alias("A_agg_list"))
... )
shape: (4, 4)
┌─────────────────┬─────────────────┬─────┬─────────────────┐
│ _lower_boundary ┆ _upper_boundary ┆ idx ┆ A_agg_list │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ list[str] │
╞═════════════════╪═════════════════╪═════╪═════════════════╡
│ -2 ┆ 1 ┆ -2 ┆ ["A", "A"] │
│ 0 ┆ 3 ┆ 0 ┆ ["A", "B", "B"] │
│ 2 ┆ 5 ┆ 2 ┆ ["B", "B", "C"] │
│ 4 ┆ 7 ┆ 4 ┆ ["C"] │
└─────────────────┴─────────────────┴─────┴─────────────────┘
""" # noqa: W505
return DynamicGroupBy(
self,
index_column=index_column,
every=every,
period=period,
offset=offset,
label=label,
include_boundaries=include_boundaries,
closed=closed,
group_by=group_by,
start_by=start_by,
predicates=None,
)
@deprecate_renamed_parameter("by", "group_by", version="0.20.14")
def upsample(
self,
time_column: str,
*,
every: str | timedelta,
group_by: str | Sequence[str] | None = None,
maintain_order: bool = False,
) -> DataFrame:
"""
Upsample a DataFrame at a regular frequency.
The `every` argument is created with the following string language:
- 1ns (1 nanosecond)
- 1us (1 microsecond)
- 1ms (1 millisecond)
- 1s (1 second)
- 1m (1 minute)
- 1h (1 hour)
- 1d (1 calendar day)
- 1w (1 calendar week)
- 1mo (1 calendar month)
- 1q (1 calendar quarter)
- 1y (1 calendar year)
- 1i (1 index count)
Or combine them:
- "3d12h4m25s" # 3 days, 12 hours, 4 minutes, and 25 seconds
By "calendar day", we mean the corresponding time on the next day (which may
not be 24 hours, due to daylight savings). Similarly for "calendar week",
"calendar month", "calendar quarter", and "calendar year".
.. versionchanged:: 0.20.14
The `by` parameter was renamed `group_by`.
Parameters
----------
time_column
Time column will be used to determine a date_range.
Note that this column has to be sorted for the output to make sense.
every
Interval will start 'every' duration.
group_by
First group by these columns and then upsample for every group.
maintain_order
Keep the ordering predictable. This is slower.
Returns
-------
DataFrame
Result will be sorted by `time_column` (but note that if `group_by` columns
are passed, it will only be sorted within each group).
Examples
--------
Upsample a DataFrame by a certain interval.
>>> from datetime import datetime
>>> df = pl.DataFrame(
... {
... "time": [
... datetime(2021, 2, 1),
... datetime(2021, 4, 1),
... datetime(2021, 5, 1),
... datetime(2021, 6, 1),
... ],
... "groups": ["A", "B", "A", "B"],
... "values": [0, 1, 2, 3],
... }
... ).set_sorted("time")
>>> df.upsample(
... time_column="time", every="1mo", group_by="groups", maintain_order=True
... ).select(pl.all().fill_null(strategy="forward"))
shape: (7, 3)
┌─────────────────────┬────────┬────────┐
│ time ┆ groups ┆ values │
│ --- ┆ --- ┆ --- │
│ datetime[μs] ┆ str ┆ i64 │
╞═════════════════════╪════════╪════════╡
│ 2021-02-01 00:00:00 ┆ A ┆ 0 │
│ 2021-03-01 00:00:00 ┆ A ┆ 0 │
│ 2021-04-01 00:00:00 ┆ A ┆ 0 │
│ 2021-05-01 00:00:00 ┆ A ┆ 2 │
│ 2021-04-01 00:00:00 ┆ B ┆ 1 │
│ 2021-05-01 00:00:00 ┆ B ┆ 1 │
│ 2021-06-01 00:00:00 ┆ B ┆ 3 │
└─────────────────────┴────────┴────────┘
"""
if group_by is None:
group_by = []
if isinstance(group_by, str):
group_by = [group_by]
every = parse_as_duration_string(every)
return self._from_pydf(
self._df.upsample(group_by, time_column, every, maintain_order)
)
def join_asof(
self,
other: DataFrame,
*,
left_on: str | None | Expr = None,
right_on: str | None | Expr = None,
on: str | None | Expr = None,
by_left: str | Sequence[str] | None = None,
by_right: str | Sequence[str] | None = None,
by: str | Sequence[str] | None = None,
strategy: AsofJoinStrategy = "backward",
suffix: str = "_right",
tolerance: str | int | float | timedelta | None = None,
allow_parallel: bool = True,
force_parallel: bool = False,
coalesce: bool = True,
allow_exact_matches: bool = True,
check_sortedness: bool = True,
) -> DataFrame:
"""
Perform an asof join.
This is similar to a left-join except that we match on nearest key rather than
equal keys.
Both DataFrames must be sorted by the `on` key (within each `by` group, if
specified).
For each row in the left DataFrame:
- A "backward" search selects the last row in the right DataFrame whose
'on' key is less than or equal to the left's key.
- A "forward" search selects the first row in the right DataFrame whose
'on' key is greater than or equal to the left's key.
- A "nearest" search selects the last row in the right DataFrame whose value
is nearest to the left's key. String keys are not currently supported for a
nearest search.
The default is "backward".
Parameters
----------
other
Lazy DataFrame to join with.
left_on
Join column of the left DataFrame.
right_on
Join column of the right DataFrame.
on
Join column of both DataFrames. If set, `left_on` and `right_on` should be
None.
by
Join on these columns before doing asof join
by_left
Join on these columns before doing asof join
by_right
Join on these columns before doing asof join
strategy : {'backward', 'forward', 'nearest'}
Join strategy.
suffix
Suffix to append to columns with a duplicate name.
tolerance
Numeric tolerance. By setting this the join will only be done if the near
keys are within this distance. If an asof join is done on columns of dtype
"Date", "Datetime", "Duration" or "Time", use either a datetime.timedelta
object or the following string language:
- 1ns (1 nanosecond)
- 1us (1 microsecond)
- 1ms (1 millisecond)
- 1s (1 second)
- 1m (1 minute)
- 1h (1 hour)
- 1d (1 calendar day)
- 1w (1 calendar week)
- 1mo (1 calendar month)
- 1q (1 calendar quarter)
- 1y (1 calendar year)
Or combine them:
"3d12h4m25s" # 3 days, 12 hours, 4 minutes, and 25 seconds
By "calendar day", we mean the corresponding time on the next day
(which may not be 24 hours, due to daylight savings). Similarly for
"calendar week", "calendar month", "calendar quarter", and
"calendar year".
allow_parallel
Allow the physical plan to optionally evaluate the computation of both
DataFrames up to the join in parallel.
force_parallel
Force the physical plan to evaluate the computation of both DataFrames up to
the join in parallel.
coalesce
Coalescing behavior (merging of `on` / `left_on` / `right_on` columns):
- *True*: Always coalesce join columns.
- *False*: Never coalesce join columns.
Note that joining on any other expressions than `col`
will turn off coalescing.
allow_exact_matches
Whether exact matches are valid join predicates.
- If True, allow matching with the same ``on`` value
(i.e. less-than-or-equal-to / greater-than-or-equal-to)
- If False, don't match the same ``on`` value
(i.e., strictly less-than / strictly greater-than).
check_sortedness
Check the sortedness of the asof keys. If the keys are not sorted Polars
will error. Currently, sortedness cannot be checked if 'by' groups are
provided.
Examples
--------
>>> from datetime import date
>>> gdp = pl.DataFrame(
... {
... "date": pl.date_range(
... date(2016, 1, 1),
... date(2020, 1, 1),
... "1y",
... eager=True,
... ),
... "gdp": [4164, 4411, 4566, 4696, 4827],
... }
... )
>>> gdp
shape: (5, 2)
┌────────────┬──────┐
│ date ┆ gdp │
│ --- ┆ --- │
│ date ┆ i64 │
╞════════════╪══════╡
│ 2016-01-01 ┆ 4164 │
│ 2017-01-01 ┆ 4411 │
│ 2018-01-01 ┆ 4566 │
│ 2019-01-01 ┆ 4696 │
│ 2020-01-01 ┆ 4827 │
└────────────┴──────┘
>>> population = pl.DataFrame(
... {
... "date": [date(2016, 3, 1), date(2018, 8, 1), date(2019, 1, 1)],
... "population": [82.19, 82.66, 83.12],
... }
... ).sort("date")
>>> population
shape: (3, 2)
┌────────────┬────────────┐
│ date ┆ population │
│ --- ┆ --- │
│ date ┆ f64 │
╞════════════╪════════════╡
│ 2016-03-01 ┆ 82.19 │
│ 2018-08-01 ┆ 82.66 │
│ 2019-01-01 ┆ 83.12 │
└────────────┴────────────┘
Note how the dates don't quite match. If we join them using `join_asof` and
`strategy='backward'`, then each date from `population` which doesn't have an
exact match is matched with the closest earlier date from `gdp`:
>>> population.join_asof(gdp, on="date", strategy="backward")
shape: (3, 3)
┌────────────┬────────────┬──────┐
│ date ┆ population ┆ gdp │
│ --- ┆ --- ┆ --- │
│ date ┆ f64 ┆ i64 │
╞════════════╪════════════╪══════╡
│ 2016-03-01 ┆ 82.19 ┆ 4164 │
│ 2018-08-01 ┆ 82.66 ┆ 4566 │
│ 2019-01-01 ┆ 83.12 ┆ 4696 │
└────────────┴────────────┴──────┘
Note how:
- date `2016-03-01` from `population` is matched with `2016-01-01` from `gdp`;
- date `2018-08-01` from `population` is matched with `2018-01-01` from `gdp`.
You can verify this by passing `coalesce=False`:
>>> population.join_asof(gdp, on="date", strategy="backward", coalesce=False)
shape: (3, 4)
┌────────────┬────────────┬────────────┬──────┐
│ date ┆ population ┆ date_right ┆ gdp │
│ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ f64 ┆ date ┆ i64 │
╞════════════╪════════════╪════════════╪══════╡
│ 2016-03-01 ┆ 82.19 ┆ 2016-01-01 ┆ 4164 │
│ 2018-08-01 ┆ 82.66 ┆ 2018-01-01 ┆ 4566 │
│ 2019-01-01 ┆ 83.12 ┆ 2019-01-01 ┆ 4696 │
└────────────┴────────────┴────────────┴──────┘
If we instead use `strategy='forward'`, then each date from `population` which
doesn't have an exact match is matched with the closest later date from `gdp`:
>>> population.join_asof(gdp, on="date", strategy="forward")
shape: (3, 3)
┌────────────┬────────────┬──────┐
│ date ┆ population ┆ gdp │
│ --- ┆ --- ┆ --- │
│ date ┆ f64 ┆ i64 │
╞════════════╪════════════╪══════╡
│ 2016-03-01 ┆ 82.19 ┆ 4411 │
│ 2018-08-01 ┆ 82.66 ┆ 4696 │
│ 2019-01-01 ┆ 83.12 ┆ 4696 │
└────────────┴────────────┴──────┘
Note how:
- date `2016-03-01` from `population` is matched with `2017-01-01` from `gdp`;
- date `2018-08-01` from `population` is matched with `2019-01-01` from `gdp`.
Finally, `strategy='nearest'` gives us a mix of the two results above, as each
date from `population` which doesn't have an exact match is matched with the
closest date from `gdp`, regardless of whether it's earlier or later:
>>> population.join_asof(gdp, on="date", strategy="nearest")
shape: (3, 3)
┌────────────┬────────────┬──────┐
│ date ┆ population ┆ gdp │
│ --- ┆ --- ┆ --- │
│ date ┆ f64 ┆ i64 │
╞════════════╪════════════╪══════╡
│ 2016-03-01 ┆ 82.19 ┆ 4164 │
│ 2018-08-01 ┆ 82.66 ┆ 4696 │
│ 2019-01-01 ┆ 83.12 ┆ 4696 │
└────────────┴────────────┴──────┘
Note how:
- date `2016-03-01` from `population` is matched with `2016-01-01` from `gdp`;
- date `2018-08-01` from `population` is matched with `2019-01-01` from `gdp`.
They `by` argument allows joining on another column first, before the asof join.
In this example we join by `country` first, then asof join by date, as above.
>>> gdp_dates = pl.date_range( # fmt: skip
... date(2016, 1, 1), date(2020, 1, 1), "1y", eager=True
... )
>>> gdp2 = pl.DataFrame(
... {
... "country": ["Germany"] * 5 + ["Netherlands"] * 5,
... "date": pl.concat([gdp_dates, gdp_dates]),
... "gdp": [4164, 4411, 4566, 4696, 4827, 784, 833, 914, 910, 909],
... }
... ).sort("country", "date")
>>>
>>> gdp2
shape: (10, 3)
┌─────────────┬────────────┬──────┐
│ country ┆ date ┆ gdp │
│ --- ┆ --- ┆ --- │
│ str ┆ date ┆ i64 │
╞═════════════╪════════════╪══════╡
│ Germany ┆ 2016-01-01 ┆ 4164 │
│ Germany ┆ 2017-01-01 ┆ 4411 │
│ Germany ┆ 2018-01-01 ┆ 4566 │
│ Germany ┆ 2019-01-01 ┆ 4696 │
│ Germany ┆ 2020-01-01 ┆ 4827 │
│ Netherlands ┆ 2016-01-01 ┆ 784 │
│ Netherlands ┆ 2017-01-01 ┆ 833 │
│ Netherlands ┆ 2018-01-01 ┆ 914 │
│ Netherlands ┆ 2019-01-01 ┆ 910 │
│ Netherlands ┆ 2020-01-01 ┆ 909 │
└─────────────┴────────────┴──────┘
>>> pop2 = pl.DataFrame(
... {
... "country": ["Germany"] * 3 + ["Netherlands"] * 3,
... "date": [
... date(2016, 3, 1),
... date(2018, 8, 1),
... date(2019, 1, 1),
... date(2016, 3, 1),
... date(2018, 8, 1),
... date(2019, 1, 1),
... ],
... "population": [82.19, 82.66, 83.12, 17.11, 17.32, 17.40],
... }
... ).sort("country", "date")
>>>
>>> pop2
shape: (6, 3)
┌─────────────┬────────────┬────────────┐
│ country ┆ date ┆ population │
│ --- ┆ --- ┆ --- │
│ str ┆ date ┆ f64 │
╞═════════════╪════════════╪════════════╡
│ Germany ┆ 2016-03-01 ┆ 82.19 │
│ Germany ┆ 2018-08-01 ┆ 82.66 │
│ Germany ┆ 2019-01-01 ┆ 83.12 │
│ Netherlands ┆ 2016-03-01 ┆ 17.11 │
│ Netherlands ┆ 2018-08-01 ┆ 17.32 │
│ Netherlands ┆ 2019-01-01 ┆ 17.4 │
└─────────────┴────────────┴────────────┘
>>> pop2.join_asof(gdp2, by="country", on="date", strategy="nearest")
shape: (6, 4)
┌─────────────┬────────────┬────────────┬──────┐
│ country ┆ date ┆ population ┆ gdp │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ date ┆ f64 ┆ i64 │
╞═════════════╪════════════╪════════════╪══════╡
│ Germany ┆ 2016-03-01 ┆ 82.19 ┆ 4164 │
│ Germany ┆ 2018-08-01 ┆ 82.66 ┆ 4696 │
│ Germany ┆ 2019-01-01 ┆ 83.12 ┆ 4696 │
│ Netherlands ┆ 2016-03-01 ┆ 17.11 ┆ 784 │
│ Netherlands ┆ 2018-08-01 ┆ 17.32 ┆ 910 │
│ Netherlands ┆ 2019-01-01 ┆ 17.4 ┆ 910 │
└─────────────┴────────────┴────────────┴──────┘
"""
require_same_type(self, other)
if on is not None:
if not isinstance(on, (str, pl.Expr)):
msg = (
f"expected `on` to be str or Expr, got {qualified_type_name(on)!r}"
)
raise TypeError(msg)
else:
if not isinstance(left_on, (str, pl.Expr)):
msg = f"expected `left_on` to be str or Expr, got {qualified_type_name(left_on)!r}"
raise TypeError(msg)
elif not isinstance(right_on, (str, pl.Expr)):
msg = f"expected `right_on` to be str or Expr, got {qualified_type_name(right_on)!r}"
raise TypeError(msg)
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.join_asof(
other.lazy(),
left_on=left_on,
right_on=right_on,
on=on,
by_left=by_left,
by_right=by_right,
by=by,
strategy=strategy,
suffix=suffix,
tolerance=tolerance,
allow_parallel=allow_parallel,
force_parallel=force_parallel,
coalesce=coalesce,
allow_exact_matches=allow_exact_matches,
check_sortedness=check_sortedness,
)
.collect(optimizations=QueryOptFlags._eager())
)
@deprecate_renamed_parameter("join_nulls", "nulls_equal", version="1.24")
def join(
self,
other: DataFrame,
on: str | Expr | Sequence[str | Expr] | None = None,
how: JoinStrategy = "inner",
*,
left_on: str | Expr | Sequence[str | Expr] | None = None,
right_on: str | Expr | Sequence[str | Expr] | None = None,
suffix: str = "_right",
validate: JoinValidation = "m:m",
nulls_equal: bool = False,
coalesce: bool | None = None,
maintain_order: MaintainOrderJoin | None = None,
) -> DataFrame:
"""
Join in SQL-like fashion.
.. versionchanged:: 1.24
The `join_nulls` parameter was renamed `nulls_equal`.
Parameters
----------
other
DataFrame to join with.
on
Name(s) of the join columns in both DataFrames. If set, `left_on` and
`right_on` should be None. This should not be specified if `how='cross'`.
how : {'inner', 'left', 'right', 'full', 'semi', 'anti', 'cross'}
Join strategy.
.. list-table ::
:header-rows: 0
* - **inner**
- *(Default)* Returns rows that have matching values in both tables.
* - **left**
- Returns all rows from the left table, and the matched rows from
the right table.
* - **full**
- Returns all rows when there is a match in either left or right.
* - **cross**
- Returns the Cartesian product of rows from both tables
* - **semi**
- Returns rows from the left table that have a match in the right
table.
* - **anti**
- Returns rows from the left table that have no match in the right
table.
left_on
Name(s) of the left join column(s).
right_on
Name(s) of the right join column(s).
suffix
Suffix to append to columns with a duplicate name.
validate: {'m:m', 'm:1', '1:m', '1:1'}
Checks if join is of specified type.
.. list-table ::
:header-rows: 0
* - **m:m**
- *(Default)* Many-to-many (default). Does not result in checks.
* - **1:1**
- One-to-one. Checks if join keys are unique in both left and
right datasets.
* - **1:m**
- One-to-many. Checks if join keys are unique in left dataset.
* - **m:1**
- Many-to-one. Check if join keys are unique in right dataset.
.. note::
This is currently not supported by the streaming engine.
nulls_equal
Join on null values. By default null values will never produce matches.
coalesce
Coalescing behavior (merging of join columns).
.. list-table ::
:header-rows: 0
* - **None**
- *(Default)* Coalesce unless `how='full'` is specified.
* - **True**
- Always coalesce join columns.
* - **False**
- Never coalesce join columns.
.. note::
Joining on any other expressions than `col`
will turn off coalescing.
maintain_order : {'none', 'left', 'right', 'left_right', 'right_left'}
Which DataFrame row order to preserve, if any.
Do not rely on any observed ordering without explicitly setting this
parameter, as your code may break in a future release.
Not specifying any ordering can improve performance.
.. list-table ::
:header-rows: 0
* - **none**
- *(Default)* No specific ordering is desired. The ordering might
differ across Polars versions or even between different runs.
* - **left**
- Preserves the order of the left DataFrame.
* - **right**
- Preserves the order of the right DataFrame.
* - **left_right**
- First preserves the order of the left DataFrame, then the right.
* - **right_left**
- First preserves the order of the right DataFrame, then the left.
See Also
--------
join_asof
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> other_df = pl.DataFrame(
... {
... "apple": ["x", "y", "z"],
... "ham": ["a", "b", "d"],
... }
... )
>>> df.join(other_df, on="ham")
shape: (2, 4)
┌─────┬─────┬─────┬───────┐
│ foo ┆ bar ┆ ham ┆ apple │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str ┆ str │
╞═════╪═════╪═════╪═══════╡
│ 1 ┆ 6.0 ┆ a ┆ x │
│ 2 ┆ 7.0 ┆ b ┆ y │
└─────┴─────┴─────┴───────┘
>>> df.join(other_df, on="ham", how="full")
shape: (4, 5)
┌──────┬──────┬──────┬───────┬───────────┐
│ foo ┆ bar ┆ ham ┆ apple ┆ ham_right │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str ┆ str ┆ str │
╞══════╪══════╪══════╪═══════╪═══════════╡
│ 1 ┆ 6.0 ┆ a ┆ x ┆ a │
│ 2 ┆ 7.0 ┆ b ┆ y ┆ b │
│ null ┆ null ┆ null ┆ z ┆ d │
│ 3 ┆ 8.0 ┆ c ┆ null ┆ null │
└──────┴──────┴──────┴───────┴───────────┘
>>> df.join(other_df, on="ham", how="full", coalesce=True)
shape: (4, 4)
┌──────┬──────┬─────┬───────┐
│ foo ┆ bar ┆ ham ┆ apple │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str ┆ str │
╞══════╪══════╪═════╪═══════╡
│ 1 ┆ 6.0 ┆ a ┆ x │
│ 2 ┆ 7.0 ┆ b ┆ y │
│ null ┆ null ┆ d ┆ z │
│ 3 ┆ 8.0 ┆ c ┆ null │
└──────┴──────┴─────┴───────┘
>>> df.join(other_df, on="ham", how="left")
shape: (3, 4)
┌─────┬─────┬─────┬───────┐
│ foo ┆ bar ┆ ham ┆ apple │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str ┆ str │
╞═════╪═════╪═════╪═══════╡
│ 1 ┆ 6.0 ┆ a ┆ x │
│ 2 ┆ 7.0 ┆ b ┆ y │
│ 3 ┆ 8.0 ┆ c ┆ null │
└─────┴─────┴─────┴───────┘
>>> df.join(other_df, on="ham", how="semi")
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6.0 ┆ a │
│ 2 ┆ 7.0 ┆ b │
└─────┴─────┴─────┘
>>> df.join(other_df, on="ham", how="anti")
shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞═════╪═════╪═════╡
│ 3 ┆ 8.0 ┆ c │
└─────┴─────┴─────┘
>>> df.join(other_df, how="cross")
shape: (9, 5)
┌─────┬─────┬─────┬───────┬───────────┐
│ foo ┆ bar ┆ ham ┆ apple ┆ ham_right │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str ┆ str ┆ str │
╞═════╪═════╪═════╪═══════╪═══════════╡
│ 1 ┆ 6.0 ┆ a ┆ x ┆ a │
│ 1 ┆ 6.0 ┆ a ┆ y ┆ b │
│ 1 ┆ 6.0 ┆ a ┆ z ┆ d │
│ 2 ┆ 7.0 ┆ b ┆ x ┆ a │
│ 2 ┆ 7.0 ┆ b ┆ y ┆ b │
│ 2 ┆ 7.0 ┆ b ┆ z ┆ d │
│ 3 ┆ 8.0 ┆ c ┆ x ┆ a │
│ 3 ┆ 8.0 ┆ c ┆ y ┆ b │
│ 3 ┆ 8.0 ┆ c ┆ z ┆ d │
└─────┴─────┴─────┴───────┴───────────┘
Notes
-----
For joining on columns with categorical data, see :class:`polars.StringCache`.
"""
require_same_type(self, other)
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.join(
other=other.lazy(),
left_on=left_on,
right_on=right_on,
on=on,
how=how,
suffix=suffix,
validate=validate,
nulls_equal=nulls_equal,
coalesce=coalesce,
maintain_order=maintain_order,
)
.collect(optimizations=QueryOptFlags._eager())
)
@unstable()
def join_where(
self,
other: DataFrame,
*predicates: Expr | Iterable[Expr],
suffix: str = "_right",
) -> DataFrame:
"""
Perform a join based on one or multiple (in)equality predicates.
This performs an inner join, so only rows where all predicates are true
are included in the result, and a row from either DataFrame may be included
multiple times in the result.
.. note::
The row order of the input DataFrames is not preserved.
.. warning::
This functionality is experimental. It may be
changed at any point without it being considered a breaking change.
Parameters
----------
other
DataFrame to join with.
*predicates
(In)Equality condition to join the two tables on.
When a column name occurs in both tables, the proper suffix must
be applied in the predicate.
suffix
Suffix to append to columns with a duplicate name.
Examples
--------
Join two dataframes together based on two predicates which get AND-ed together.
>>> east = pl.DataFrame(
... {
... "id": [100, 101, 102],
... "dur": [120, 140, 160],
... "rev": [12, 14, 16],
... "cores": [2, 8, 4],
... }
... )
>>> west = pl.DataFrame(
... {
... "t_id": [404, 498, 676, 742],
... "time": [90, 130, 150, 170],
... "cost": [9, 13, 15, 16],
... "cores": [4, 2, 1, 4],
... }
... )
>>> east.join_where(
... west,
... pl.col("dur") < pl.col("time"),
... pl.col("rev") < pl.col("cost"),
... )
shape: (5, 8)
┌─────┬─────┬─────┬───────┬──────┬──────┬──────┬─────────────┐
│ id ┆ dur ┆ rev ┆ cores ┆ t_id ┆ time ┆ cost ┆ cores_right │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═══════╪══════╪══════╪══════╪═════════════╡
│ 100 ┆ 120 ┆ 12 ┆ 2 ┆ 498 ┆ 130 ┆ 13 ┆ 2 │
│ 100 ┆ 120 ┆ 12 ┆ 2 ┆ 676 ┆ 150 ┆ 15 ┆ 1 │
│ 100 ┆ 120 ┆ 12 ┆ 2 ┆ 742 ┆ 170 ┆ 16 ┆ 4 │
│ 101 ┆ 140 ┆ 14 ┆ 8 ┆ 676 ┆ 150 ┆ 15 ┆ 1 │
│ 101 ┆ 140 ┆ 14 ┆ 8 ┆ 742 ┆ 170 ┆ 16 ┆ 4 │
└─────┴─────┴─────┴───────┴──────┴──────┴──────┴─────────────┘
To OR them together, use a single expression and the `|` operator.
>>> east.join_where(
... west,
... (pl.col("dur") < pl.col("time")) | (pl.col("rev") < pl.col("cost")),
... )
shape: (6, 8)
┌─────┬─────┬─────┬───────┬──────┬──────┬──────┬─────────────┐
│ id ┆ dur ┆ rev ┆ cores ┆ t_id ┆ time ┆ cost ┆ cores_right │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═══════╪══════╪══════╪══════╪═════════════╡
│ 100 ┆ 120 ┆ 12 ┆ 2 ┆ 498 ┆ 130 ┆ 13 ┆ 2 │
│ 100 ┆ 120 ┆ 12 ┆ 2 ┆ 676 ┆ 150 ┆ 15 ┆ 1 │
│ 100 ┆ 120 ┆ 12 ┆ 2 ┆ 742 ┆ 170 ┆ 16 ┆ 4 │
│ 101 ┆ 140 ┆ 14 ┆ 8 ┆ 676 ┆ 150 ┆ 15 ┆ 1 │
│ 101 ┆ 140 ┆ 14 ┆ 8 ┆ 742 ┆ 170 ┆ 16 ┆ 4 │
│ 102 ┆ 160 ┆ 16 ┆ 4 ┆ 742 ┆ 170 ┆ 16 ┆ 4 │
└─────┴─────┴─────┴───────┴──────┴──────┴──────┴─────────────┘
"""
require_same_type(self, other)
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.join_where(
other.lazy(),
*predicates,
suffix=suffix,
)
.collect(optimizations=QueryOptFlags._eager())
)
def map_rows(
self,
function: Callable[[tuple[Any, ...]], Any],
return_dtype: PolarsDataType | None = None,
*,
inference_size: int = 256,
) -> DataFrame:
"""
Apply a custom/user-defined function (UDF) over the rows of the DataFrame.
.. warning::
This method is much slower than the native expressions API.
Only use it if you cannot implement your logic otherwise.
The UDF will receive each row as a tuple of values: `udf(row)`.
Implementing logic using a Python function is almost always *significantly*
slower and more memory intensive than implementing the same logic using
the native expression API because:
- The native expression engine runs in Rust; UDFs run in Python.
- Use of Python UDFs forces the DataFrame to be materialized in memory.
- Polars-native expressions can be parallelised (UDFs typically cannot).
- Polars-native expressions can be logically optimised (UDFs cannot).
Wherever possible you should strongly prefer the native expression API
to achieve the best performance.
Parameters
----------
function
Custom function or lambda.
return_dtype
Output type of the operation. If none given, Polars tries to infer the type.
inference_size
Only used in the case when the custom function returns rows.
This uses the first `n` rows to determine the output schema.
Notes
-----
* The frame-level `map_rows` cannot track column names (as the UDF is a
black-box that may arbitrarily drop, rearrange, transform, or add new
columns); if you want to apply a UDF such that column names are preserved,
you should use the expression-level `map_elements` syntax instead.
* If your function is expensive and you don't want it to be called more than
once for a given input, consider applying an `@lru_cache` decorator to it.
If your data is suitable you may achieve *significant* speedups.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3], "bar": [-1, 5, 8]})
Return a DataFrame by mapping each row to a tuple:
>>> df.map_rows(lambda t: (t[0] * 2, t[1] * 3))
shape: (3, 2)
┌──────────┬──────────┐
│ column_0 ┆ column_1 │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════════╪══════════╡
│ 2 ┆ -3 │
│ 4 ┆ 15 │
│ 6 ┆ 24 │
└──────────┴──────────┘
However, it is much better to implement this with a native expression:
>>> df.select(
... pl.col("foo") * 2,
... pl.col("bar") * 3,
... ) # doctest: +IGNORE_RESULT
Return a DataFrame with a single column by mapping each row to a scalar:
>>> df.map_rows(lambda t: (t[0] * 2 + t[1]))
shape: (3, 1)
┌─────┐
│ map │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ 9 │
│ 14 │
└─────┘
In this case it is better to use the following native expression:
>>> df.select(pl.col("foo") * 2 + pl.col("bar")) # doctest: +IGNORE_RESULT
"""
# TODO: Enable warning for inefficient map
# from polars._utils.udfs import warn_on_inefficient_map
# warn_on_inefficient_map(function, columns=self.columns, map_target="frame)
out, is_df = self._df.map_rows(function, return_dtype, inference_size)
if is_df:
return self._from_pydf(out)
else:
return wrap_s(out).to_frame()
def hstack(
self, columns: list[Series] | DataFrame, *, in_place: bool = False
) -> DataFrame:
"""
Return a new DataFrame grown horizontally by stacking multiple Series to it.
Parameters
----------
columns
Series to stack.
in_place
Modify in place.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> x = pl.Series("apple", [10, 20, 30])
>>> df.hstack([x])
shape: (3, 4)
┌─────┬─────┬─────┬───────┐
│ foo ┆ bar ┆ ham ┆ apple │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str ┆ i64 │
╞═════╪═════╪═════╪═══════╡
│ 1 ┆ 6 ┆ a ┆ 10 │
│ 2 ┆ 7 ┆ b ┆ 20 │
│ 3 ┆ 8 ┆ c ┆ 30 │
└─────┴─────┴─────┴───────┘
"""
if not isinstance(columns, list):
columns = columns.get_columns()
if in_place:
self._df.hstack_mut([s._s for s in columns])
return self
else:
return self._from_pydf(self._df.hstack([s._s for s in columns]))
def vstack(self, other: DataFrame, *, in_place: bool = False) -> DataFrame:
"""
Grow this DataFrame vertically by stacking a DataFrame to it.
Parameters
----------
other
DataFrame to stack.
in_place
Modify in place.
See Also
--------
extend
Examples
--------
>>> df1 = pl.DataFrame(
... {
... "foo": [1, 2],
... "bar": [6, 7],
... "ham": ["a", "b"],
... }
... )
>>> df2 = pl.DataFrame(
... {
... "foo": [3, 4],
... "bar": [8, 9],
... "ham": ["c", "d"],
... }
... )
>>> df1.vstack(df2)
shape: (4, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
│ 4 ┆ 9 ┆ d │
└─────┴─────┴─────┘
"""
require_same_type(self, other)
if in_place:
self._df.vstack_mut(other._df)
return self
return self._from_pydf(self._df.vstack(other._df))
def extend(self, other: DataFrame) -> DataFrame:
"""
Extend the memory backed by this `DataFrame` with the values from `other`.
Different from `vstack` which adds the chunks from `other` to the chunks of
this `DataFrame`, `extend` appends the data from `other` to the underlying
memory locations and thus may cause a reallocation.
If this does not cause a reallocation, the resulting data structure will not
have any extra chunks and thus will yield faster queries.
Prefer `extend` over `vstack` when you want to do a query after a single
append. For instance, during online operations where you add `n` rows and rerun
a query.
Prefer `vstack` over `extend` when you want to append many times before
doing a query. For instance, when you read in multiple files and want to store
them in a single `DataFrame`. In the latter case, finish the sequence of
`vstack` operations with a `rechunk`.
Parameters
----------
other
DataFrame to vertically add.
Warnings
--------
This method modifies the dataframe in-place. The dataframe is returned for
convenience only.
See Also
--------
vstack
Examples
--------
>>> df1 = pl.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
>>> df2 = pl.DataFrame({"foo": [10, 20, 30], "bar": [40, 50, 60]})
>>> df1.extend(df2)
shape: (6, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 4 │
│ 2 ┆ 5 │
│ 3 ┆ 6 │
│ 10 ┆ 40 │
│ 20 ┆ 50 │
│ 30 ┆ 60 │
└─────┴─────┘
"""
require_same_type(self, other)
self._df.extend(other._df)
return self
def drop(
self,
*columns: ColumnNameOrSelector | Iterable[ColumnNameOrSelector],
strict: bool = True,
) -> DataFrame:
"""
Remove columns from the dataframe.
Parameters
----------
*columns
Names of the columns that should be removed from the dataframe.
Accepts column selector input.
strict
Validate that all column names exist in the current schema,
and throw an exception if any do not.
Examples
--------
Drop a single column by passing the name of that column.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.drop("ham")
shape: (3, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪═════╡
│ 1 ┆ 6.0 │
│ 2 ┆ 7.0 │
│ 3 ┆ 8.0 │
└─────┴─────┘
Drop multiple columns by passing a list of column names.
>>> df.drop(["bar", "ham"])
shape: (3, 1)
┌─────┐
│ foo │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ 2 │
│ 3 │
└─────┘
Drop multiple columns by passing a selector.
>>> import polars.selectors as cs
>>> df.drop(cs.numeric())
shape: (3, 1)
┌─────┐
│ ham │
│ --- │
│ str │
╞═════╡
│ a │
│ b │
│ c │
└─────┘
Use positional arguments to drop multiple columns.
>>> df.drop("foo", "ham")
shape: (3, 1)
┌─────┐
│ bar │
│ --- │
│ f64 │
╞═════╡
│ 6.0 │
│ 7.0 │
│ 8.0 │
└─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.drop(*columns, strict=strict)
.collect(optimizations=QueryOptFlags._eager())
)
def drop_in_place(self, name: str) -> Series:
"""
Drop a single column in-place and return the dropped column.
Parameters
----------
name
Name of the column to drop.
Returns
-------
Series
The dropped column.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.drop_in_place("ham")
shape: (3,)
Series: 'ham' [str]
[
"a"
"b"
"c"
]
"""
return wrap_s(self._df.drop_in_place(name))
def cast(
self,
dtypes: (
Mapping[
ColumnNameOrSelector | PolarsDataType, PolarsDataType | PythonDataType
]
| PolarsDataType
),
*,
strict: bool = True,
) -> DataFrame:
"""
Cast DataFrame column(s) to the specified dtype(s).
Parameters
----------
dtypes
Mapping of column names (or selector) to dtypes, or a single dtype
to which all columns will be cast.
strict
Raise if cast is invalid on rows after predicates are pushed down.
If `False`, invalid casts will produce null values.
Examples
--------
>>> from datetime import date
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": [date(2020, 1, 2), date(2021, 3, 4), date(2022, 5, 6)],
... }
... )
Cast specific frame columns to the specified dtypes:
>>> df.cast({"foo": pl.Float32, "bar": pl.UInt8})
shape: (3, 3)
┌─────┬─────┬────────────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f32 ┆ u8 ┆ date │
╞═════╪═════╪════════════╡
│ 1.0 ┆ 6 ┆ 2020-01-02 │
│ 2.0 ┆ 7 ┆ 2021-03-04 │
│ 3.0 ┆ 8 ┆ 2022-05-06 │
└─────┴─────┴────────────┘
Cast all frame columns matching one dtype (or dtype group) to another dtype:
>>> df.cast({pl.Date: pl.Datetime})
shape: (3, 3)
┌─────┬─────┬─────────────────────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ datetime[μs] │
╞═════╪═════╪═════════════════════╡
│ 1 ┆ 6.0 ┆ 2020-01-02 00:00:00 │
│ 2 ┆ 7.0 ┆ 2021-03-04 00:00:00 │
│ 3 ┆ 8.0 ┆ 2022-05-06 00:00:00 │
└─────┴─────┴─────────────────────┘
Use selectors to define the columns being cast:
>>> import polars.selectors as cs
>>> df.cast({cs.numeric(): pl.UInt32, cs.temporal(): pl.String})
shape: (3, 3)
┌─────┬─────┬────────────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ str │
╞═════╪═════╪════════════╡
│ 1 ┆ 6 ┆ 2020-01-02 │
│ 2 ┆ 7 ┆ 2021-03-04 │
│ 3 ┆ 8 ┆ 2022-05-06 │
└─────┴─────┴────────────┘
Cast all frame columns to the specified dtype:
>>> df.cast(pl.String).to_dict(as_series=False)
{'foo': ['1', '2', '3'],
'bar': ['6.0', '7.0', '8.0'],
'ham': ['2020-01-02', '2021-03-04', '2022-05-06']}
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.cast(dtypes, strict=strict)
.collect(optimizations=QueryOptFlags._eager())
)
def clear(self, n: int = 0) -> DataFrame:
"""
Create an empty (n=0) or `n`-row null-filled (n>0) copy of the DataFrame.
Returns a `n`-row null-filled DataFrame with an identical schema.
`n` can be greater than the current number of rows in the DataFrame.
Parameters
----------
n
Number of (null-filled) rows to return in the cleared frame.
See Also
--------
clone : Cheap deepcopy/clone.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [None, 2, 3, 4],
... "b": [0.5, None, 2.5, 13],
... "c": [True, True, False, None],
... }
... )
>>> df.clear()
shape: (0, 3)
┌─────┬─────┬──────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ bool │
╞═════╪═════╪══════╡
└─────┴─────┴──────┘
>>> df.clear(n=2)
shape: (2, 3)
┌──────┬──────┬──────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ bool │
╞══════╪══════╪══════╡
│ null ┆ null ┆ null │
│ null ┆ null ┆ null │
└──────┴──────┴──────┘
"""
if not (is_int := isinstance(n, int)) or n < 0: # type: ignore[redundant-expr]
msg = f"`n` should be an integer >= 0, got {n}"
err = TypeError if not is_int else ValueError
raise err(msg)
if n == 0:
return self._from_pydf(self._df.clear())
return self.__class__(
{
nm: pl.Series(name=nm, dtype=tp).extend_constant(None, n)
for nm, tp in self.schema.items()
}
)
def clone(self) -> DataFrame:
"""
Create a copy of this DataFrame.
This is a cheap operation that does not copy data.
See Also
--------
clear : Create an empty copy of the current DataFrame, with identical
schema but no data.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 4],
... "b": [0.5, 4, 10, 13],
... "c": [True, True, False, True],
... }
... )
>>> df.clone()
shape: (4, 3)
┌─────┬──────┬───────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ bool │
╞═════╪══════╪═══════╡
│ 1 ┆ 0.5 ┆ true │
│ 2 ┆ 4.0 ┆ true │
│ 3 ┆ 10.0 ┆ false │
│ 4 ┆ 13.0 ┆ true │
└─────┴──────┴───────┘
"""
return self._from_pydf(self._df.clone())
def get_columns(self) -> list[Series]:
"""
Get the DataFrame as a List of Series.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
>>> df.get_columns()
[shape: (3,)
Series: 'foo' [i64]
[
1
2
3
], shape: (3,)
Series: 'bar' [i64]
[
4
5
6
]]
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 4],
... "b": [0.5, 4, 10, 13],
... "c": [True, True, False, True],
... }
... )
>>> df.get_columns()
[shape: (4,)
Series: 'a' [i64]
[
1
2
3
4
], shape: (4,)
Series: 'b' [f64]
[
0.5
4.0
10.0
13.0
], shape: (4,)
Series: 'c' [bool]
[
true
true
false
true
]]
"""
return [wrap_s(s) for s in self._df.get_columns()]
@overload
def get_column(self, name: str, *, default: Series | NoDefault = ...) -> Series: ...
@overload
def get_column(self, name: str, *, default: Any) -> Any: ...
def get_column(
self, name: str, *, default: Any | NoDefault = no_default
) -> Series | Any:
"""
Get a single column by name.
Parameters
----------
name
String name of the column to retrieve.
default
Value to return if the column does not exist; if not explicitly set and
the column is not present a `ColumnNotFoundError` exception is raised.
Returns
-------
Series (or arbitrary default value, if specified).
See Also
--------
to_series
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
>>> df.get_column("foo")
shape: (3,)
Series: 'foo' [i64]
[
1
2
3
]
Missing column handling; can optionally provide an arbitrary default value
to the method (otherwise a `ColumnNotFoundError` exception is raised).
>>> df.get_column("baz", default=pl.Series("baz", ["?", "?", "?"]))
shape: (3,)
Series: 'baz' [str]
[
"?"
"?"
"?"
]
>>> res = df.get_column("baz", default=None)
>>> res is None
True
"""
try:
return wrap_s(self._df.get_column(name))
except ColumnNotFoundError:
if default is no_default:
raise
return default
def fill_null(
self,
value: Any | Expr | None = None,
strategy: FillNullStrategy | None = None,
limit: int | None = None,
*,
matches_supertype: bool = True,
) -> DataFrame:
"""
Fill null values using the specified value or strategy.
Parameters
----------
value
Value used to fill null values.
strategy : {None, 'forward', 'backward', 'min', 'max', 'mean', 'zero', 'one'}
Strategy used to fill null values.
limit
Number of consecutive null values to fill when using the 'forward' or
'backward' strategy.
matches_supertype
Fill all matching supertype of the fill `value`.
Returns
-------
DataFrame
DataFrame with None values replaced by the filling strategy.
See Also
--------
fill_nan
Notes
-----
A null value is not the same as a NaN value.
To fill NaN values, use :func:`fill_nan`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 2, None, 4],
... "b": [0.5, 4, None, 13],
... }
... )
>>> df.fill_null(99)
shape: (4, 2)
┌─────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪══════╡
│ 1 ┆ 0.5 │
│ 2 ┆ 4.0 │
│ 99 ┆ 99.0 │
│ 4 ┆ 13.0 │
└─────┴──────┘
>>> df.fill_null(strategy="forward")
shape: (4, 2)
┌─────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪══════╡
│ 1 ┆ 0.5 │
│ 2 ┆ 4.0 │
│ 2 ┆ 4.0 │
│ 4 ┆ 13.0 │
└─────┴──────┘
>>> df.fill_null(strategy="max")
shape: (4, 2)
┌─────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪══════╡
│ 1 ┆ 0.5 │
│ 2 ┆ 4.0 │
│ 4 ┆ 13.0 │
│ 4 ┆ 13.0 │
└─────┴──────┘
>>> df.fill_null(strategy="zero")
shape: (4, 2)
┌─────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪══════╡
│ 1 ┆ 0.5 │
│ 2 ┆ 4.0 │
│ 0 ┆ 0.0 │
│ 4 ┆ 13.0 │
└─────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.fill_null(value, strategy, limit, matches_supertype=matches_supertype)
.collect(optimizations=QueryOptFlags._eager())
)
def fill_nan(self, value: Expr | int | float | None) -> DataFrame:
"""
Fill floating point NaN values by an Expression evaluation.
Parameters
----------
value
Value used to fill NaN values.
Returns
-------
DataFrame
DataFrame with NaN values replaced by the given value.
See Also
--------
fill_null
Notes
-----
A NaN value is not the same as a null value.
To fill null values, use :func:`fill_null`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1.5, 2, float("nan"), 4],
... "b": [0.5, 4, float("nan"), 13],
... }
... )
>>> df.fill_nan(99)
shape: (4, 2)
┌──────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ f64 ┆ f64 │
╞══════╪══════╡
│ 1.5 ┆ 0.5 │
│ 2.0 ┆ 4.0 │
│ 99.0 ┆ 99.0 │
│ 4.0 ┆ 13.0 │
└──────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().fill_nan(value).collect(optimizations=QueryOptFlags._eager())
def explode(
self,
columns: ColumnNameOrSelector | Iterable[ColumnNameOrSelector],
*more_columns: ColumnNameOrSelector,
empty_as_null: bool = True,
keep_nulls: bool = True,
) -> DataFrame:
"""
Explode the dataframe to long format by exploding the given columns.
Parameters
----------
columns
Column names, expressions, or a selector defining them. The underlying
columns being exploded must be of the `List` or `Array` data type.
*more_columns
Additional names of columns to explode, specified as positional arguments.
empty_as_null
Explode an empty list/array into a `null`.
keep_nulls
Explode a `null` list/array into a `null`.
Returns
-------
DataFrame
Examples
--------
>>> df = pl.DataFrame(
... {
... "letters": ["a", "a", "b", "c"],
... "numbers": [[1], [2, 3], [4, 5], [6, 7, 8]],
... }
... )
>>> df
shape: (4, 2)
┌─────────┬───────────┐
│ letters ┆ numbers │
│ --- ┆ --- │
│ str ┆ list[i64] │
╞═════════╪═══════════╡
│ a ┆ [1] │
│ a ┆ [2, 3] │
│ b ┆ [4, 5] │
│ c ┆ [6, 7, 8] │
└─────────┴───────────┘
>>> df.explode("numbers")
shape: (8, 2)
┌─────────┬─────────┐
│ letters ┆ numbers │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════════╪═════════╡
│ a ┆ 1 │
│ a ┆ 2 │
│ a ┆ 3 │
│ b ┆ 4 │
│ b ┆ 5 │
│ c ┆ 6 │
│ c ┆ 7 │
│ c ┆ 8 │
└─────────┴─────────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.explode(
columns,
*more_columns,
empty_as_null=empty_as_null,
keep_nulls=keep_nulls,
)
.collect(optimizations=QueryOptFlags._eager())
)
@deprecate_renamed_parameter("columns", "on", version="1.0.0")
def pivot(
self,
on: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
on_columns: Sequence[Any] | pl.Series | pl.DataFrame | None = None,
*,
index: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None,
values: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None,
aggregate_function: PivotAgg | Expr | None = None,
maintain_order: bool = True,
sort_columns: bool = False,
separator: str = "_",
) -> DataFrame:
"""
Create a spreadsheet-style pivot table as a DataFrame.
Only available in eager mode. See "Examples" section below for how to do a
"lazy pivot" if you know the unique column values in advance.
.. versionchanged:: 1.0.0
The `columns` parameter was renamed `on`.
Parameters
----------
on
The column(s) whose values will be used as the new columns of the output
DataFrame.
on_columns
What value combinations will be considered for the output table.
index
The column(s) that remain from the input to the output. The output DataFrame will have one row
for each unique combination of the `index`'s values.
If None, all remaining columns not specified on `on` and `values` will be used. At least one
of `index` and `values` must be specified.
values
The existing column(s) of values which will be moved under the new columns from index. If an
aggregation is specified, these are the values on which the aggregation will be computed.
If None, all remaining columns not specified on `on` and `index` will be used.
At least one of `index` and `values` must be specified.
aggregate_function
Choose from:
- None: no aggregation takes place, will raise error if multiple values are in group.
- A predefined aggregate function string, one of
{'min', 'max', 'first', 'last', 'sum', 'mean', 'median', 'len'}
- An expression to do the aggregation. The expression can only access data from the respective
'values' columns as generated by pivot, through `pl.element()`.
maintain_order
Ensure the values of `index` are sorted by discovery order.
sort_columns
Sort the transposed columns by name. Default is by order of discovery.
separator
Used as separator/delimiter in generated column names in case of multiple
`values` columns.
Returns
-------
DataFrame
Notes
-----
In some other frameworks, you might know this operation as `pivot_wider`.
Examples
--------
You can use `pivot` to reshape a dataframe from "long" to "wide" format.
For example, suppose we have a dataframe of test scores achieved by some
students, where each row represents a distinct test.
>>> df = pl.DataFrame(
... {
... "name": ["Cady", "Cady", "Karen", "Karen"],
... "subject": ["maths", "physics", "maths", "physics"],
... "test_1": [98, 99, 61, 58],
... "test_2": [100, 100, 60, 60],
... }
... )
>>> df
shape: (4, 4)
┌───────┬─────────┬────────┬────────┐
│ name ┆ subject ┆ test_1 ┆ test_2 │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ i64 │
╞═══════╪═════════╪════════╪════════╡
│ Cady ┆ maths ┆ 98 ┆ 100 │
│ Cady ┆ physics ┆ 99 ┆ 100 │
│ Karen ┆ maths ┆ 61 ┆ 60 │
│ Karen ┆ physics ┆ 58 ┆ 60 │
└───────┴─────────┴────────┴────────┘
Using `pivot`, we can reshape so we have one row per student, with different
subjects as columns, and their `test_1` scores as values:
>>> df.pivot("subject", index="name", values="test_1")
shape: (2, 3)
┌───────┬───────┬─────────┐
│ name ┆ maths ┆ physics │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═══════╪═══════╪═════════╡
│ Cady ┆ 98 ┆ 99 │
│ Karen ┆ 61 ┆ 58 │
└───────┴───────┴─────────┘
If you want to only pivot over a limited set of `subject` values or already
know the `subject` values ahead of time, you can provide these using the
`on_columns` argument.
>>> df.pivot(
... "subject",
... on_columns=["maths", "physics"],
... index="name",
... values="test_1",
... )
shape: (2, 3)
┌───────┬───────┬─────────┐
│ name ┆ maths ┆ physics │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═══════╪═══════╪═════════╡
│ Cady ┆ 98 ┆ 99 │
│ Karen ┆ 61 ┆ 58 │
└───────┴───────┴─────────┘
You can use selectors too - here we include all test scores in the pivoted table:
>>> import polars.selectors as cs
>>> df.pivot("subject", values=cs.starts_with("test"))
shape: (2, 5)
┌───────┬──────────────┬────────────────┬──────────────┬────────────────┐
│ name ┆ test_1_maths ┆ test_1_physics ┆ test_2_maths ┆ test_2_physics │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═══════╪══════════════╪════════════════╪══════════════╪════════════════╡
│ Cady ┆ 98 ┆ 99 ┆ 100 ┆ 100 │
│ Karen ┆ 61 ┆ 58 ┆ 60 ┆ 60 │
└───────┴──────────────┴────────────────┴──────────────┴────────────────┘
If you end up with multiple values per cell, you can specify how to aggregate
them with `aggregate_function`:
>>> df = pl.DataFrame(
... {
... "ix": [1, 1, 2, 2, 1, 2],
... "col": ["a", "a", "a", "a", "b", "b"],
... "foo": [0, 1, 2, 2, 7, 1],
... "bar": [0, 2, 0, 0, 9, 4],
... }
... )
>>> df.pivot("col", index="ix", aggregate_function="sum")
shape: (2, 5)
┌─────┬───────┬───────┬───────┬───────┐
│ ix ┆ foo_a ┆ foo_b ┆ bar_a ┆ bar_b │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═══════╪═══════╪═══════╪═══════╡
│ 1 ┆ 1 ┆ 7 ┆ 2 ┆ 9 │
│ 2 ┆ 4 ┆ 1 ┆ 0 ┆ 4 │
└─────┴───────┴───────┴───────┴───────┘
You can also pass a custom aggregation function using
:meth:`polars.element`:
>>> df = pl.DataFrame(
... {
... "col1": ["a", "a", "a", "b", "b", "b"],
... "col2": ["x", "x", "x", "x", "y", "y"],
... "col3": [6, 7, 3, 2, 5, 7],
... }
... )
>>> df.pivot(
... "col2",
... index="col1",
... values="col3",
... aggregate_function=pl.element().tanh().mean(),
... )
shape: (2, 3)
┌──────┬──────────┬──────────┐
│ col1 ┆ x ┆ y │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞══════╪══════════╪══════════╡
│ a ┆ 0.998347 ┆ null │
│ b ┆ 0.964028 ┆ 0.999954 │
└──────┴──────────┴──────────┘
See Also
--------
LazyFrame.pivot
""" # noqa: W505
from polars.lazyframe.opt_flags import QueryOptFlags
on_cols: Sequence[Any] | pl.Series | pl.DataFrame
if on_columns is None:
cols = self.select(on).unique(maintain_order=True)
if sort_columns:
cols = cols.sort(on)
on_cols = cols
else:
on_cols = on_columns
return (
self.lazy()
.pivot(
on=on,
on_columns=on_cols,
index=index,
values=values,
aggregate_function=aggregate_function,
maintain_order=maintain_order,
separator=separator,
)
.collect(optimizations=QueryOptFlags._eager())
)
def unpivot(
self,
on: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None,
*,
index: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None,
variable_name: str | None = None,
value_name: str | None = None,
) -> DataFrame:
"""
Unpivot a DataFrame from wide to long format.
Optionally leaves identifiers set.
This function is useful to massage a DataFrame into a format where one or more
columns are identifier variables (index) while all other columns, considered
measured variables (on), are "unpivoted" to the row axis leaving just
two non-identifier columns, 'variable' and 'value'.
Parameters
----------
on
Column(s) or selector(s) to use as values variables; if `on`
is empty all columns that are not in `index` will be used.
index
Column(s) or selector(s) to use as identifier variables.
variable_name
Name to give to the `variable` column. Defaults to "variable"
value_name
Name to give to the `value` column. Defaults to "value"
Notes
-----
If you're coming from pandas, this is similar to `pandas.DataFrame.melt`,
but with `index` replacing `id_vars` and `on` replacing `value_vars`.
In other frameworks, you might know this operation as `pivot_longer`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": ["x", "y", "z"],
... "b": [1, 3, 5],
... "c": [2, 4, 6],
... }
... )
>>> import polars.selectors as cs
>>> df.unpivot(cs.numeric(), index="a")
shape: (6, 3)
┌─────┬──────────┬───────┐
│ a ┆ variable ┆ value │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 │
╞═════╪══════════╪═══════╡
│ x ┆ b ┆ 1 │
│ y ┆ b ┆ 3 │
│ z ┆ b ┆ 5 │
│ x ┆ c ┆ 2 │
│ y ┆ c ┆ 4 │
│ z ┆ c ┆ 6 │
└─────┴──────────┴───────┘
"""
on = [] if on is None else _expand_selectors(self, on)
index = [] if index is None else _expand_selectors(self, index)
return self._from_pydf(self._df.unpivot(on, index, value_name, variable_name))
def unstack(
self,
*,
step: int,
how: UnstackDirection = "vertical",
columns: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None,
fill_values: list[Any] | None = None,
) -> DataFrame:
"""
Unstack a long table to a wide form without doing an aggregation.
This can be much faster than a pivot, because it can skip the grouping phase.
Parameters
----------
step
Number of rows in the unstacked frame.
how : { 'vertical', 'horizontal' }
Direction of the unstack.
columns
Column name(s) or selector(s) to include in the operation.
If set to `None` (default), use all columns.
fill_values
Fill values that don't fit the new size with this value.
Examples
--------
>>> from string import ascii_uppercase
>>> df = pl.DataFrame(
... {
... "x": list(ascii_uppercase[0:8]),
... "y": pl.int_range(1, 9, eager=True),
... }
... ).with_columns(
... z=pl.int_ranges(pl.col("y"), pl.col("y") + 2, dtype=pl.UInt8),
... )
>>> df
shape: (8, 3)
┌─────┬─────┬──────────┐
│ x ┆ y ┆ z │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ list[u8] │
╞═════╪═════╪══════════╡
│ A ┆ 1 ┆ [1, 2] │
│ B ┆ 2 ┆ [2, 3] │
│ C ┆ 3 ┆ [3, 4] │
│ D ┆ 4 ┆ [4, 5] │
│ E ┆ 5 ┆ [5, 6] │
│ F ┆ 6 ┆ [6, 7] │
│ G ┆ 7 ┆ [7, 8] │
│ H ┆ 8 ┆ [8, 9] │
└─────┴─────┴──────────┘
>>> df.unstack(step=4, how="vertical")
shape: (4, 6)
┌─────┬─────┬─────┬─────┬──────────┬──────────┐
│ x_0 ┆ x_1 ┆ y_0 ┆ y_1 ┆ z_0 ┆ z_1 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ i64 ┆ list[u8] ┆ list[u8] │
╞═════╪═════╪═════╪═════╪══════════╪══════════╡
│ A ┆ E ┆ 1 ┆ 5 ┆ [1, 2] ┆ [5, 6] │
│ B ┆ F ┆ 2 ┆ 6 ┆ [2, 3] ┆ [6, 7] │
│ C ┆ G ┆ 3 ┆ 7 ┆ [3, 4] ┆ [7, 8] │
│ D ┆ H ┆ 4 ┆ 8 ┆ [4, 5] ┆ [8, 9] │
└─────┴─────┴─────┴─────┴──────────┴──────────┘
>>> df.unstack(step=2, how="horizontal")
shape: (4, 6)
┌─────┬─────┬─────┬─────┬──────────┬──────────┐
│ x_0 ┆ x_1 ┆ y_0 ┆ y_1 ┆ z_0 ┆ z_1 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ i64 ┆ list[u8] ┆ list[u8] │
╞═════╪═════╪═════╪═════╪══════════╪══════════╡
│ A ┆ B ┆ 1 ┆ 2 ┆ [1, 2] ┆ [2, 3] │
│ C ┆ D ┆ 3 ┆ 4 ┆ [3, 4] ┆ [4, 5] │
│ E ┆ F ┆ 5 ┆ 6 ┆ [5, 6] ┆ [6, 7] │
│ G ┆ H ┆ 7 ┆ 8 ┆ [7, 8] ┆ [8, 9] │
└─────┴─────┴─────┴─────┴──────────┴──────────┘
>>> import polars.selectors as cs
>>> df.unstack(step=5, columns=cs.numeric(), fill_values=0)
shape: (5, 2)
┌─────┬─────┐
│ y_0 ┆ y_1 │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 6 │
│ 2 ┆ 7 │
│ 3 ┆ 8 │
│ 4 ┆ 0 │
│ 5 ┆ 0 │
└─────┴─────┘
"""
import math
df = self.select(columns) if columns is not None else self
height = df.height
if how == "vertical":
n_rows = step
n_cols = math.ceil(height / n_rows)
else:
n_cols = step
n_rows = math.ceil(height / n_cols)
if n_fill := n_cols * n_rows - height:
if not isinstance(fill_values, list):
fill_values = [fill_values for _ in range(df.width)]
df = df.select(
s.extend_constant(next_fill, n_fill)
for s, next_fill in zip(df, fill_values)
)
if how == "horizontal":
df = (
df.with_columns(
(F.int_range(0, n_cols * n_rows, eager=True) % n_cols).alias(
"__sort_order"
),
)
.sort("__sort_order")
.drop("__sort_order")
)
zfill_val = math.floor(math.log10(n_cols)) + 1
slices = [
s.slice(slice_nbr * n_rows, n_rows).alias(
s.name + "_" + str(slice_nbr).zfill(zfill_val)
)
for s in df
for slice_nbr in range(n_cols)
]
return DataFrame(slices)
@overload
def partition_by(
self,
by: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*more_by: ColumnNameOrSelector,
maintain_order: bool = ...,
include_key: bool = ...,
as_dict: Literal[False] = ...,
) -> list[DataFrame]: ...
@overload
def partition_by(
self,
by: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*more_by: ColumnNameOrSelector,
maintain_order: bool = ...,
include_key: bool = ...,
as_dict: Literal[True],
) -> dict[tuple[Any, ...], DataFrame]: ...
@overload
def partition_by(
self,
by: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*more_by: ColumnNameOrSelector,
maintain_order: bool = ...,
include_key: bool = ...,
as_dict: bool,
) -> list[DataFrame] | dict[tuple[Any, ...], DataFrame]: ...
def partition_by(
self,
by: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*more_by: ColumnNameOrSelector,
maintain_order: bool = True,
include_key: bool = True,
as_dict: bool = False,
) -> list[DataFrame] | dict[tuple[Any, ...], DataFrame]:
"""
Group by the given columns and return the groups as separate dataframes.
Parameters
----------
by
Column name(s) or selector(s) to group by.
*more_by
Additional names of columns to group by, specified as positional arguments.
maintain_order
Ensure that the order of the groups is consistent with the input data.
This is slower than a default partition by operation.
include_key
Include the columns used to partition the DataFrame in the output.
as_dict
Return a dictionary instead of a list. The dictionary keys are tuples of
the distinct group values that identify each group.
Examples
--------
Pass a single column name to partition by that column.
>>> df = pl.DataFrame(
... {
... "a": ["a", "b", "a", "b", "c"],
... "b": [1, 2, 1, 3, 3],
... "c": [5, 4, 3, 2, 1],
... }
... )
>>> df.partition_by("a") # doctest: +IGNORE_RESULT
[shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ a ┆ 1 ┆ 5 │
│ a ┆ 1 ┆ 3 │
└─────┴─────┴─────┘,
shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ b ┆ 2 ┆ 4 │
│ b ┆ 3 ┆ 2 │
└─────┴─────┴─────┘,
shape: (1, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ c ┆ 3 ┆ 1 │
└─────┴─────┴─────┘]
Partition by multiple columns by either passing a list of column names, or by
specifying each column name as a positional argument.
>>> df.partition_by("a", "b") # doctest: +IGNORE_RESULT
[shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ a ┆ 1 ┆ 5 │
│ a ┆ 1 ┆ 3 │
└─────┴─────┴─────┘,
shape: (1, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ b ┆ 2 ┆ 4 │
└─────┴─────┴─────┘,
shape: (1, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ b ┆ 3 ┆ 2 │
└─────┴─────┴─────┘,
shape: (1, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ c ┆ 3 ┆ 1 │
└─────┴─────┴─────┘]
Return the partitions as a dictionary by specifying `as_dict=True`.
>>> import polars.selectors as cs
>>> df.partition_by(cs.string(), as_dict=True) # doctest: +IGNORE_RESULT
{('a',): shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ a ┆ 1 ┆ 5 │
│ a ┆ 1 ┆ 3 │
└─────┴─────┴─────┘,
('b',): shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ b ┆ 2 ┆ 4 │
│ b ┆ 3 ┆ 2 │
└─────┴─────┴─────┘,
('c',): shape: (1, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ c ┆ 3 ┆ 1 │
└─────┴─────┴─────┘}
"""
by_parsed = _expand_selectors(self, by, *more_by)
partitions = [
self._from_pydf(_df)
for _df in self._df.partition_by(by_parsed, maintain_order, include_key)
]
if as_dict:
if include_key:
names = [p.select(by_parsed).row(0) for p in partitions]
else:
if not maintain_order: # Group keys cannot be matched to partitions
msg = "cannot use `partition_by` with `maintain_order=False, include_key=False, as_dict=True`"
raise ValueError(msg)
names = self.select(by_parsed).unique(maintain_order=True).rows()
return dict(zip(names, partitions))
return partitions
def shift(self, n: int = 1, *, fill_value: IntoExpr | None = None) -> DataFrame:
"""
Shift values by the given number of indices.
Parameters
----------
n
Number of indices to shift forward. If a negative value is passed, values
are shifted in the opposite direction instead.
fill_value
Fill the resulting null values with this value. Accepts scalar expression
input. Non-expression inputs are parsed as literals.
Notes
-----
This method is similar to the `LAG` operation in SQL when the value for `n`
is positive. With a negative value for `n`, it is similar to `LEAD`.
Examples
--------
By default, values are shifted forward by one index.
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 4],
... "b": [5, 6, 7, 8],
... }
... )
>>> df.shift()
shape: (4, 2)
┌──────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪══════╡
│ null ┆ null │
│ 1 ┆ 5 │
│ 2 ┆ 6 │
│ 3 ┆ 7 │
└──────┴──────┘
Pass a negative value to shift in the opposite direction instead.
>>> df.shift(-2)
shape: (4, 2)
┌──────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪══════╡
│ 3 ┆ 7 │
│ 4 ┆ 8 │
│ null ┆ null │
│ null ┆ null │
└──────┴──────┘
Specify `fill_value` to fill the resulting null values.
>>> df.shift(-2, fill_value=100)
shape: (4, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 3 ┆ 7 │
│ 4 ┆ 8 │
│ 100 ┆ 100 │
│ 100 ┆ 100 │
└─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.shift(n, fill_value=fill_value)
.collect(optimizations=QueryOptFlags._eager())
)
def is_duplicated(self) -> Series:
"""
Get a mask of all duplicated rows in this DataFrame.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 1],
... "b": ["x", "y", "z", "x"],
... }
... )
>>> df.is_duplicated()
shape: (4,)
Series: '' [bool]
[
true
false
false
true
]
This mask can be used to visualize the duplicated lines like this:
>>> df.filter(df.is_duplicated())
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═════╡
│ 1 ┆ x │
│ 1 ┆ x │
└─────┴─────┘
"""
return wrap_s(self._df.is_duplicated())
def is_unique(self) -> Series:
"""
Get a mask of all unique rows in this DataFrame.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 1],
... "b": ["x", "y", "z", "x"],
... }
... )
>>> df.is_unique()
shape: (4,)
Series: '' [bool]
[
false
true
true
false
]
This mask can be used to visualize the unique lines like this:
>>> df.filter(df.is_unique())
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═════╡
│ 2 ┆ y │
│ 3 ┆ z │
└─────┴─────┘
"""
return wrap_s(self._df.is_unique())
def lazy(self) -> LazyFrame:
"""
Start a lazy query from this point. This returns a `LazyFrame` object.
Operations on a `LazyFrame` are not executed until this is triggered
by calling one of:
* :meth:`.collect() <polars.LazyFrame.collect>`
(run on all data)
* :meth:`.explain() <polars.LazyFrame.explain>`
(print the query plan)
* :meth:`.show_graph() <polars.LazyFrame.show_graph>`
(show the query plan as graphviz graph)
* :meth:`.collect_schema() <polars.LazyFrame.collect_schema>`
(return the final frame schema)
Lazy operations are recommended because they allow for query optimization and
additional parallelism.
Returns
-------
LazyFrame
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [None, 2, 3, 4],
... "b": [0.5, None, 2.5, 13],
... "c": [True, True, False, None],
... }
... )
>>> df.lazy()
<LazyFrame at ...>
"""
return wrap_ldf(self._df.lazy())
def select(
self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr
) -> DataFrame:
"""
Select columns from this DataFrame.
Parameters
----------
*exprs
Column(s) to select, specified as positional arguments.
Accepts expression input. Strings are parsed as column names,
other non-expression inputs are parsed as literals.
**named_exprs
Additional columns to select, specified as keyword arguments.
The columns will be renamed to the keyword used.
Examples
--------
Pass the name of a column to select that column.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.select("foo")
shape: (3, 1)
┌─────┐
│ foo │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ 2 │
│ 3 │
└─────┘
Multiple columns can be selected by passing a list of column names.
>>> df.select(["foo", "bar"])
shape: (3, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 6 │
│ 2 ┆ 7 │
│ 3 ┆ 8 │
└─────┴─────┘
Multiple columns can also be selected using positional arguments instead of a
list. Expressions are also accepted.
>>> df.select(pl.col("foo"), pl.col("bar") + 1)
shape: (3, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 7 │
│ 2 ┆ 8 │
│ 3 ┆ 9 │
└─────┴─────┘
Use keyword arguments to easily name your expression inputs.
>>> df.select(threshold=pl.when(pl.col("foo") > 2).then(10).otherwise(0))
shape: (3, 1)
┌───────────┐
│ threshold │
│ --- │
│ i32 │
╞═══════════╡
│ 0 │
│ 0 │
│ 10 │
└───────────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.select(*exprs, **named_exprs)
.collect(optimizations=QueryOptFlags._eager())
)
def select_seq(
self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr
) -> DataFrame:
"""
Select columns from this DataFrame.
This will run all expression sequentially instead of in parallel.
Use this when the work per expression is cheap.
Parameters
----------
*exprs
Column(s) to select, specified as positional arguments.
Accepts expression input. Strings are parsed as column names,
other non-expression inputs are parsed as literals.
**named_exprs
Additional columns to select, specified as keyword arguments.
The columns will be renamed to the keyword used.
See Also
--------
select
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.select_seq(*exprs, **named_exprs)
.collect(optimizations=QueryOptFlags._eager())
)
def with_columns(
self,
*exprs: IntoExpr | Iterable[IntoExpr],
**named_exprs: IntoExpr,
) -> DataFrame:
"""
Add columns to this DataFrame.
Added columns will replace existing columns with the same name.
Parameters
----------
*exprs
Column(s) to add, specified as positional arguments.
Accepts expression input. Strings are parsed as column names, other
non-expression inputs are parsed as literals.
**named_exprs
Additional columns to add, specified as keyword arguments.
The columns will be renamed to the keyword used.
Returns
-------
DataFrame
A new DataFrame with the columns added.
Notes
-----
Creating a new DataFrame using this method does not create a new copy of
existing data.
Examples
--------
Pass an expression to add it as a new column.
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 4],
... "b": [0.5, 4, 10, 13],
... "c": [True, True, False, True],
... }
... )
>>> df.with_columns((pl.col("a") ** 2).alias("a^2"))
shape: (4, 4)
┌─────┬──────┬───────┬─────┐
│ a ┆ b ┆ c ┆ a^2 │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ bool ┆ i64 │
╞═════╪══════╪═══════╪═════╡
│ 1 ┆ 0.5 ┆ true ┆ 1 │
│ 2 ┆ 4.0 ┆ true ┆ 4 │
│ 3 ┆ 10.0 ┆ false ┆ 9 │
│ 4 ┆ 13.0 ┆ true ┆ 16 │
└─────┴──────┴───────┴─────┘
Added columns will replace existing columns with the same name.
>>> df.with_columns(pl.col("a").cast(pl.Float64))
shape: (4, 3)
┌─────┬──────┬───────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ bool │
╞═════╪══════╪═══════╡
│ 1.0 ┆ 0.5 ┆ true │
│ 2.0 ┆ 4.0 ┆ true │
│ 3.0 ┆ 10.0 ┆ false │
│ 4.0 ┆ 13.0 ┆ true │
└─────┴──────┴───────┘
Multiple columns can be added using positional arguments.
>>> df.with_columns(
... (pl.col("a") ** 2).alias("a^2"),
... (pl.col("b") / 2).alias("b/2"),
... (pl.col("c").not_()).alias("not c"),
... )
shape: (4, 6)
┌─────┬──────┬───────┬─────┬──────┬───────┐
│ a ┆ b ┆ c ┆ a^2 ┆ b/2 ┆ not c │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ bool ┆ i64 ┆ f64 ┆ bool │
╞═════╪══════╪═══════╪═════╪══════╪═══════╡
│ 1 ┆ 0.5 ┆ true ┆ 1 ┆ 0.25 ┆ false │
│ 2 ┆ 4.0 ┆ true ┆ 4 ┆ 2.0 ┆ false │
│ 3 ┆ 10.0 ┆ false ┆ 9 ┆ 5.0 ┆ true │
│ 4 ┆ 13.0 ┆ true ┆ 16 ┆ 6.5 ┆ false │
└─────┴──────┴───────┴─────┴──────┴───────┘
Multiple columns can also be added by passing a list of expressions.
>>> df.with_columns(
... [
... (pl.col("a") ** 2).alias("a^2"),
... (pl.col("b") / 2).alias("b/2"),
... (pl.col("c").not_()).alias("not c"),
... ]
... )
shape: (4, 6)
┌─────┬──────┬───────┬─────┬──────┬───────┐
│ a ┆ b ┆ c ┆ a^2 ┆ b/2 ┆ not c │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ bool ┆ i64 ┆ f64 ┆ bool │
╞═════╪══════╪═══════╪═════╪══════╪═══════╡
│ 1 ┆ 0.5 ┆ true ┆ 1 ┆ 0.25 ┆ false │
│ 2 ┆ 4.0 ┆ true ┆ 4 ┆ 2.0 ┆ false │
│ 3 ┆ 10.0 ┆ false ┆ 9 ┆ 5.0 ┆ true │
│ 4 ┆ 13.0 ┆ true ┆ 16 ┆ 6.5 ┆ false │
└─────┴──────┴───────┴─────┴──────┴───────┘
Use keyword arguments to easily name your expression inputs.
>>> df.with_columns(
... ab=pl.col("a") * pl.col("b"),
... not_c=pl.col("c").not_(),
... )
shape: (4, 5)
┌─────┬──────┬───────┬──────┬───────┐
│ a ┆ b ┆ c ┆ ab ┆ not_c │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ bool ┆ f64 ┆ bool │
╞═════╪══════╪═══════╪══════╪═══════╡
│ 1 ┆ 0.5 ┆ true ┆ 0.5 ┆ false │
│ 2 ┆ 4.0 ┆ true ┆ 8.0 ┆ false │
│ 3 ┆ 10.0 ┆ false ┆ 30.0 ┆ true │
│ 4 ┆ 13.0 ┆ true ┆ 52.0 ┆ false │
└─────┴──────┴───────┴──────┴───────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.with_columns(*exprs, **named_exprs)
.collect(optimizations=QueryOptFlags._eager())
)
def with_columns_seq(
self,
*exprs: IntoExpr | Iterable[IntoExpr],
**named_exprs: IntoExpr,
) -> DataFrame:
"""
Add columns to this DataFrame.
Added columns will replace existing columns with the same name.
This will run all expression sequentially instead of in parallel.
Use this when the work per expression is cheap.
Parameters
----------
*exprs
Column(s) to add, specified as positional arguments.
Accepts expression input. Strings are parsed as column names, other
non-expression inputs are parsed as literals.
**named_exprs
Additional columns to add, specified as keyword arguments.
The columns will be renamed to the keyword used.
Returns
-------
DataFrame
A new DataFrame with the columns added.
See Also
--------
with_columns
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.with_columns_seq(*exprs, **named_exprs)
.collect(optimizations=QueryOptFlags._eager())
)
@overload
def n_chunks(self, strategy: Literal["first"] = ...) -> int: ...
@overload
def n_chunks(self, strategy: Literal["all"]) -> list[int]: ...
def n_chunks(self, strategy: Literal["first", "all"] = "first") -> int | list[int]:
"""
Get number of chunks used by the ChunkedArrays of this DataFrame.
Parameters
----------
strategy : {'first', 'all'}
Return the number of chunks of the 'first' column,
or 'all' columns in this DataFrame.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 4],
... "b": [0.5, 4, 10, 13],
... "c": [True, True, False, True],
... }
... )
>>> df.n_chunks()
1
>>> df.n_chunks(strategy="all")
[1, 1, 1]
"""
if strategy == "first":
return self._df.n_chunks()
elif strategy == "all":
return [s.n_chunks() for s in self.__iter__()]
else:
msg = (
f"unexpected input for `strategy`: {strategy!r}"
f"\n\nChoose one of {{'first', 'all'}}"
)
raise ValueError(msg)
def max(self) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their maximum value.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.max()
shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 3 ┆ 8 ┆ c │
└─────┴─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().max().collect(optimizations=QueryOptFlags._eager())
def max_horizontal(self) -> Series:
"""
Get the maximum value horizontally across columns.
Returns
-------
Series
A Series named `"max"`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [4.0, 5.0, 6.0],
... }
... )
>>> df.max_horizontal()
shape: (3,)
Series: 'max' [f64]
[
4.0
5.0
6.0
]
"""
return self.select(max=F.max_horizontal(F.all())).to_series()
def min(self) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their minimum value.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.min()
shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
└─────┴─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().min().collect(optimizations=QueryOptFlags._eager())
def min_horizontal(self) -> Series:
"""
Get the minimum value horizontally across columns.
Returns
-------
Series
A Series named `"min"`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [4.0, 5.0, 6.0],
... }
... )
>>> df.min_horizontal()
shape: (3,)
Series: 'min' [f64]
[
1.0
2.0
3.0
]
"""
return self.select(min=F.min_horizontal(F.all())).to_series()
def sum(self) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their sum value.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.sum()
shape: (1, 3)
┌─────┬─────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪══════╡
│ 6 ┆ 21 ┆ null │
└─────┴─────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().sum().collect(optimizations=QueryOptFlags._eager())
def sum_horizontal(self, *, ignore_nulls: bool = True) -> Series:
"""
Sum all values horizontally across columns.
Parameters
----------
ignore_nulls
Ignore null values (default).
If set to `False`, any null value in the input will lead to a null output.
Returns
-------
Series
A Series named `"sum"`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [4.0, 5.0, 6.0],
... }
... )
>>> df.sum_horizontal()
shape: (3,)
Series: 'sum' [f64]
[
5.0
7.0
9.0
]
"""
return self.select(
sum=F.sum_horizontal(F.all(), ignore_nulls=ignore_nulls)
).to_series()
def mean(self) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their mean value.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... "spam": [True, False, None],
... }
... )
>>> df.mean()
shape: (1, 4)
┌─────┬─────┬──────┬──────┐
│ foo ┆ bar ┆ ham ┆ spam │
│ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str ┆ f64 │
╞═════╪═════╪══════╪══════╡
│ 2.0 ┆ 7.0 ┆ null ┆ 0.5 │
└─────┴─────┴──────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().mean().collect(optimizations=QueryOptFlags._eager())
def mean_horizontal(self, *, ignore_nulls: bool = True) -> Series:
"""
Take the mean of all values horizontally across columns.
Parameters
----------
ignore_nulls
Ignore null values (default).
If set to `False`, any null value in the input will lead to a null output.
Returns
-------
Series
A Series named `"mean"`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [4.0, 5.0, 6.0],
... }
... )
>>> df.mean_horizontal()
shape: (3,)
Series: 'mean' [f64]
[
2.5
3.5
4.5
]
"""
return self.select(
mean=F.mean_horizontal(F.all(), ignore_nulls=ignore_nulls)
).to_series()
def std(self, ddof: int = 1) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their standard deviation value.
Parameters
----------
ddof
“Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof,
where N represents the number of elements.
By default ddof is 1.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.std()
shape: (1, 3)
┌─────┬─────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str │
╞═════╪═════╪══════╡
│ 1.0 ┆ 1.0 ┆ null │
└─────┴─────┴──────┘
>>> df.std(ddof=0)
shape: (1, 3)
┌──────────┬──────────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str │
╞══════════╪══════════╪══════╡
│ 0.816497 ┆ 0.816497 ┆ null │
└──────────┴──────────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().std(ddof).collect(optimizations=QueryOptFlags._eager())
def var(self, ddof: int = 1) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their variance value.
Parameters
----------
ddof
“Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof,
where N represents the number of elements.
By default ddof is 1.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.var()
shape: (1, 3)
┌─────┬─────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str │
╞═════╪═════╪══════╡
│ 1.0 ┆ 1.0 ┆ null │
└─────┴─────┴──────┘
>>> df.var(ddof=0)
shape: (1, 3)
┌──────────┬──────────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str │
╞══════════╪══════════╪══════╡
│ 0.666667 ┆ 0.666667 ┆ null │
└──────────┴──────────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().var(ddof).collect(optimizations=QueryOptFlags._eager())
def median(self) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their median value.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.median()
shape: (1, 3)
┌─────┬─────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str │
╞═════╪═════╪══════╡
│ 2.0 ┆ 7.0 ┆ null │
└─────┴─────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().median().collect(optimizations=QueryOptFlags._eager())
def product(self) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their product values.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3],
... "b": [0.5, 4, 10],
... "c": [True, True, False],
... }
... )
>>> df.product()
shape: (1, 3)
┌─────┬──────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ i64 │
╞═════╪══════╪═════╡
│ 6 ┆ 20.0 ┆ 0 │
└─────┴──────┴─────┘
"""
exprs = []
for name, dt in self.schema.items():
if dt.is_numeric() or isinstance(dt, Boolean):
exprs.append(F.col(name).product())
else:
exprs.append(F.lit(None).alias(name))
return self.select(exprs)
def quantile(
self, quantile: float, interpolation: QuantileMethod = "nearest"
) -> DataFrame:
"""
Aggregate the columns of this DataFrame to their quantile value.
Parameters
----------
quantile
Quantile between 0.0 and 1.0.
interpolation : {'nearest', 'higher', 'lower', 'midpoint', 'linear', 'equiprobable'}
Interpolation method.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.quantile(0.5, "nearest")
shape: (1, 3)
┌─────┬─────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ str │
╞═════╪═════╪══════╡
│ 2.0 ┆ 7.0 ┆ null │
└─────┴─────┴──────┘
""" # noqa: W505
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.quantile(quantile, interpolation)
.collect(optimizations=QueryOptFlags._eager())
)
def to_dummies(
self,
columns: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None,
*,
separator: str = "_",
drop_first: bool = False,
drop_nulls: bool = False,
) -> DataFrame:
"""
Convert categorical variables into dummy/indicator variables.
Parameters
----------
columns
Column name(s) or selector(s) that should be converted to dummy
variables. If set to `None` (default), convert all columns.
separator
Separator/delimiter used when generating column names.
drop_first
Remove the first category from the variables being encoded.
drop_nulls
If there are `None` values in the series, a `null` column is not generated
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2],
... "bar": [3, 4],
... "ham": ["a", "b"],
... }
... )
>>> df.to_dummies()
shape: (2, 6)
┌───────┬───────┬───────┬───────┬───────┬───────┐
│ foo_1 ┆ foo_2 ┆ bar_3 ┆ bar_4 ┆ ham_a ┆ ham_b │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u8 ┆ u8 ┆ u8 ┆ u8 ┆ u8 ┆ u8 │
╞═══════╪═══════╪═══════╪═══════╪═══════╪═══════╡
│ 1 ┆ 0 ┆ 1 ┆ 0 ┆ 1 ┆ 0 │
│ 0 ┆ 1 ┆ 0 ┆ 1 ┆ 0 ┆ 1 │
└───────┴───────┴───────┴───────┴───────┴───────┘
>>> df.to_dummies(drop_first=True)
shape: (2, 3)
┌───────┬───────┬───────┐
│ foo_2 ┆ bar_4 ┆ ham_b │
│ --- ┆ --- ┆ --- │
│ u8 ┆ u8 ┆ u8 │
╞═══════╪═══════╪═══════╡
│ 0 ┆ 0 ┆ 0 │
│ 1 ┆ 1 ┆ 1 │
└───────┴───────┴───────┘
>>> import polars.selectors as cs
>>> df.to_dummies(cs.integer(), separator=":")
shape: (2, 5)
┌───────┬───────┬───────┬───────┬─────┐
│ foo:1 ┆ foo:2 ┆ bar:3 ┆ bar:4 ┆ ham │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u8 ┆ u8 ┆ u8 ┆ u8 ┆ str │
╞═══════╪═══════╪═══════╪═══════╪═════╡
│ 1 ┆ 0 ┆ 1 ┆ 0 ┆ a │
│ 0 ┆ 1 ┆ 0 ┆ 1 ┆ b │
└───────┴───────┴───────┴───────┴─────┘
>>> df.to_dummies(cs.integer(), drop_first=True, separator=":")
shape: (2, 3)
┌───────┬───────┬─────┐
│ foo:2 ┆ bar:4 ┆ ham │
│ --- ┆ --- ┆ --- │
│ u8 ┆ u8 ┆ str │
╞═══════╪═══════╪═════╡
│ 0 ┆ 0 ┆ a │
│ 1 ┆ 1 ┆ b │
└───────┴───────┴─────┘
"""
if columns is not None:
columns = _expand_selectors(self, columns)
return self._from_pydf(
self._df.to_dummies(columns, separator, drop_first, drop_nulls)
)
def unique(
self,
subset: IntoExpr | Collection[IntoExpr] | None = None,
*,
keep: UniqueKeepStrategy = "any",
maintain_order: bool = False,
) -> DataFrame:
r"""
Drop duplicate rows from this DataFrame.
Parameters
----------
subset
Column name(s), selector(s), or expressions to consider when identifying
duplicate rows. If set to `None` (default), all columns are considered.
keep : {'first', 'last', 'any', 'none'}
Which of the duplicate rows to keep.
* 'any': Does not give any guarantee of which row is kept.
This allows more optimizations.
* 'none': Don't keep duplicate rows.
* 'first': Keep the first unique row.
* 'last': Keep the last unique row.
maintain_order
Keep the same order as the original DataFrame. This is more expensive
to compute. Settings this to `True` blocks the possibility to run on
the streaming engine.
Returns
-------
DataFrame
DataFrame with unique rows.
Warnings
--------
This method will fail if there is a column of type `List` in the DataFrame (or
in the "subset" parameter).
Notes
-----
If you're coming from Pandas, this is similar to
`pandas.DataFrame.drop_duplicates`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3, 1, 1],
... "bar": ["a", "a", "a", "x", "x"],
... "ham": ["b", "b", "b", "y", "y"],
... }
... )
By default, all columns are considered when determining which rows are unique:
>>> df.unique(maintain_order=True)
shape: (4, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ a ┆ b │
│ 2 ┆ a ┆ b │
│ 3 ┆ a ┆ b │
│ 1 ┆ x ┆ y │
└─────┴─────┴─────┘
We can also consider only a subset of columns when determining uniqueness,
controlling which row we keep when duplicates are found:
>>> df.unique(subset="foo", keep="first", maintain_order=True)
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ a ┆ b │
│ 2 ┆ a ┆ b │
│ 3 ┆ a ┆ b │
└─────┴─────┴─────┘
>>> df.unique(subset="foo", keep="last", maintain_order=True)
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞═════╪═════╪═════╡
│ 2 ┆ a ┆ b │
│ 3 ┆ a ┆ b │
│ 1 ┆ x ┆ y │
└─────┴─────┴─────┘
>>> df.unique(subset="foo", keep="none", maintain_order=True)
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞═════╪═════╪═════╡
│ 2 ┆ a ┆ b │
│ 3 ┆ a ┆ b │
└─────┴─────┴─────┘
Selectors can be used to define the "subset" parameter:
>>> import polars.selectors as cs
>>> df.unique(subset=cs.string(), maintain_order=True)
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ a ┆ b │
│ 1 ┆ x ┆ y │
└─────┴─────┴─────┘
We can also use an arbitrary expression in the "subset" parameter; in this
example we use the part of the label in front of ":" to determine uniqueness:
>>> df = pl.DataFrame(
... {
... "label": ["xx:1", "xx:2", "yy:3", "yy:4"],
... "value": [100, 200, 300, 400],
... }
... )
>>> df.unique(
... subset=pl.col("label").str.extract(r"^(\w+):"),
... maintain_order=True,
... keep="first",
... )
shape: (2, 2)
┌───────┬───────┐
│ label ┆ value │
│ --- ┆ --- │
│ str ┆ i64 │
╞═══════╪═══════╡
│ xx:1 ┆ 100 │
│ yy:3 ┆ 300 │
└───────┴───────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.unique(subset=subset, keep=keep, maintain_order=maintain_order)
.collect(optimizations=QueryOptFlags._eager())
)
def n_unique(self, subset: str | Expr | Sequence[str | Expr] | None = None) -> int:
"""
Return the number of unique rows, or the number of unique row-subsets.
Parameters
----------
subset
One or more columns/expressions that define what to count;
omit to return the count of unique rows.
Notes
-----
This method operates at the `DataFrame` level; to operate on subsets at the
expression level you can make use of struct-packing instead, for example:
>>> expr_unique_subset = pl.struct("a", "b").n_unique()
If instead you want to count the number of unique values per-column, you can
also use expression-level syntax to return a new frame containing that result:
>>> df = pl.DataFrame(
... [[1, 2, 3], [1, 2, 4]], schema=["a", "b", "c"], orient="row"
... )
>>> df_nunique = df.select(pl.all().n_unique())
In aggregate context there is also an equivalent method for returning the
unique values per-group:
>>> df_agg_nunique = df.group_by("a").n_unique()
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 1, 2, 3, 4, 5],
... "b": [0.5, 0.5, 1.0, 2.0, 3.0, 3.0],
... "c": [True, True, True, False, True, True],
... }
... )
>>> df.n_unique()
5
Simple columns subset.
>>> df.n_unique(subset=["b", "c"])
4
Expression subset.
>>> df.n_unique(
... subset=[
... (pl.col("a") // 2),
... (pl.col("c") | (pl.col("b") >= 2)),
... ],
... )
3
"""
if isinstance(subset, str):
expr = F.col(subset)
elif isinstance(subset, pl.Expr):
expr = subset
elif isinstance(subset, Sequence) and len(subset) == 1:
expr = wrap_expr(parse_into_expression(subset[0]))
else:
struct_fields = F.all() if (subset is None) else subset
expr = F.struct(struct_fields)
from polars.lazyframe.opt_flags import QueryOptFlags
df = (
self.lazy()
.select(expr.n_unique())
.collect(optimizations=QueryOptFlags._eager())
)
return 0 if df.is_empty() else df.row(0)[0]
@deprecated(
"`DataFrame.approx_n_unique` is deprecated; "
"use `select(pl.all().approx_n_unique())` instead."
)
def approx_n_unique(self) -> DataFrame:
"""
Approximate count of unique values.
.. deprecated:: 0.20.11
Use the `select(pl.all().approx_n_unique())` method instead.
This is done using the HyperLogLog++ algorithm for cardinality estimation.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 4],
... "b": [1, 2, 1, 1],
... }
... )
>>> df.approx_n_unique() # doctest: +SKIP
shape: (1, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═════╪═════╡
│ 4 ┆ 2 │
└─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy().approx_n_unique().collect(optimizations=QueryOptFlags._eager())
)
def rechunk(self) -> DataFrame:
"""
Rechunk the data in this DataFrame to a contiguous allocation.
This will make sure all subsequent operations have optimal and predictable
performance.
"""
return self._from_pydf(self._df.rechunk())
def null_count(self) -> DataFrame:
"""
Create a new DataFrame that shows the null counts per column.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, None, 3],
... "bar": [6, 7, None],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.null_count()
shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ u32 │
╞═════╪═════╪═════╡
│ 1 ┆ 1 ┆ 0 │
└─────┴─────┴─────┘
"""
return self._from_pydf(self._df.null_count())
def sample(
self,
n: int | Series | None = None,
*,
fraction: float | Series | None = None,
with_replacement: bool = False,
shuffle: bool = False,
seed: int | None = None,
) -> DataFrame:
"""
Sample from this DataFrame.
Parameters
----------
n
Number of items to return. Cannot be used with `fraction`. Defaults to 1 if
`fraction` is None.
fraction
Fraction of items to return. Cannot be used with `n`.
with_replacement
Allow values to be sampled more than once.
shuffle
If set to True, the order of the sampled rows will be shuffled. If
set to False (default), the order of the returned rows will be
neither stable nor fully random.
seed
Seed for the random number generator. If set to None (default), a
random seed is generated for each sample operation.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.sample(n=2, seed=0) # doctest: +IGNORE_RESULT
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 3 ┆ 8 ┆ c │
│ 2 ┆ 7 ┆ b │
└─────┴─────┴─────┘
"""
if n is not None and fraction is not None:
msg = "cannot specify both `n` and `fraction`"
raise ValueError(msg)
if seed is None:
seed = random.randint(0, 10000)
if n is None and fraction is not None:
if not isinstance(fraction, pl.Series):
fraction = pl.Series("frac", [fraction])
return self._from_pydf(
self._df.sample_frac(fraction._s, with_replacement, shuffle, seed)
)
if n is None:
n = 1
if not isinstance(n, pl.Series):
n = pl.Series("", [n])
return self._from_pydf(self._df.sample_n(n._s, with_replacement, shuffle, seed))
def fold(self, operation: Callable[[Series, Series], Series]) -> Series:
"""
Apply a horizontal reduction on a DataFrame.
This can be used to effectively determine aggregations on a row level, and can
be applied to any DataType that can be supercast (cast to a similar parent
type).
An example of the supercast rules when applying an arithmetic operation on two
DataTypes are for instance:
- Int8 + String = String
- Float32 + Int64 = Float32
- Float32 + Float64 = Float64
Examples
--------
A horizontal sum operation:
>>> df = pl.DataFrame(
... {
... "a": [2, 1, 3],
... "b": [1, 2, 3],
... "c": [1.0, 2.0, 3.0],
... }
... )
>>> df.fold(lambda s1, s2: s1 + s2)
shape: (3,)
Series: 'a' [f64]
[
4.0
5.0
9.0
]
A horizontal minimum operation:
>>> df = pl.DataFrame({"a": [2, 1, 3], "b": [1, 2, 3], "c": [1.0, 2.0, 3.0]})
>>> df.fold(lambda s1, s2: s1.zip_with(s1 < s2, s2))
shape: (3,)
Series: 'a' [f64]
[
1.0
1.0
3.0
]
A horizontal string concatenation:
>>> df = pl.DataFrame(
... {
... "a": ["foo", "bar", None],
... "b": [1, 2, 3],
... "c": [1.0, 2.0, 3.0],
... }
... )
>>> df.fold(lambda s1, s2: s1 + s2)
shape: (3,)
Series: 'a' [str]
[
"foo11.0"
"bar22.0"
null
]
A horizontal boolean or, similar to a row-wise .any():
>>> df = pl.DataFrame(
... {
... "a": [False, False, True],
... "b": [False, True, False],
... }
... )
>>> df.fold(lambda s1, s2: s1 | s2)
shape: (3,)
Series: 'a' [bool]
[
false
true
true
]
Parameters
----------
operation
function that takes two `Series` and returns a `Series`.
"""
acc = self.to_series(0)
for i in range(1, self.width):
acc = operation(acc, self.to_series(i))
return acc
@overload
def row(
self,
index: int | None = ...,
*,
by_predicate: Expr | None = ...,
named: Literal[False] = ...,
) -> tuple[Any, ...]: ...
@overload
def row(
self,
index: int | None = ...,
*,
by_predicate: Expr | None = ...,
named: Literal[True],
) -> dict[str, Any]: ...
def row(
self,
index: int | None = None,
*,
by_predicate: Expr | None = None,
named: bool = False,
) -> tuple[Any, ...] | dict[str, Any]:
"""
Get the values of a single row, either by index or by predicate.
Parameters
----------
index
Row index.
by_predicate
Select the row according to a given expression/predicate.
named
Return a dictionary instead of a tuple. The dictionary is a mapping of
column name to row value. This is more expensive than returning a regular
tuple, but allows for accessing values by column name.
Returns
-------
tuple (default) or dictionary of row values
Notes
-----
The `index` and `by_predicate` params are mutually exclusive. Additionally,
to ensure clarity, the `by_predicate` parameter must be supplied by keyword.
When using `by_predicate` it is an error condition if anything other than
one row is returned; more than one row raises `TooManyRowsReturnedError`, and
zero rows will raise `NoRowsReturnedError` (both inherit from `RowsError`).
Warnings
--------
You should NEVER use this method to iterate over a DataFrame; if you require
row-iteration you should strongly prefer use of `iter_rows()` instead.
See Also
--------
iter_rows : Row iterator over frame data (does not materialise all rows).
rows : Materialise all frame data as a list of rows (potentially expensive).
item: Return dataframe element as a scalar.
Examples
--------
Specify an index to return the row at the given index as a tuple.
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.row(2)
(3, 8, 'c')
Specify `named=True` to get a dictionary instead with a mapping of column
names to row values.
>>> df.row(2, named=True)
{'foo': 3, 'bar': 8, 'ham': 'c'}
Use `by_predicate` to return the row that matches the given predicate.
>>> df.row(by_predicate=(pl.col("ham") == "b"))
(2, 7, 'b')
"""
if index is None and by_predicate is None:
if self.height == 1:
index = 0
else:
msg = (
'can only call `.row()` without "index" or "by_predicate" values '
f"if the DataFrame has a single row; shape={self.shape!r}"
)
raise ValueError(msg)
elif index is not None and by_predicate is not None:
msg = "cannot set both 'index' and 'by_predicate'; mutually exclusive"
raise ValueError(msg)
elif isinstance(index, pl.Expr):
msg = "expressions should be passed to the `by_predicate` parameter"
raise TypeError(msg)
if index is not None:
row = self._df.row_tuple(index)
if named:
return dict(zip(self.columns, row))
else:
return row
elif by_predicate is not None:
if not isinstance(by_predicate, pl.Expr):
msg = f"expected `by_predicate` to be an expression, got {qualified_type_name(by_predicate)!r}"
raise TypeError(msg)
rows = self.filter(by_predicate).rows()
n_rows = len(rows)
if n_rows > 1:
msg = f"predicate <{by_predicate!s}> returned {n_rows} rows"
raise TooManyRowsReturnedError(msg)
elif n_rows == 0:
msg = f"predicate <{by_predicate!s}> returned no rows"
raise NoRowsReturnedError(msg)
row = rows[0]
if named:
return dict(zip(self.columns, row))
else:
return row
else:
msg = "one of `index` or `by_predicate` must be set"
raise ValueError(msg)
@overload
def rows(self, *, named: Literal[False] = ...) -> list[tuple[Any, ...]]: ...
@overload
def rows(self, *, named: Literal[True]) -> list[dict[str, Any]]: ...
def rows(
self, *, named: bool = False
) -> list[tuple[Any, ...]] | list[dict[str, Any]]:
"""
Returns all data in the DataFrame as a list of rows of python-native values.
By default, each row is returned as a tuple of values given in the same order
as the frame columns. Setting `named=True` will return rows of dictionaries
instead.
Parameters
----------
named
Return dictionaries instead of tuples. The dictionaries are a mapping of
column name to row value. This is more expensive than returning a regular
tuple, but allows for accessing values by column name.
Notes
-----
If you have `ns`-precision temporal values you should be aware that Python
natively only supports up to `μs`-precision; `ns`-precision values will be
truncated to microseconds on conversion to Python. If this matters to your
use-case you should export to a different format (such as Arrow or NumPy).
Warnings
--------
Row-iteration is not optimal as the underlying data is stored in columnar form;
where possible, prefer export via one of the dedicated export/output methods.
You should also consider using `iter_rows` instead, to avoid materialising all
the data at once; there is little performance difference between the two, but
peak memory can be reduced if processing rows in batches.
Returns
-------
list of row value tuples (default), or list of dictionaries (if `named=True`).
See Also
--------
iter_rows : Row iterator over frame data (does not materialise all rows).
rows_by_key : Materialises frame data as a key-indexed dictionary.
Examples
--------
>>> df = pl.DataFrame(
... {
... "x": ["a", "b", "b", "a"],
... "y": [1, 2, 3, 4],
... "z": [0, 3, 6, 9],
... }
... )
>>> df.rows()
[('a', 1, 0), ('b', 2, 3), ('b', 3, 6), ('a', 4, 9)]
>>> df.rows(named=True)
[{'x': 'a', 'y': 1, 'z': 0},
{'x': 'b', 'y': 2, 'z': 3},
{'x': 'b', 'y': 3, 'z': 6},
{'x': 'a', 'y': 4, 'z': 9}]
"""
if named:
# Load these into the local namespace for a minor performance boost
dict_, zip_, columns = dict, zip, self.columns
return [dict_(zip_(columns, row)) for row in self._df.row_tuples()]
else:
return self._df.row_tuples()
@overload
def rows_by_key(
self,
key: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*,
named: Literal[False] = ...,
include_key: bool = ...,
unique: Literal[False] = ...,
) -> dict[Any, list[Any]]: ...
@overload
def rows_by_key(
self,
key: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*,
named: Literal[False] = ...,
include_key: bool = ...,
unique: Literal[True],
) -> dict[Any, Any]: ...
@overload
def rows_by_key(
self,
key: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*,
named: Literal[True],
include_key: bool = ...,
unique: Literal[False] = ...,
) -> dict[Any, list[dict[str, Any]]]: ...
@overload
def rows_by_key(
self,
key: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*,
named: Literal[True],
include_key: bool = ...,
unique: Literal[True],
) -> dict[Any, dict[str, Any]]: ...
def rows_by_key(
self,
key: ColumnNameOrSelector | Sequence[ColumnNameOrSelector],
*,
named: bool = False,
include_key: bool = False,
unique: bool = False,
) -> dict[Any, Any]:
"""
Returns all data as a dictionary of python-native values keyed by some column.
This method is like `rows`, but instead of returning rows in a flat list, rows
are grouped by the values in the `key` column(s) and returned as a dictionary.
Note that this method should not be used in place of native operations, due to
the high cost of materializing all frame data out into a dictionary; it should
be used only when you need to move the values out into a Python data structure
or other object that cannot operate directly with Polars/Arrow.
Parameters
----------
key
The column(s) to use as the key for the returned dictionary. If multiple
columns are specified, the key will be a tuple of those values, otherwise
it will be a string.
named
Return dictionary rows instead of tuples, mapping column name to row value.
include_key
Include key values inline with the associated data (by default the key
values are omitted as a memory/performance optimisation, as they can be
reoconstructed from the key).
unique
Indicate that the key is unique; this will result in a 1:1 mapping from
key to a single associated row. Note that if the key is *not* actually
unique the last row with the given key will be returned.
Notes
-----
If you have `ns`-precision temporal values you should be aware that Python
natively only supports up to `μs`-precision; `ns`-precision values will be
truncated to microseconds on conversion to Python. If this matters to your
use-case you should export to a different format (such as Arrow or NumPy).
See Also
--------
rows : Materialize all frame data as a list of rows (potentially expensive).
iter_rows : Row iterator over frame data (does not materialize all rows).
to_dict : Convert DataFrame to a dictionary mapping column name to values.
Examples
--------
>>> df = pl.DataFrame(
... {
... "w": ["a", "b", "b", "a"],
... "x": ["q", "q", "q", "k"],
... "y": [1.0, 2.5, 3.0, 4.5],
... "z": [9, 8, 7, 6],
... }
... )
Group rows by the given key column(s):
>>> df.rows_by_key(key=["w"])
defaultdict(<class 'list'>,
{'a': [('q', 1.0, 9), ('k', 4.5, 6)],
'b': [('q', 2.5, 8), ('q', 3.0, 7)]})
Return the same row groupings as dictionaries:
>>> df.rows_by_key(key=["w"], named=True)
defaultdict(<class 'list'>,
{'a': [{'x': 'q', 'y': 1.0, 'z': 9},
{'x': 'k', 'y': 4.5, 'z': 6}],
'b': [{'x': 'q', 'y': 2.5, 'z': 8},
{'x': 'q', 'y': 3.0, 'z': 7}]})
Return row groupings, assuming keys are unique:
>>> df.rows_by_key(key=["z"], unique=True)
{9: ('a', 'q', 1.0),
8: ('b', 'q', 2.5),
7: ('b', 'q', 3.0),
6: ('a', 'k', 4.5)}
Return row groupings as dictionaries, assuming keys are unique:
>>> df.rows_by_key(key=["z"], named=True, unique=True)
{9: {'w': 'a', 'x': 'q', 'y': 1.0},
8: {'w': 'b', 'x': 'q', 'y': 2.5},
7: {'w': 'b', 'x': 'q', 'y': 3.0},
6: {'w': 'a', 'x': 'k', 'y': 4.5}}
Return dictionary rows grouped by a compound key, including key values:
>>> df.rows_by_key(key=["w", "x"], named=True, include_key=True)
defaultdict(<class 'list'>,
{('a', 'q'): [{'w': 'a', 'x': 'q', 'y': 1.0, 'z': 9}],
('b', 'q'): [{'w': 'b', 'x': 'q', 'y': 2.5, 'z': 8},
{'w': 'b', 'x': 'q', 'y': 3.0, 'z': 7}],
('a', 'k'): [{'w': 'a', 'x': 'k', 'y': 4.5, 'z': 6}]})
"""
key = _expand_selectors(self, key)
keys = (
iter(self.get_column(key[0]))
if len(key) == 1
else self.select(key).iter_rows()
)
if include_key:
values = self
else:
data_cols = [k for k in self.schema if k not in key]
values = self.select(data_cols)
zipped = zip(keys, values.iter_rows(named=named)) # type: ignore[call-overload]
# if unique, we expect to write just one entry per key; otherwise, we're
# returning a list of rows for each key, so append into a defaultdict.
if unique:
rows = dict(zipped)
else:
rows = defaultdict(list)
for key, data in zipped:
rows[key].append(data)
return rows
@overload
def iter_rows(
self, *, named: Literal[False] = ..., buffer_size: int = ...
) -> Iterator[tuple[Any, ...]]: ...
@overload
def iter_rows(
self, *, named: Literal[True], buffer_size: int = ...
) -> Iterator[dict[str, Any]]: ...
def iter_rows(
self, *, named: bool = False, buffer_size: int = 512
) -> Iterator[tuple[Any, ...]] | Iterator[dict[str, Any]]:
"""
Returns an iterator over the DataFrame of rows of python-native values.
Parameters
----------
named
Return dictionaries instead of tuples. The dictionaries are a mapping of
column name to row value. This is more expensive than returning a regular
tuple, but allows for accessing values by column name.
buffer_size
Determines the number of rows that are buffered internally while iterating
over the data; you should only modify this in very specific cases where the
default value is determined not to be a good fit to your access pattern, as
the speedup from using the buffer is significant (~2-4x). Setting this
value to zero disables row buffering (not recommended).
Notes
-----
If you have `ns`-precision temporal values you should be aware that Python
natively only supports up to `μs`-precision; `ns`-precision values will be
truncated to microseconds on conversion to Python. If this matters to your
use-case you should export to a different format (such as Arrow or NumPy).
Warnings
--------
Row iteration is not optimal as the underlying data is stored in columnar form;
where possible, prefer export via one of the dedicated export/output methods
that deals with columnar data.
Yields
------
iterator of tuples (default) or dictionaries (if named) of python row values
See Also
--------
rows : Materialises all frame data as a list of rows (potentially expensive).
rows_by_key : Materialises frame data as a key-indexed dictionary.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 3, 5],
... "b": [2, 4, 6],
... }
... )
>>> [row[0] for row in df.iter_rows()]
[1, 3, 5]
>>> [row["b"] for row in df.iter_rows(named=True)]
[2, 4, 6]
"""
# load into the local namespace for a (minor) performance boost in the hot loops
columns, get_row, dict_, zip_ = self.columns, self.row, dict, zip
has_object = Object in self.dtypes
# note: buffering rows results in a 2-4x speedup over individual calls
# to ".row(i)", so it should only be disabled in extremely specific cases.
if buffer_size and not has_object:
for offset in range(0, self.height, buffer_size):
zerocopy_slice = self.slice(offset, buffer_size)
if named:
for row in zerocopy_slice.rows(named=False):
yield dict_(zip_(columns, row))
else:
yield from zerocopy_slice.rows(named=False)
elif named:
for i in range(self.height):
yield dict_(zip_(columns, get_row(i)))
else:
for i in range(self.height):
yield get_row(i)
def iter_columns(self) -> Iterator[Series]:
"""
Returns an iterator over the columns of this DataFrame.
Yields
------
Series
Notes
-----
Consider whether you can use :func:`all` instead.
If you can, it will be more efficient.
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 3, 5],
... "b": [2, 4, 6],
... }
... )
>>> [s.name for s in df.iter_columns()]
['a', 'b']
If you're using this to modify a dataframe's columns, e.g.
>>> # Do NOT do this
>>> pl.DataFrame(column * 2 for column in df.iter_columns())
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 2 ┆ 4 │
│ 6 ┆ 8 │
│ 10 ┆ 12 │
└─────┴─────┘
then consider whether you can use :func:`all` instead:
>>> df.select(pl.all() * 2)
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 2 ┆ 4 │
│ 6 ┆ 8 │
│ 10 ┆ 12 │
└─────┴─────┘
"""
for s in self._df.get_columns():
yield wrap_s(s)
def iter_slices(self, n_rows: int = 10_000) -> Iterator[DataFrame]:
r"""
Returns a non-copying iterator of slices over the underlying DataFrame.
Parameters
----------
n_rows
Determines the number of rows contained in each DataFrame slice.
Examples
--------
>>> from datetime import date
>>> df = pl.DataFrame(
... data={
... "a": range(17_500),
... "b": date(2023, 1, 1),
... "c": "klmnoopqrstuvwxyz",
... },
... schema_overrides={"a": pl.Int32},
... )
>>> for idx, frame in enumerate(df.iter_slices()):
... print(f"{type(frame).__name__}:[{idx}]:{len(frame)}")
DataFrame:[0]:10000
DataFrame:[1]:7500
Using `iter_slices` is an efficient way to chunk-iterate over DataFrames and
any supported frame export/conversion types; for example, as RecordBatches:
>>> for frame in df.iter_slices(n_rows=15_000):
... record_batch = frame.to_arrow().to_batches()[0]
... print(f"{record_batch.schema}\n<< {len(record_batch)}")
a: int32
b: date32[day]
c: large_string
<< 15000
a: int32
b: date32[day]
c: large_string
<< 2500
See Also
--------
iter_rows : Row iterator over frame data (does not materialise all rows).
partition_by : Split into multiple DataFrames, partitioned by groups.
"""
for offset in range(0, self.height, n_rows):
yield self.slice(offset, n_rows)
def shrink_to_fit(self, *, in_place: bool = False) -> DataFrame:
"""
Shrink DataFrame memory usage.
Shrinks to fit the exact capacity needed to hold the data.
"""
if in_place:
self._df.shrink_to_fit()
return self
else:
df = self.clone()
df._df.shrink_to_fit()
return df
def gather_every(self, n: int, offset: int = 0) -> DataFrame:
"""
Take every nth row in the DataFrame and return as a new DataFrame.
Parameters
----------
n
Gather every *n*-th row.
offset
Starting index.
Examples
--------
>>> s = pl.DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]})
>>> s.gather_every(2)
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 5 │
│ 3 ┆ 7 │
└─────┴─────┘
>>> s.gather_every(2, offset=1)
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 2 ┆ 6 │
│ 4 ┆ 8 │
└─────┴─────┘
"""
return self.select(F.col("*").gather_every(n, offset))
def hash_rows(
self,
seed: int = 0,
seed_1: int | None = None,
seed_2: int | None = None,
seed_3: int | None = None,
) -> Series:
"""
Hash and combine the rows in this DataFrame.
The hash value is of type `UInt64`.
Parameters
----------
seed
Random seed parameter. Defaults to 0.
seed_1
Random seed parameter. Defaults to `seed` if not set.
seed_2
Random seed parameter. Defaults to `seed` if not set.
seed_3
Random seed parameter. Defaults to `seed` if not set.
Notes
-----
This implementation of `hash_rows` does not guarantee stable results
across different Polars versions. Its stability is only guaranteed within a
single version.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, None, 3, 4],
... "ham": ["a", "b", None, "d"],
... }
... )
>>> df.hash_rows(seed=42) # doctest: +IGNORE_RESULT
shape: (4,)
Series: '' [u64]
[
10783150408545073287
1438741209321515184
10047419486152048166
2047317070637311557
]
"""
k0 = seed
k1 = seed_1 if seed_1 is not None else seed
k2 = seed_2 if seed_2 is not None else seed
k3 = seed_3 if seed_3 is not None else seed
return wrap_s(self._df.hash_rows(k0, k1, k2, k3))
def interpolate(self) -> DataFrame:
"""
Interpolate intermediate values. The interpolation method is linear.
Nulls at the beginning and end of the series remain null.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, None, 9, 10],
... "bar": [6, 7, 9, None],
... "baz": [1, None, None, 9],
... }
... )
>>> df.interpolate()
shape: (4, 3)
┌──────┬──────┬──────────┐
│ foo ┆ bar ┆ baz │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 │
╞══════╪══════╪══════════╡
│ 1.0 ┆ 6.0 ┆ 1.0 │
│ 5.0 ┆ 7.0 ┆ 3.666667 │
│ 9.0 ┆ 9.0 ┆ 6.333333 │
│ 10.0 ┆ null ┆ 9.0 │
└──────┴──────┴──────────┘
"""
return self.select(F.col("*").interpolate())
def is_empty(self) -> bool:
"""
Returns `True` if the DataFrame contains no rows.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
>>> df.is_empty()
False
>>> df.filter(pl.col("foo") > 99).is_empty()
True
"""
return self._df.is_empty()
def to_struct(self, name: str = "") -> Series:
"""
Convert a `DataFrame` to a `Series` of type `Struct`.
Parameters
----------
name
Name for the struct Series
Examples
--------
>>> df = pl.DataFrame(
... {
... "a": [1, 2, 3, 4, 5],
... "b": ["one", "two", "three", "four", "five"],
... }
... )
>>> df.to_struct("nums")
shape: (5,)
Series: 'nums' [struct[2]]
[
{1,"one"}
{2,"two"}
{3,"three"}
{4,"four"}
{5,"five"}
]
"""
return wrap_s(self._df.to_struct(name, []))
def unnest(
self,
columns: ColumnNameOrSelector | Collection[ColumnNameOrSelector],
*more_columns: ColumnNameOrSelector,
separator: str | None = None,
) -> DataFrame:
"""
Decompose struct columns into separate columns for each of their fields.
The new columns will be inserted into the dataframe at the location of the
struct column.
Parameters
----------
columns
Name of the struct column(s) that should be unnested.
*more_columns
Additional columns to unnest, specified as positional arguments.
separator
Rename output column names as combination of the struct column name,
name separator and field name.
Examples
--------
>>> df = pl.DataFrame(
... {
... "before": ["foo", "bar"],
... "t_a": [1, 2],
... "t_b": ["a", "b"],
... "t_c": [True, None],
... "t_d": [[1, 2], [3]],
... "after": ["baz", "womp"],
... }
... ).select("before", pl.struct(pl.col("^t_.$")).alias("t_struct"), "after")
>>> df
shape: (2, 3)
┌────────┬─────────────────────┬───────┐
│ before ┆ t_struct ┆ after │
│ --- ┆ --- ┆ --- │
│ str ┆ struct[4] ┆ str │
╞════════╪═════════════════════╪═══════╡
│ foo ┆ {1,"a",true,[1, 2]} ┆ baz │
│ bar ┆ {2,"b",null,[3]} ┆ womp │
└────────┴─────────────────────┴───────┘
>>> df.unnest("t_struct")
shape: (2, 6)
┌────────┬─────┬─────┬──────┬───────────┬───────┐
│ before ┆ t_a ┆ t_b ┆ t_c ┆ t_d ┆ after │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ bool ┆ list[i64] ┆ str │
╞════════╪═════╪═════╪══════╪═══════════╪═══════╡
│ foo ┆ 1 ┆ a ┆ true ┆ [1, 2] ┆ baz │
│ bar ┆ 2 ┆ b ┆ null ┆ [3] ┆ womp │
└────────┴─────┴─────┴──────┴───────────┴───────┘
>>> df = pl.DataFrame(
... {
... "before": ["foo", "bar"],
... "t_a": [1, 2],
... "t_b": ["a", "b"],
... "t_c": [True, None],
... "t_d": [[1, 2], [3]],
... "after": ["baz", "womp"],
... }
... ).select(
... "before",
... pl.struct(pl.col("^t_.$").name.map(lambda t: t[2:])).alias("t"),
... "after",
... )
>>> df.unnest("t", separator="::")
shape: (2, 6)
┌────────┬──────┬──────┬──────┬───────────┬───────┐
│ before ┆ t::a ┆ t::b ┆ t::c ┆ t::d ┆ after │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ bool ┆ list[i64] ┆ str │
╞════════╪══════╪══════╪══════╪═══════════╪═══════╡
│ foo ┆ 1 ┆ a ┆ true ┆ [1, 2] ┆ baz │
│ bar ┆ 2 ┆ b ┆ null ┆ [3] ┆ womp │
└────────┴──────┴──────┴──────┴───────────┴───────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.unnest(columns, *more_columns, separator=separator)
.collect(optimizations=QueryOptFlags._eager())
)
def corr(self, **kwargs: Any) -> DataFrame:
"""
Return pairwise Pearson product-moment correlation coefficients between columns.
See numpy `corrcoef` for more information:
https://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html
Notes
-----
This functionality requires numpy to be installed.
Parameters
----------
**kwargs
Keyword arguments are passed to numpy `corrcoef`.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3], "bar": [3, 2, 1], "ham": [7, 8, 9]})
>>> df.corr()
shape: (3, 3)
┌──────┬──────┬──────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 │
╞══════╪══════╪══════╡
│ 1.0 ┆ -1.0 ┆ 1.0 │
│ -1.0 ┆ 1.0 ┆ -1.0 │
│ 1.0 ┆ -1.0 ┆ 1.0 │
└──────┴──────┴──────┘
"""
correlation_matrix = np.corrcoef(self.to_numpy(), rowvar=False, **kwargs)
if self.width == 1:
correlation_matrix = np.array([correlation_matrix])
return DataFrame(correlation_matrix, schema=self.columns)
def merge_sorted(self, other: DataFrame, key: str) -> DataFrame:
"""
Take two sorted DataFrames and merge them by the sorted key.
The output of this operation will also be sorted.
It is the callers responsibility that the frames
are sorted in ascending order by that key otherwise
the output will not make sense.
The schemas of both DataFrames must be equal.
Parameters
----------
other
Other DataFrame that must be merged
key
Key that is sorted.
Examples
--------
>>> df0 = pl.DataFrame(
... {"name": ["steve", "elise", "bob"], "age": [42, 44, 18]}
... ).sort("age")
>>> df0
shape: (3, 2)
┌───────┬─────┐
│ name ┆ age │
│ --- ┆ --- │
│ str ┆ i64 │
╞═══════╪═════╡
│ bob ┆ 18 │
│ steve ┆ 42 │
│ elise ┆ 44 │
└───────┴─────┘
>>> df1 = pl.DataFrame(
... {"name": ["anna", "megan", "steve", "thomas"], "age": [21, 33, 42, 20]}
... ).sort("age")
>>> df1
shape: (4, 2)
┌────────┬─────┐
│ name ┆ age │
│ --- ┆ --- │
│ str ┆ i64 │
╞════════╪═════╡
│ thomas ┆ 20 │
│ anna ┆ 21 │
│ megan ┆ 33 │
│ steve ┆ 42 │
└────────┴─────┘
>>> df0.merge_sorted(df1, key="age")
shape: (7, 2)
┌────────┬─────┐
│ name ┆ age │
│ --- ┆ --- │
│ str ┆ i64 │
╞════════╪═════╡
│ bob ┆ 18 │
│ thomas ┆ 20 │
│ anna ┆ 21 │
│ megan ┆ 33 │
│ steve ┆ 42 │
│ steve ┆ 42 │
│ elise ┆ 44 │
└────────┴─────┘
Notes
-----
No guarantee is given over the output row order when the key is equal
between the both dataframes.
The key must be sorted in ascending order.
"""
from polars.lazyframe.opt_flags import QueryOptFlags
require_same_type(self, other)
return (
self.lazy()
.merge_sorted(other.lazy(), key)
.collect(optimizations=QueryOptFlags._eager())
)
def set_sorted(
self,
column: str,
*,
descending: bool = False,
) -> DataFrame:
"""
Flag a column as sorted.
This can speed up future operations.
Parameters
----------
column
Column that is sorted
descending
Whether the column is sorted in descending order.
Warnings
--------
This can lead to incorrect results if the data is NOT sorted!!
Use with care!
"""
# NOTE: Only accepts 1 column on purpose! User think they are sorted by
# the combined multicolumn values.
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.set_sorted(column, descending=descending)
.collect(optimizations=QueryOptFlags._eager())
)
@unstable()
def update(
self,
other: DataFrame,
on: str | Sequence[str] | None = None,
how: Literal["left", "inner", "full"] = "left",
*,
left_on: str | Sequence[str] | None = None,
right_on: str | Sequence[str] | None = None,
include_nulls: bool = False,
maintain_order: MaintainOrderJoin | None = "left",
) -> DataFrame:
"""
Update the values in this `DataFrame` with the values in `other`.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
Parameters
----------
other
DataFrame that will be used to update the values
on
Column names that will be joined on. If set to `None` (default),
the implicit row index of each frame is used as a join key.
how : {'left', 'inner', 'full'}
* 'left' will keep all rows from the left table; rows may be duplicated
if multiple rows in the right frame match the left row's key.
* 'inner' keeps only those rows where the key exists in both frames.
* 'full' will update existing rows where the key matches while also
adding any new rows contained in the given frame.
left_on
Join column(s) of the left DataFrame.
right_on
Join column(s) of the right DataFrame.
include_nulls
Overwrite values in the left frame with null values from the right frame.
If set to `False` (default), null values in the right frame are ignored.
maintain_order : {'none', 'left', 'right', 'left_right', 'right_left'}
Which order of rows from the inputs to preserve. See :func:`~DataFrame.join`
for details. Unlike `join` this function preserves the left order by
default.
Notes
-----
This is syntactic sugar for a left/inner join that preserves the order
of the left `DataFrame` by default, with an optional coalesce when
`include_nulls = False`.
Examples
--------
>>> df = pl.DataFrame(
... {
... "A": [1, 2, 3, 4],
... "B": [400, 500, 600, 700],
... }
... )
>>> df
shape: (4, 2)
┌─────┬─────┐
│ A ┆ B │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 400 │
│ 2 ┆ 500 │
│ 3 ┆ 600 │
│ 4 ┆ 700 │
└─────┴─────┘
>>> new_df = pl.DataFrame(
... {
... "B": [-66, None, -99],
... "C": [5, 3, 1],
... }
... )
Update `df` values with the non-null values in `new_df`, by row index:
>>> df.update(new_df)
shape: (4, 2)
┌─────┬─────┐
│ A ┆ B │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ -66 │
│ 2 ┆ 500 │
│ 3 ┆ -99 │
│ 4 ┆ 700 │
└─────┴─────┘
Update `df` values with the non-null values in `new_df`, by row index,
but only keeping those rows that are common to both frames:
>>> df.update(new_df, how="inner")
shape: (3, 2)
┌─────┬─────┐
│ A ┆ B │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ -66 │
│ 2 ┆ 500 │
│ 3 ┆ -99 │
└─────┴─────┘
Update `df` values with the non-null values in `new_df`, using a full
outer join strategy that defines explicit join columns in each frame:
>>> df.update(new_df, left_on=["A"], right_on=["C"], how="full")
shape: (5, 2)
┌─────┬─────┐
│ A ┆ B │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ -99 │
│ 2 ┆ 500 │
│ 3 ┆ 600 │
│ 4 ┆ 700 │
│ 5 ┆ -66 │
└─────┴─────┘
Update `df` values including null values in `new_df`, using a full outer
join strategy that defines explicit join columns in each frame:
>>> df.update(new_df, left_on="A", right_on="C", how="full", include_nulls=True)
shape: (5, 2)
┌─────┬──────┐
│ A ┆ B │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪══════╡
│ 1 ┆ -99 │
│ 2 ┆ 500 │
│ 3 ┆ null │
│ 4 ┆ 700 │
│ 5 ┆ -66 │
└─────┴──────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
require_same_type(self, other)
return (
self.lazy()
.update(
other.lazy(),
on,
how,
left_on=left_on,
right_on=right_on,
include_nulls=include_nulls,
maintain_order=maintain_order,
)
.collect(optimizations=QueryOptFlags._eager())
)
def count(self) -> DataFrame:
"""
Return the number of non-null elements for each column.
Examples
--------
>>> df = pl.DataFrame(
... {"a": [1, 2, 3, 4], "b": [1, 2, 1, None], "c": [None, None, None, None]}
... )
>>> df.count()
shape: (1, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ u32 │
╞═════╪═════╪═════╡
│ 4 ┆ 3 ┆ 0 │
└─────┴─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return self.lazy().count().collect(optimizations=QueryOptFlags._eager())
@deprecated(
"`DataFrame.melt` is deprecated; use `DataFrame.unpivot` instead, with "
"`index` instead of `id_vars` and `on` instead of `value_vars`"
)
def melt(
self,
id_vars: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None,
value_vars: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None,
variable_name: str | None = None,
value_name: str | None = None,
) -> DataFrame:
"""
Unpivot a DataFrame from wide to long format.
Optionally leaves identifiers set.
This function is useful to massage a DataFrame into a format where one or more
columns are identifier variables (id_vars) while all other columns, considered
measured variables (value_vars), are "unpivoted" to the row axis leaving just
two non-identifier columns, 'variable' and 'value'.
.. deprecated:: 1.0.0
Use the :meth:`.unpivot` method instead.
Parameters
----------
id_vars
Column(s) or selector(s) to use as identifier variables.
value_vars
Column(s) or selector(s) to use as values variables; if `value_vars`
is empty all columns that are not in `id_vars` will be used.
variable_name
Name to give to the `variable` column. Defaults to "variable"
value_name
Name to give to the `value` column. Defaults to "value"
"""
return self.unpivot(
index=id_vars,
on=value_vars,
variable_name=variable_name,
value_name=value_name,
)
@unstable()
def match_to_schema(
self,
schema: SchemaDict | Schema,
*,
missing_columns: Literal["insert", "raise"]
| Mapping[str, Literal["insert", "raise"] | Expr] = "raise",
missing_struct_fields: Literal["insert", "raise"]
| Mapping[str, Literal["insert", "raise"]] = "raise",
extra_columns: Literal["ignore", "raise"] = "raise",
extra_struct_fields: Literal["ignore", "raise"]
| Mapping[str, Literal["ignore", "raise"]] = "raise",
integer_cast: Literal["upcast", "forbid"]
| Mapping[str, Literal["upcast", "forbid"]] = "forbid",
float_cast: Literal["upcast", "forbid"]
| Mapping[str, Literal["upcast", "forbid"]] = "forbid",
) -> DataFrame:
"""
Match or evolve the schema of a LazyFrame into a specific schema.
By default, match_to_schema returns an error if the input schema does not
exactly match the target schema. It also allows columns to be freely reordered,
with additional coercion rules available through optional parameters.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
Parameters
----------
schema
Target schema to match or evolve to.
missing_columns
Raise of insert missing columns from the input with respect to the `schema`.
This can also be an expression per column with what to insert if it is
missing.
missing_struct_fields
Raise of insert missing struct fields from the input with respect to the
`schema`.
extra_columns
Raise of ignore extra columns from the input with respect to the `schema`.
extra_struct_fields
Raise of ignore extra struct fields from the input with respect to the
`schema`.
integer_cast
Forbid of upcast for integer columns from the input to the respective column
in `schema`.
float_cast
Forbid of upcast for float columns from the input to the respective column
in `schema`.
Examples
--------
Ensuring the schema matches
>>> df = pl.DataFrame({"a": [1, 2, 3], "b": ["A", "B", "C"]})
>>> df.match_to_schema({"a": pl.Int64, "b": pl.String})
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═════╡
│ 1 ┆ A │
│ 2 ┆ B │
│ 3 ┆ C │
└─────┴─────┘
>>> df.match_to_schema({"a": pl.Int64}) # doctest: +SKIP
polars.exceptions.SchemaError: extra columns in `match_to_schema`: "b"
Adding missing columns
>>> (
... pl.DataFrame({"a": [1, 2, 3]}).match_to_schema(
... {"a": pl.Int64, "b": pl.String},
... missing_columns="insert",
... )
... )
shape: (3, 2)
┌─────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪══════╡
│ 1 ┆ null │
│ 2 ┆ null │
│ 3 ┆ null │
└─────┴──────┘
>>> (
... pl.DataFrame({"a": [1, 2, 3]}).match_to_schema(
... {"a": pl.Int64, "b": pl.String},
... missing_columns={"b": pl.col.a.cast(pl.String)},
... )
... )
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═════╡
│ 1 ┆ 1 │
│ 2 ┆ 2 │
│ 3 ┆ 3 │
└─────┴─────┘
Removing extra columns
>>> (
... pl.DataFrame({"a": [1, 2, 3], "b": ["A", "B", "C"]}).match_to_schema(
... {"a": pl.Int64},
... extra_columns="ignore",
... )
... )
shape: (3, 1)
┌─────┐
│ a │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ 2 │
│ 3 │
└─────┘
Upcasting integers and floats
>>> (
... pl.DataFrame(
... {"a": [1, 2, 3], "b": [1.0, 2.0, 3.0]},
... schema={"a": pl.Int32, "b": pl.Float32},
... ).match_to_schema(
... {"a": pl.Int64, "b": pl.Float64},
... integer_cast="upcast",
... float_cast="upcast",
... )
... )
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪═════╡
│ 1 ┆ 1.0 │
│ 2 ┆ 2.0 │
│ 3 ┆ 3.0 │
└─────┴─────┘
"""
from polars.lazyframe.opt_flags import QueryOptFlags
return (
self.lazy()
.match_to_schema(
schema=schema,
missing_columns=missing_columns,
missing_struct_fields=missing_struct_fields,
extra_columns=extra_columns,
extra_struct_fields=extra_struct_fields,
integer_cast=integer_cast,
float_cast=float_cast,
)
.collect(optimizations=QueryOptFlags._eager())
)
def _to_metadata(
self,
columns: None | str | list[str] = None,
stats: None | str | list[str] = None,
) -> DataFrame:
"""
Get all runtime metadata for each column.
This is unstable and is meant for debugging purposes.
Parameters
----------
columns
Column(s) to show the information for
stats
Statistics to show
"""
df = self
if columns is not None:
if isinstance(columns, str):
columns = [columns]
df = df.select(columns)
md = self._from_pydf(df._df._to_metadata())
if stats is not None:
if isinstance(stats, str):
stats = [stats]
if "column_name" not in stats:
stats = ["column_name"] + stats
md = md.select(stats)
return md
def _row_encode(
self,
*,
unordered: bool = False,
descending: list[bool] | None = None,
nulls_last: list[bool] | None = None,
) -> Series:
"""
Row encode the given DataFrame.
This is an internal function not meant for outside consumption and can
be changed or removed at any point in time.
fields have order:
- descending
- nulls_last
- no_order
"""
return self.select_seq(
F._row_encode(
F.all(),
unordered=unordered,
descending=descending,
nulls_last=nulls_last,
)
).to_series()
def _prepare_other_arg(other: Any, length: int | None = None) -> Series:
# if not a series create singleton series such that it will broadcast
value = other
if not isinstance(other, pl.Series):
if isinstance(other, str):
pass
elif isinstance(other, Sequence):
msg = "operation not supported"
raise TypeError(msg)
other = pl.Series("", [other])
if length is not None:
if length > 1:
other = other.extend_constant(value=value, n=length - 1)
elif length == 0:
other = other.slice(0, 0)
return other
| DataFrame |
python | getsentry__sentry | src/sentry/integrations/jira/handlers/jira_handler.py | {
"start": 402,
"end": 548
} | class ____(TicketingActionHandler):
group = ActionHandler.Group.TICKET_CREATION
provider_slug = IntegrationProviderSlug.JIRA
| JiraActionHandler |
python | walkccc__LeetCode | solutions/123. Best Time to Buy and Sell Stock III/123.py | {
"start": 0,
"end": 366
} | class ____:
def maxProfit(self, prices: list[int]) -> int:
sellTwo = 0
holdTwo = -math.inf
sellOne = 0
holdOne = -math.inf
for price in prices:
sellTwo = max(sellTwo, holdTwo + price)
holdTwo = max(holdTwo, sellOne - price)
sellOne = max(sellOne, holdOne + price)
holdOne = max(holdOne, -price)
return sellTwo
| Solution |
python | conda__conda | conda/core/initialize.py | {
"start": 3043,
"end": 80730
} | class ____:
NEEDS_SUDO = "needs sudo"
MODIFIED = "modified"
NO_CHANGE = "no change"
ContentTypeOptions = Literal["initialize", "add_condabin_to_path"]
# #####################################################
# top-level functions
# #####################################################
def install(conda_prefix):
plan = make_install_plan(conda_prefix)
run_plan(plan)
if not context.dry_run and any(
step["result"] == Result.NEEDS_SUDO for step in plan
):
raise CondaError("Some steps require elevated permissions.")
print_plan_results(plan)
return 0
def initialize(
conda_prefix, shells, for_user, for_system, anaconda_prompt, reverse=False
):
plan1 = []
if os.getenv("CONDA_PIP_UNINITIALIZED") == "true":
plan1 = make_install_plan(conda_prefix)
run_plan(plan1)
if not context.dry_run:
run_plan_elevated(plan1)
plan2 = make_initialize_plan(
conda_prefix, shells, for_user, for_system, anaconda_prompt, reverse=reverse
)
run_plan(plan2)
if not context.dry_run:
run_plan_elevated(plan2)
plan = plan1 + plan2
print_plan_results(plan)
if any(step["result"] == Result.NEEDS_SUDO for step in plan):
print("Operation failed.", file=sys.stderr)
return 1
def initialize_dev(shell, dev_env_prefix=None, conda_source_root=None):
# > alias conda-dev='eval "$(python -m conda init --dev)"'
# > eval "$(python -m conda init --dev)"
prefix = expand(dev_env_prefix or sys.prefix)
conda_source_root = expand(conda_source_root or os.getcwd())
python_exe, python_version, site_packages_dir = _get_python_info(prefix)
if not isfile(join(conda_source_root, "conda", "__main__.py")):
raise CondaValueError(
f"Directory is not a conda source root: {conda_source_root}"
)
plan = make_install_plan(prefix)
plan.append(
{
"function": remove_conda_in_sp_dir.__name__,
"kwargs": {
"target_path": site_packages_dir,
},
}
)
plan.append(
{
"function": make_conda_egg_link.__name__,
"kwargs": {
"target_path": join(site_packages_dir, "conda.egg-link"),
"conda_source_root": conda_source_root,
},
}
)
plan.append(
{
"function": modify_easy_install_pth.__name__,
"kwargs": {
"target_path": join(site_packages_dir, "easy-install.pth"),
"conda_source_root": conda_source_root,
},
}
)
plan.append(
{
"function": make_dev_egg_info_file.__name__,
"kwargs": {
"target_path": join(conda_source_root, "conda.egg-info"),
},
}
)
run_plan(plan)
if context.dry_run or context.verbose:
print_plan_results(plan, sys.stderr)
if any(step["result"] == Result.NEEDS_SUDO for step in plan): # pragma: no cover
raise CondaError(
"Operation failed. Privileged install disallowed for 'conda init --dev'."
)
env_vars = {
"PYTHONHASHSEED": randint(0, 4294967296),
"PYTHON_MAJOR_VERSION": python_version[0],
"TEST_PLATFORM": "win" if on_win else "unix",
}
unset_env_vars = (
"CONDA_DEFAULT_ENV",
"CONDA_EXE",
"_CE_M",
"_CE_CONDA",
"CONDA_PREFIX",
"CONDA_PREFIX_1",
"CONDA_PREFIX_2",
"CONDA_PYTHON_EXE",
"CONDA_PROMPT_MODIFIER",
"CONDA_SHLVL",
)
if shell == "bash":
print("\n".join(_initialize_dev_bash(prefix, env_vars, unset_env_vars)))
elif shell == "cmd.exe":
script = _initialize_dev_cmdexe(prefix, env_vars, unset_env_vars)
if not context.dry_run:
with open_utf8("dev-init.bat", "w") as fh:
fh.write("\n".join(script))
if context.verbose:
print("\n".join(script))
print("now run > .\\dev-init.bat")
else:
raise NotImplementedError()
return 0
def _initialize_dev_bash(prefix, env_vars, unset_env_vars):
sys_executable = abspath(sys.executable)
if on_win:
sys_executable = f"$(cygpath '{sys_executable}')"
# unset/set environment variables
yield from (f"unset {envvar}" for envvar in unset_env_vars)
yield from (
f"export {envvar}='{value}'" for envvar, value in sorted(env_vars.items())
)
# initialize shell interface
yield f'eval "$("{sys_executable}" -m conda shell.bash hook)"'
# optionally activate environment
if context.auto_activate:
yield f"conda activate '{prefix}'"
def _initialize_dev_cmdexe(prefix, env_vars, unset_env_vars):
dev_arg = ""
if context.dev:
dev_arg = "--dev"
condabin = Path(prefix, "condabin")
yield (
'@IF NOT "%CONDA_PROMPT_MODIFIER%" == "" '
'@CALL SET "PROMPT=%%PROMPT:%CONDA_PROMPT_MODIFIER%=%_empty_not_set_%%%"'
)
# unset/set environment variables
yield from (f"@SET {envvar}=" for envvar in unset_env_vars)
yield from (
f'@SET "{envvar}={value}"' for envvar, value in sorted(env_vars.items())
)
# initialize shell interface
yield f'@CALL "{condabin / "conda_hook.bat"}" {dev_arg}'
yield "@IF %ERRORLEVEL% NEQ 0 @EXIT /B %ERRORLEVEL%"
# optionally activate environment
if context.auto_activate:
yield f'@CALL "{condabin / "conda.bat"}" activate {dev_arg} "{prefix}"'
yield "@IF %ERRORLEVEL% NEQ 0 @EXIT /B %ERRORLEVEL%"
def add_condabin_to_path(conda_prefix, shells, for_user, for_system, reverse=False):
plan = make_condabin_plan(
conda_prefix, shells, for_user, for_system, reverse=reverse
)
run_plan(plan)
if not context.dry_run:
run_plan_elevated(plan)
print_plan_results(plan)
if any(step["result"] == Result.NEEDS_SUDO for step in plan):
print("Operation failed.", file=sys.stderr)
return 1
# #####################################################
# plan creators
# #####################################################
def make_install_plan(conda_prefix):
try:
python_exe, python_version, site_packages_dir = _get_python_info(conda_prefix)
except OSError:
python_exe, python_version, site_packages_dir = None, None, None # NOQA
plan = []
# ######################################
# executables
# ######################################
if on_win:
conda_exe_path = join(conda_prefix, "Scripts", "conda-script.py")
conda_env_exe_path = join(conda_prefix, "Scripts", "conda-env-script.py")
plan.append(
{
"function": make_entry_point_exe.__name__,
"kwargs": {
"target_path": join(conda_prefix, "Scripts", "conda.exe"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": make_entry_point_exe.__name__,
"kwargs": {
"target_path": join(conda_prefix, "Scripts", "conda-env.exe"),
"conda_prefix": conda_prefix,
},
}
)
else:
# We can't put a conda.exe in condabin on Windows. It'll conflict with conda.bat.
plan.append(
{
"function": make_entry_point.__name__,
"kwargs": {
"target_path": join(conda_prefix, "condabin", "conda"),
"conda_prefix": conda_prefix,
"module": "conda.cli",
"func": "main",
},
}
)
conda_exe_path = join(conda_prefix, "bin", "conda")
conda_env_exe_path = join(conda_prefix, "bin", "conda-env")
plan.append(
{
"function": make_entry_point.__name__,
"kwargs": {
"target_path": conda_exe_path,
"conda_prefix": conda_prefix,
"module": "conda.cli",
"func": "main",
},
}
)
plan.append(
{
"function": make_entry_point.__name__,
"kwargs": {
"target_path": conda_env_exe_path,
"conda_prefix": conda_prefix,
# TODO: Remove upon full deprecation in 25.3
"module": "conda_env.cli.main",
"func": "main",
},
}
)
# ######################################
# shell wrappers
# ######################################
if on_win:
plan.append(
{
"function": install_condabin_conda_bat.__name__,
"kwargs": {
"target_path": join(conda_prefix, "condabin", "conda.bat"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_library_bin_conda_bat.__name__,
"kwargs": {
"target_path": join(conda_prefix, "Library", "bin", "conda.bat"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_condabin_conda_activate_bat.__name__,
"kwargs": {
"target_path": join(
conda_prefix, "condabin", "_conda_activate.bat"
),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_condabin_rename_tmp_bat.__name__,
"kwargs": {
"target_path": join(conda_prefix, "condabin", "rename_tmp.bat"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_condabin_conda_auto_activate_bat.__name__,
"kwargs": {
"target_path": join(
conda_prefix, "condabin", "conda_auto_activate.bat"
),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_condabin_hook_bat.__name__,
"kwargs": {
"target_path": join(conda_prefix, "condabin", "conda_hook.bat"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_Scripts_activate_bat.__name__,
"kwargs": {
"target_path": join(conda_prefix, "Scripts", "activate.bat"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_activate_bat.__name__,
"kwargs": {
"target_path": join(conda_prefix, "condabin", "activate.bat"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_deactivate_bat.__name__,
"kwargs": {
"target_path": join(conda_prefix, "condabin", "deactivate.bat"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_activate.__name__,
"kwargs": {
"target_path": join(conda_prefix, BIN_DIRECTORY, "activate"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_deactivate.__name__,
"kwargs": {
"target_path": join(conda_prefix, BIN_DIRECTORY, "deactivate"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_conda_sh.__name__,
"kwargs": {
"target_path": join(conda_prefix, "etc", "profile.d", "conda.sh"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_conda_fish.__name__,
"kwargs": {
"target_path": join(
conda_prefix, "etc", "fish", "conf.d", "conda.fish"
),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_conda_psm1.__name__,
"kwargs": {
"target_path": join(conda_prefix, "shell", "condabin", "Conda.psm1"),
"conda_prefix": conda_prefix,
},
}
)
plan.append(
{
"function": install_conda_hook_ps1.__name__,
"kwargs": {
"target_path": join(
conda_prefix, "shell", "condabin", "conda-hook.ps1"
),
"conda_prefix": conda_prefix,
},
}
)
if site_packages_dir:
plan.append(
{
"function": install_conda_xsh.__name__,
"kwargs": {
"target_path": join(site_packages_dir, "xontrib", "conda.xsh"),
"conda_prefix": conda_prefix,
},
}
)
else:
print(
"WARNING: Cannot install xonsh wrapper without a python interpreter in prefix: "
f"{conda_prefix}",
file=sys.stderr,
)
plan.append(
{
"function": install_conda_csh.__name__,
"kwargs": {
"target_path": join(conda_prefix, "etc", "profile.d", "conda.csh"),
"conda_prefix": conda_prefix,
},
}
)
return plan
def make_initialize_plan(
conda_prefix, shells, for_user, for_system, anaconda_prompt, reverse=False
):
"""
Creates a plan for initializing conda in shells.
Bash:
On Linux, when opening the terminal, .bashrc is sourced (because it is an interactive shell).
On macOS on the other hand, the .bash_profile gets sourced by default when executing it in
Terminal.app. Some other programs do the same on macOS so that's why we're initializing conda
in .bash_profile.
On Windows, there are multiple ways to open bash depending on how it was installed. Git Bash,
Cygwin, and MSYS2 all use .bash_profile by default.
PowerShell:
There's several places PowerShell can store its path, depending on if it's Windows PowerShell,
PowerShell Core on Windows, or PowerShell Core on macOS/Linux. The easiest way to resolve it
is to just ask different possible installations of PowerShell where their profiles are.
"""
plan = make_install_plan(conda_prefix)
shells = set(shells)
if shells & {"bash", "zsh"}:
if "bash" in shells and for_user:
bashrc_path = expand(
join("~", ".bash_profile" if (on_mac or on_win) else ".bashrc")
)
plan.append(
{
"function": init_sh_user.__name__,
"kwargs": {
"target_path": bashrc_path,
"conda_prefix": conda_prefix,
"shell": "bash",
"reverse": reverse,
},
}
)
if "zsh" in shells and for_user:
if "ZDOTDIR" in os.environ:
zshrc_path = expand(join("$ZDOTDIR", ".zshrc"))
else:
zshrc_path = expand(join("~", ".zshrc"))
plan.append(
{
"function": init_sh_user.__name__,
"kwargs": {
"target_path": zshrc_path,
"conda_prefix": conda_prefix,
"shell": "zsh",
"reverse": reverse,
},
}
)
if for_system:
plan.append(
{
"function": init_sh_system.__name__,
"kwargs": {
"target_path": "/etc/profile.d/conda.sh",
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if "fish" in shells:
if for_user:
config_fish_path = expand(join("~", ".config", "fish", "config.fish"))
plan.append(
{
"function": init_fish_user.__name__,
"kwargs": {
"target_path": config_fish_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if for_system:
config_fish_path = expand(join("~", ".config", "fish", "config.fish"))
plan.append(
{
"function": init_fish_user.__name__,
"kwargs": {
"target_path": config_fish_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if "xonsh" in shells:
if for_user:
config_xonsh_path = expand(join("~", ".xonshrc"))
plan.append(
{
"function": init_xonsh_user.__name__,
"kwargs": {
"target_path": config_xonsh_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if for_system:
if on_win:
config_xonsh_path = expand(
join("%ALLUSERSPROFILE%", "xonsh", "xonshrc")
)
else:
config_xonsh_path = "/etc/xonshrc"
plan.append(
{
"function": init_xonsh_user.__name__,
"kwargs": {
"target_path": config_xonsh_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if "tcsh" in shells and for_user:
tcshrc_path = expand(join("~", ".tcshrc"))
plan.append(
{
"function": init_sh_user.__name__,
"kwargs": {
"target_path": tcshrc_path,
"conda_prefix": conda_prefix,
"shell": "tcsh",
"reverse": reverse,
},
}
)
if "powershell" in shells:
if for_user:
profile = "$PROFILE.CurrentUserAllHosts"
if for_system:
profile = "$PROFILE.AllUsersAllHosts"
def find_powershell_paths(*exe_names):
for exe_name in exe_names:
try:
yield subprocess_call(
(exe_name, "-NoProfile", "-Command", profile)
).stdout.strip()
except Exception:
pass
config_powershell_paths = set(
find_powershell_paths("powershell", "pwsh", "pwsh-preview")
)
for config_path in config_powershell_paths:
if config_path is not None:
plan.append(
{
"function": init_powershell_user.__name__,
"kwargs": {
"target_path": config_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if "cmd.exe" in shells:
if for_user:
plan.append(
{
"function": init_cmd_exe_registry.__name__,
"kwargs": {
"target_path": "HKEY_CURRENT_USER\\Software\\Microsoft\\"
"Command Processor\\AutoRun",
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if for_system:
plan.append(
{
"function": init_cmd_exe_registry.__name__,
"kwargs": {
"target_path": "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\"
"Command Processor\\AutoRun",
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
# it would be nice to enable this on a user-level basis, but unfortunately, it is
# a system-level key only.
plan.append(
{
"function": init_long_path.__name__,
"kwargs": {
"target_path": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\"
"FileSystem\\LongPathsEnabled"
},
}
)
if anaconda_prompt:
plan.append(
{
"function": install_anaconda_prompt.__name__,
"kwargs": {
"target_path": join(
conda_prefix, "condabin", "Anaconda Prompt.lnk"
),
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if on_win:
desktop_dir, exception = get_folder_path(FOLDERID.Desktop)
if exception:
raise RuntimeError(f"Could not get Desktop folder: {exception}")
else:
desktop_dir = join(expanduser("~"), "Desktop")
plan.append(
{
"function": install_anaconda_prompt.__name__,
"kwargs": {
"target_path": join(desktop_dir, "Anaconda Prompt.lnk"),
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
return plan
def make_condabin_plan(conda_prefix, shells, for_user, for_system, reverse=False):
"""
Creates a plan to add $PREFIX/condabin to $PATH.
"""
plan = []
shells = set(shells)
if shells & {"bash", "zsh"}:
if "bash" in shells and for_user:
bashrc_path = expand(
join("~", ".bash_profile" if (on_mac or on_win) else ".bashrc")
)
plan.append(
{
"function": init_sh_user.__name__,
"kwargs": {
"target_path": bashrc_path,
"conda_prefix": conda_prefix,
"shell": "bash",
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if "zsh" in shells and for_user:
if "ZDOTDIR" in os.environ:
zshrc_path = expand(join("$ZDOTDIR", ".zshrc"))
else:
zshrc_path = expand(join("~", ".zshrc"))
plan.append(
{
"function": init_sh_user.__name__,
"kwargs": {
"target_path": zshrc_path,
"conda_prefix": conda_prefix,
"shell": "zsh",
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if for_system:
plan.append(
{
"function": init_sh_system.__name__,
"kwargs": {
"target_path": "/etc/profile.d/conda.sh",
"conda_prefix": conda_prefix,
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if "fish" in shells:
if for_user:
config_fish_path = expand(join("~", ".config", "fish", "config.fish"))
plan.append(
{
"function": init_fish_user.__name__,
"kwargs": {
"target_path": config_fish_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if for_system:
config_fish_path = expand(join("~", ".config", "fish", "config.fish"))
plan.append(
{
"function": init_fish_user.__name__,
"kwargs": {
"target_path": config_fish_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if "xonsh" in shells:
if for_user:
config_xonsh_path = expand(join("~", ".xonshrc"))
plan.append(
{
"function": init_xonsh_user.__name__,
"kwargs": {
"target_path": config_xonsh_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if for_system:
if on_win:
config_xonsh_path = expand(
join("%ALLUSERSPROFILE%", "xonsh", "xonshrc")
)
else:
config_xonsh_path = "/etc/xonshrc"
plan.append(
{
"function": init_xonsh_user.__name__,
"kwargs": {
"target_path": config_xonsh_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if "tcsh" in shells and for_user:
tcshrc_path = expand(join("~", ".tcshrc"))
plan.append(
{
"function": init_sh_user.__name__,
"kwargs": {
"target_path": tcshrc_path,
"conda_prefix": conda_prefix,
"shell": "tcsh",
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if "powershell" in shells:
if for_user:
profile = "$PROFILE.CurrentUserAllHosts"
if for_system:
profile = "$PROFILE.AllUsersAllHosts"
def find_powershell_paths(*exe_names):
for exe_name in exe_names:
try:
yield subprocess_call(
(exe_name, "-NoProfile", "-Command", profile)
).stdout.strip()
except Exception:
pass
config_powershell_paths = set(
find_powershell_paths("powershell", "pwsh", "pwsh-preview")
)
for config_path in config_powershell_paths:
if config_path is not None:
plan.append(
{
"function": init_powershell_user.__name__,
"kwargs": {
"target_path": config_path,
"conda_prefix": conda_prefix,
"reverse": reverse,
"content_type": "add_condabin_to_path",
},
}
)
if "cmd.exe" in shells:
if for_user:
# Modify HKCU\Environment\PATH
plan.append(
{
"function": add_condabin_to_path_registry.__name__,
"kwargs": {
"target_path": "HKEY_CURRENT_USER\\Environment\\PATH",
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
if for_system:
# Modify HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PATH
plan.append(
{
"function": add_condabin_to_path_registry.__name__,
"kwargs": {
"target_path": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\"
"Session Manager\\Environment\\PATH",
"conda_prefix": conda_prefix,
"reverse": reverse,
},
}
)
# Also ensure long paths are enabled if modifying system settings
plan.append(
{
"function": init_long_path.__name__,
"kwargs": {
"target_path": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\"
"FileSystem\\LongPathsEnabled"
},
}
)
# Note: We are *not* modifying AutoRun here for PATH changes,
# only the persistent PATH environment variable. AutoRun is for shell hooks.
return plan
# #####################################################
# plan runners
# #####################################################
def run_plan(plan):
for step in plan:
previous_result = step.get("result", None)
if previous_result in (Result.MODIFIED, Result.NO_CHANGE):
continue
try:
result = globals()[step["function"]](
*step.get("args", ()), **step.get("kwargs", {})
)
except OSError as e:
log.info("%s: %r", step["function"], e, exc_info=True)
result = Result.NEEDS_SUDO
step["result"] = result
def run_plan_elevated(plan):
"""
The strategy of this function differs between unix and Windows. Both strategies use a
subprocess call, where the subprocess is run with elevated privileges. The executable
invoked with the subprocess is `python -m conda.core.initialize`, so see the
`if __name__ == "__main__"` at the bottom of this module.
For unix platforms, we convert the plan list to json, and then call this module with
`sudo python -m conda.core.initialize` while piping the plan json to stdin. We collect json
from stdout for the results of the plan execution with elevated privileges.
For Windows, we create a temporary file that holds the json content of the plan. The
subprocess reads the content of the file, modifies the content of the file with updated
execution status, and then closes the file. This process then reads the content of that file
for the individual operation execution results, and then deletes the file.
"""
if any(step["result"] == Result.NEEDS_SUDO for step in plan):
plan_input = json.dumps(
plan,
ensure_ascii=False,
default=lambda x: x.__dict__,
)
if on_win:
from ..common._os.windows import run_as_admin
temp_path = None
try:
with Utf8NamedTemporaryFile("w+", suffix=".json", delete=False) as tf:
# the default mode is 'w+b', and universal new lines don't work in that mode
tf.write(plan_input)
temp_path = tf.name
python_exe = f'"{abspath(sys.executable)}"'
hinstance, error_code = run_as_admin(
(python_exe, "-m", "conda.core.initialize", f'"{temp_path}"')
)
if error_code is not None:
print(
f"ERROR during elevated execution.\n rc: {error_code}",
file=sys.stderr,
)
with open_utf8(temp_path) as fh:
plan_output = ensure_text_type(fh.read())
finally:
if temp_path and lexists(temp_path):
rm_rf(temp_path)
else:
result = subprocess_call(
f"sudo {sys.executable} -m conda.core.initialize",
env={},
path=os.getcwd(),
stdin=plan_input,
)
stderr = result.stderr.strip()
if stderr:
print(stderr, file=sys.stderr)
plan_output = result.stdout.strip()
plan[:] = json.loads(plan_output)
def run_plan_from_stdin():
stdin = sys.stdin.read().strip()
plan = json.loads(stdin)
run_plan(plan)
sys.stdout.write(json.dumps(plan))
def run_plan_from_temp_file(temp_path):
with open_utf8(temp_path) as fh:
plan = json.loads(ensure_text_type(fh.read()))
run_plan(plan)
with open_utf8(temp_path, "w+b") as fh:
fh.write(ensure_binary(json.dumps(plan, ensure_ascii=False)))
def print_plan_results(plan, stream=None):
if not stream:
stream = sys.stdout
for step in plan:
print(
"%-14s%s" % (step.get("result"), step["kwargs"]["target_path"]), file=stream
)
changed = any(step.get("result") == Result.MODIFIED for step in plan)
if changed:
if context.dry_run:
print(
"\n==> DRY RUN: The above changes would have been made. NO ACTUAL CHANGES WERE MADE. <==\n",
file=stream,
)
else:
print(
"\n==> For changes to take effect, close and re-open your current shell. <==\n",
file=stream,
)
else:
if context.dry_run:
print("DRY RUN: No action would have been taken.", file=stream)
else:
print("No action taken.", file=stream)
# #####################################################
# individual operations
# #####################################################
def make_entry_point(target_path, conda_prefix, module, func):
# 'ep' in this function refers to 'entry point'
# target_path: join(conda_prefix, 'bin', 'conda')
conda_ep_path = target_path
if isfile(conda_ep_path):
with open_utf8(conda_ep_path) as fh:
original_ep_content = fh.read()
else:
original_ep_content = ""
if on_win:
# no shebang needed on windows
new_ep_content = ""
else:
python_path = join(conda_prefix, get_python_short_path())
new_ep_content = generate_shebang_for_entry_point(
python_path, with_usr_bin_env=True
)
conda_extra = dals(
"""
# Before any more imports, leave cwd out of sys.path for internal 'conda shell.*' commands.
# see https://github.com/conda/conda/issues/6549
if len(sys.argv) > 1 and sys.argv[1].startswith('shell.') and sys.path and sys.path[0] == '':
# The standard first entry in sys.path is an empty string,
# and os.path.abspath('') expands to os.getcwd().
del sys.path[0]
"""
)
new_ep_content += dals(
"""
# -*- coding: utf-8 -*-
import sys
%(extra)s
if __name__ == '__main__':
from %(module)s import %(func)s
sys.exit(%(func)s())
"""
) % {
"extra": conda_extra if module == "conda.cli" else "",
"module": module,
"func": func,
}
if new_ep_content != original_ep_content:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(original_ep_content, new_ep_content))
if not context.dry_run:
mkdir_p(dirname(conda_ep_path))
with open_utf8(conda_ep_path, "w") as fdst:
fdst.write(new_ep_content)
if not on_win:
make_executable(conda_ep_path)
return Result.MODIFIED
else:
return Result.NO_CHANGE
def make_entry_point_exe(target_path, conda_prefix):
# target_path: join(conda_prefix, 'Scripts', 'conda.exe')
exe_path = target_path
bits = 8 * struct.calcsize("P")
source_exe_path = join(CONDA_PACKAGE_ROOT, "shell", "cli-%d.exe" % bits)
if isfile(exe_path):
if compute_sum(exe_path, "md5") == compute_sum(source_exe_path, "md5"):
return Result.NO_CHANGE
if not context.dry_run:
if not isdir(dirname(exe_path)):
mkdir_p(dirname(exe_path))
# prefer copy() over create_hard_link_or_copy() because of windows file deletion issues
# with open processes
copy(source_exe_path, exe_path)
return Result.MODIFIED
def install_anaconda_prompt(target_path, conda_prefix, reverse):
# target_path: join(conda_prefix, 'condabin', 'Anaconda Prompt.lnk')
# target: join(os.environ["HOMEPATH"], "Desktop", "Anaconda Prompt.lnk")
icon_path = join(CONDA_PACKAGE_ROOT, "shell", "conda_icon.ico")
target = join(os.environ["HOMEPATH"], "Desktop", "Anaconda Prompt.lnk")
args = (
"/K",
'""{}" && "{}""'.format(
join(conda_prefix, "condabin", "conda_hook.bat"),
join(conda_prefix, "condabin", "conda_auto_activate.bat"),
),
)
# The API for the call to 'create_shortcut' has 3
# required arguments (path, description, filename)
# and 4 optional ones (args, working_dir, icon_path, icon_index).
result = Result.NO_CHANGE
if not context.dry_run:
create_shortcut(
"%windir%\\System32\\cmd.exe",
"Anconda Prompt",
"" + target_path,
" ".join(args),
"" + expanduser("~"),
"" + icon_path,
)
result = Result.MODIFIED
if reverse:
if os.path.isfile(target):
os.remove(target)
result = Result.MODIFIED
return result
def _install_file(target_path, file_content):
if isfile(target_path):
with open_utf8(target_path) as fh:
original_content = fh.read()
else:
original_content = ""
new_content = file_content
if new_content != original_content:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(original_content, new_content))
if not context.dry_run:
mkdir_p(dirname(target_path))
with open_utf8(target_path, "w") as fdst:
fdst.write(new_content)
return Result.MODIFIED
else:
return Result.NO_CHANGE
def install_conda_sh(target_path, conda_prefix):
# target_path: join(conda_prefix, 'etc', 'profile.d', 'conda.sh')
file_content = PosixActivator().hook(auto_activate=False)
return _install_file(target_path, file_content)
def install_Scripts_activate_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'Scripts', 'activate.bat')
src_path = join(CONDA_PACKAGE_ROOT, "shell", "Scripts", "activate.bat")
with open_utf8(src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_activate_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'condabin', 'activate.bat')
src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "activate.bat")
with open_utf8(src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_deactivate_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'condabin', 'deactivate.bat')
src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "deactivate.bat")
with open_utf8(src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_activate(target_path, conda_prefix):
# target_path: join(conda_prefix, BIN_DIRECTORY, 'activate')
src_path = join(CONDA_PACKAGE_ROOT, "shell", "bin", "activate")
file_content = f'#!/bin/sh\n_CONDA_ROOT="{conda_prefix}"\n'
with open_utf8(src_path) as fsrc:
file_content += fsrc.read()
return _install_file(target_path, file_content)
def install_deactivate(target_path, conda_prefix):
# target_path: join(conda_prefix, BIN_DIRECTORY, 'deactivate')
src_path = join(CONDA_PACKAGE_ROOT, "shell", "bin", "deactivate")
file_content = f'#!/bin/sh\n_CONDA_ROOT="{conda_prefix}"\n'
with open_utf8(src_path) as fsrc:
file_content += fsrc.read()
return _install_file(target_path, file_content)
def install_condabin_conda_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'condabin', 'conda.bat')
conda_bat_src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "conda.bat")
with open_utf8(conda_bat_src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_library_bin_conda_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'Library', 'bin', 'conda.bat')
conda_bat_src_path = join(
CONDA_PACKAGE_ROOT, "shell", "Library", "bin", "conda.bat"
)
with open_utf8(conda_bat_src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_condabin_conda_activate_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'condabin', '_conda_activate.bat')
conda_bat_src_path = join(
CONDA_PACKAGE_ROOT, "shell", "condabin", "_conda_activate.bat"
)
with open_utf8(conda_bat_src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_condabin_rename_tmp_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'condabin', 'rename_tmp.bat')
conda_bat_src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "rename_tmp.bat")
with open_utf8(conda_bat_src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_condabin_conda_auto_activate_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'condabin', 'conda_auto_activate.bat')
conda_bat_src_path = join(
CONDA_PACKAGE_ROOT, "shell", "condabin", "conda_auto_activate.bat"
)
with open_utf8(conda_bat_src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_condabin_hook_bat(target_path, conda_prefix):
# target_path: join(conda_prefix, 'condabin', 'conda_hook.bat')
conda_bat_src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "conda_hook.bat")
with open_utf8(conda_bat_src_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_conda_fish(target_path, conda_prefix):
# target_path: join(conda_prefix, 'etc', 'fish', 'conf.d', 'conda.fish')
file_content = FishActivator().hook(auto_activate=False)
return _install_file(target_path, file_content)
def install_conda_psm1(target_path, conda_prefix):
# target_path: join(conda_prefix, 'shell', 'condabin', 'Conda.psm1')
conda_psm1_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "Conda.psm1")
with open_utf8(conda_psm1_path) as fsrc:
file_content = fsrc.read()
return _install_file(target_path, file_content)
def install_conda_hook_ps1(target_path, conda_prefix):
# target_path: join(conda_prefix, 'shell', 'condabin', 'conda-hook.ps1')
file_content = PowerShellActivator().hook(auto_activate=False)
return _install_file(target_path, file_content)
def install_conda_xsh(target_path, conda_prefix):
# target_path: join(site_packages_dir, 'xonsh', 'conda.xsh')
file_content = XonshActivator().hook(auto_activate=False)
return _install_file(target_path, file_content)
def install_conda_csh(target_path, conda_prefix):
# target_path: join(conda_prefix, 'etc', 'profile.d', 'conda.csh')
file_content = CshActivator().hook(auto_activate=False)
return _install_file(target_path, file_content)
def _config_fish_content(conda_prefix):
conda_exe = join(conda_prefix, BIN_DIRECTORY, "conda.exe" if on_win else "conda")
if on_win:
from ..common.path import win_path_to_unix
conda_exe = win_path_to_unix(conda_exe)
conda_initialize_content = dals(
"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
if test -f %(conda_exe)s
eval %(conda_exe)s "shell.fish" "hook" $argv | source
else
if test -f "%(conda_prefix)s/etc/fish/conf.d/conda.fish"
. "%(conda_prefix)s/etc/fish/conf.d/conda.fish"
else
set -x PATH "%(conda_prefix)s/bin" $PATH
end
end
# <<< conda initialize <<<
"""
) % {
"conda_exe": conda_exe,
"conda_prefix": conda_prefix,
}
return conda_initialize_content
def _config_fish_content_to_add_condabin_to_path(conda_prefix):
condabin_dir = join(conda_prefix, "condabin")
if on_win:
from ..common.path import win_path_to_unix
condabin_dir = win_path_to_unix(condabin_dir)
conda_initialize_content = dals(
f"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
set -x PATH "{condabin_dir}" $PATH
# <<< conda initialize <<<
"""
)
return conda_initialize_content
def init_fish_user(
target_path,
conda_prefix,
reverse=False,
content_type: ContentTypeOptions = "initialize",
):
# target_path: ~/.config/config.fish
user_rc_path = target_path
try:
with open_utf8(user_rc_path) as fh:
rc_content = fh.read()
except FileNotFoundError:
rc_content = ""
except:
raise
rc_original_content = rc_content
conda_init_comment = "# commented out by conda initialize"
if content_type == "initialize":
conda_initialize_content = _config_fish_content(conda_prefix)
elif content_type == "add_condabin_to_path":
conda_initialize_content = _config_fish_content_to_add_condabin_to_path(
conda_prefix
)
else:
raise ValueError(
f"Unknown content_type='{content_type}'. Use 'initialize' or 'add_condabin_to_path'."
)
if reverse:
# uncomment any lines that were commented by prior conda init run
rc_content = re.sub(
rf"#\s(.*?)\s*{conda_init_comment}",
r"\1",
rc_content,
flags=re.MULTILINE,
)
# remove any conda init sections added
rc_content = re.sub(
r"^\s*" + CONDA_INITIALIZE_RE_BLOCK,
"",
rc_content,
flags=re.DOTALL | re.MULTILINE,
)
else:
if not on_win:
rc_content = re.sub(
rf"^[ \t]*?(set -gx PATH ([\'\"]?).*?{basename(conda_prefix)}\/bin\2 [^\n]*?\$PATH)"
r"",
rf"# \1 {conda_init_comment}",
rc_content,
flags=re.MULTILINE,
)
rc_content = re.sub(
r"^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*etc\/fish\/conf\.d\/conda\.fish.*?)\n"
r"(conda activate.*?)$",
rf"# \1 {conda_init_comment}\n# \2 {conda_init_comment}",
rc_content,
flags=re.MULTILINE,
)
rc_content = re.sub(
r"^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*etc\/fish\/conda\.d\/conda\.fish.*?)$",
rf"# \1 {conda_init_comment}",
rc_content,
flags=re.MULTILINE,
)
replace_str = "__CONDA_REPLACE_ME_123__"
rc_content = re.sub(
CONDA_INITIALIZE_RE_BLOCK,
replace_str,
rc_content,
flags=re.MULTILINE,
)
# TODO: maybe remove all but last of replace_str, if there's more than one occurrence
rc_content = rc_content.replace(replace_str, conda_initialize_content)
if "# >>> conda initialize >>>" not in rc_content:
rc_content += f"\n{conda_initialize_content}\n"
if rc_content != rc_original_content:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(rc_original_content, rc_content))
if not context.dry_run:
# Make the directory if needed.
if not exists(dirname(user_rc_path)):
mkdir_p(dirname(user_rc_path))
with open_utf8(user_rc_path, "w") as fh:
fh.write(rc_content)
return Result.MODIFIED
else:
return Result.NO_CHANGE
def _config_xonsh_content(conda_prefix):
conda_exe = join(conda_prefix, BIN_DIRECTORY, "conda.exe" if on_win else "conda")
if on_win:
from ..common.path import win_path_to_unix
conda_exe = win_path_to_unix(conda_exe)
conda_initialize_content = dals(
"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
if !(test -f "{conda_exe}"):
import sys as _sys
from types import ModuleType as _ModuleType
_mod = _ModuleType("xontrib.conda",
"Autogenerated from $({conda_exe} shell.xonsh hook)")
__xonsh__.execer.exec($("{conda_exe}" "shell.xonsh" "hook"),
glbs=_mod.__dict__,
filename="$({conda_exe} shell.xonsh hook)")
_sys.modules["xontrib.conda"] = _mod
del _sys, _mod, _ModuleType
# <<< conda initialize <<<
"""
).format(conda_exe=conda_exe)
return conda_initialize_content
def _config_xonsh_content_to_add_condabin_to_path(conda_prefix):
condabin_path = join(conda_prefix, "condabin")
if on_win:
from ..common.path import win_path_to_unix
condabin_path = win_path_to_unix(condabin_path)
return dals(
f"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
$PATH.insert(0, "{condabin_path}")
# <<< conda initialize <<<
"""
)
def init_xonsh_user(
target_path,
conda_prefix,
reverse=False,
content_type: ContentTypeOptions = "initialize",
):
# target_path: ~/.xonshrc
user_rc_path = target_path
try:
with open_utf8(user_rc_path) as fh:
rc_content = fh.read()
except FileNotFoundError:
rc_content = ""
except:
raise
rc_original_content = rc_content
conda_init_comment = "# commented out by conda initialize"
if content_type == "initialize":
conda_initialize_content = _config_xonsh_content(conda_prefix)
elif content_type == "add_condabin_to_path":
conda_initialize_content = _config_xonsh_content_to_add_condabin_to_path(
conda_prefix
)
else:
raise ValueError(
f"Unknown content_type='{content_type}'. Use 'initialize' or 'add_condabin_to_path'."
)
if reverse:
# uncomment any lines that were commented by prior conda init run
rc_content = re.sub(
rf"#\s(.*?)\s*{conda_init_comment}",
r"\1",
rc_content,
flags=re.MULTILINE,
)
# remove any conda init sections added
rc_content = re.sub(
r"^\s*" + CONDA_INITIALIZE_RE_BLOCK,
"",
rc_content,
flags=re.DOTALL | re.MULTILINE,
)
else:
replace_str = "__CONDA_REPLACE_ME_123__"
rc_content = re.sub(
CONDA_INITIALIZE_RE_BLOCK,
replace_str,
rc_content,
flags=re.MULTILINE,
)
# TODO: maybe remove all but last of replace_str, if there's more than one occurrence
rc_content = rc_content.replace(replace_str, conda_initialize_content)
if "# >>> conda initialize >>>" not in rc_content:
rc_content += f"\n{conda_initialize_content}\n"
if rc_content != rc_original_content:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(rc_original_content, rc_content))
if not context.dry_run:
# Make the directory if needed.
if not exists(dirname(user_rc_path)):
mkdir_p(dirname(user_rc_path))
with open_utf8(user_rc_path, "w") as fh:
fh.write(rc_content)
return Result.MODIFIED
else:
return Result.NO_CHANGE
def _bashrc_content(conda_prefix, shell):
conda_exe = join(conda_prefix, BIN_DIRECTORY, "conda.exe" if on_win else "conda")
if on_win:
from ..common.path import win_path_to_unix
conda_exe = win_path_to_unix(conda_exe)
conda_initialize_content = dals(
"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
if [ -f '%(conda_exe)s' ]; then
eval "$('%(conda_exe)s' 'shell.%(shell)s' 'hook')"
fi
# <<< conda initialize <<<
"""
) % {
"conda_exe": conda_exe,
"shell": shell,
}
else:
if shell in ("csh", "tcsh"):
conda_initialize_content = dals(
"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
if ( -f "%(conda_prefix)s/etc/profile.d/conda.csh" ) then
source "%(conda_prefix)s/etc/profile.d/conda.csh"
else
setenv PATH "%(conda_bin)s:$PATH"
endif
# <<< conda initialize <<<
"""
) % {
"conda_exe": conda_exe,
"shell": shell,
"conda_bin": dirname(conda_exe),
"conda_prefix": conda_prefix,
}
else:
conda_initialize_content = dals(
"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('%(conda_exe)s' 'shell.%(shell)s' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "%(conda_prefix)s/etc/profile.d/conda.sh" ]; then
. "%(conda_prefix)s/etc/profile.d/conda.sh"
else
export PATH="%(conda_bin)s:$PATH"
fi
fi
unset __conda_setup
# <<< conda initialize <<<
"""
) % {
"conda_exe": conda_exe,
"shell": shell,
"conda_bin": dirname(conda_exe),
"conda_prefix": conda_prefix,
}
return conda_initialize_content
def _bashrc_content_to_add_condabin_to_path(conda_prefix, shell):
condabin_path = join(conda_prefix, "condabin")
if on_win:
from ..common.path import win_path_to_unix
condabin_path = win_path_to_unix(condabin_path)
return dals(
f"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
if [ -d '{condabin_path}' ]; then
export PATH="{condabin_path}:$PATH"
fi
# <<< conda initialize <<<
"""
)
if shell in ("csh", "tcsh"):
return dals(
f"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
if ( -d "{condabin_path}" ) then
setenv PATH "{condabin_path}:$PATH"
endif
# <<< conda initialize <<<
"""
)
return dals(
f"""
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
export PATH="{condabin_path}:$PATH"
# <<< conda initialize <<<
"""
)
def init_sh_user(
target_path,
conda_prefix,
shell,
reverse=False,
content_type: ContentTypeOptions = "initialize",
):
# target_path: ~/.bash_profile
user_rc_path = target_path
try:
with open_utf8(user_rc_path) as fh:
rc_content = fh.read()
except FileNotFoundError:
rc_content = ""
except:
raise
rc_original_content = rc_content
if content_type == "initialize":
conda_initialize_content = _bashrc_content(conda_prefix, shell)
elif content_type == "add_condabin_to_path":
conda_initialize_content = _bashrc_content_to_add_condabin_to_path(
conda_prefix, shell
)
else:
raise ValueError(
f"Unknown content_type='{content_type}'. Use 'initialize' or 'add_condabin_to_path'."
)
conda_init_comment = "# commented out by conda initialize"
if reverse:
# uncomment any lines that were commented by prior conda init run
rc_content = re.sub(
rf"#\s(.*?)\s*{conda_init_comment}",
r"\1",
rc_content,
flags=re.MULTILINE,
)
# remove any conda init sections added
rc_content = re.sub(
r"^\s*" + CONDA_INITIALIZE_RE_BLOCK,
"",
rc_content,
flags=re.DOTALL | re.MULTILINE,
)
else:
if not on_win:
rc_content = re.sub(
rf"^[ \t]*?(export PATH=[\'\"].*?{basename(conda_prefix)}\/bin:\$PATH[\'\"])"
r"",
rf"# \1 {conda_init_comment}",
rc_content,
flags=re.MULTILINE,
)
rc_content = re.sub(
r"^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*etc\/profile\.d\/conda\.sh.*?)\n"
r"(conda activate.*?)$",
rf"# \1 {conda_init_comment}\n# \2 {conda_init_comment}",
rc_content,
flags=re.MULTILINE,
)
rc_content = re.sub(
r"^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*etc\/profile\.d\/conda\.sh.*?)$",
rf"# \1 {conda_init_comment}",
rc_content,
flags=re.MULTILINE,
)
if on_win:
rc_content = re.sub(
r"^[ \t]*^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*Scripts[/\\]activate.*?)$",
r"# \1 # commented out by conda initialize",
rc_content,
flags=re.MULTILINE,
)
else:
rc_content = re.sub(
r"^[ \t]*^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*bin/activate.*?)$",
r"# \1 # commented out by conda initialize",
rc_content,
flags=re.MULTILINE,
)
replace_str = "__CONDA_REPLACE_ME_123__"
rc_content = re.sub(
CONDA_INITIALIZE_RE_BLOCK,
replace_str,
rc_content,
flags=re.MULTILINE,
)
# TODO: maybe remove all but last of replace_str, if there's more than one occurrence
rc_content = rc_content.replace(replace_str, conda_initialize_content)
if "# >>> conda initialize >>>" not in rc_content:
rc_content += f"\n{conda_initialize_content}\n"
if rc_content != rc_original_content:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(rc_original_content, rc_content))
if not context.dry_run:
with open_utf8(user_rc_path, "w") as fh:
fh.write(rc_content)
return Result.MODIFIED
else:
return Result.NO_CHANGE
def init_sh_system(
target_path,
conda_prefix,
reverse=False,
content_type: ContentTypeOptions = "initialize",
):
# target_path: '/etc/profile.d/conda.sh'
conda_sh_system_path = target_path
if exists(conda_sh_system_path):
with open_utf8(conda_sh_system_path) as fh:
conda_sh_system_contents = fh.read()
else:
conda_sh_system_contents = ""
if reverse:
if exists(conda_sh_system_path):
os.remove(conda_sh_system_path)
return Result.MODIFIED
else:
if content_type == "initialize":
conda_sh_contents = _bashrc_content(conda_prefix, "posix")
elif content_type == "add_condabin_to_path":
conda_sh_contents = _bashrc_content_to_add_condabin_to_path(
conda_prefix, "posix"
)
else:
raise ValueError(
f"Unknown content_type='{content_type}'. "
"Use 'initialize' or 'add_condabin_to_path'."
)
if conda_sh_system_contents != conda_sh_contents:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(conda_sh_contents, conda_sh_system_contents))
if not context.dry_run:
if lexists(conda_sh_system_path):
rm_rf(conda_sh_system_path)
mkdir_p(dirname(conda_sh_system_path))
with open_utf8(conda_sh_system_path, "w") as fh:
fh.write(conda_sh_contents)
return Result.MODIFIED
return Result.NO_CHANGE
def _read_windows_registry(target_path): # pragma: no cover
# HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
# HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
# returns value_value, value_type -or- None, None if target does not exist
main_key, the_rest = target_path.split("\\", 1)
subkey_str, value_name = the_rest.rsplit("\\", 1)
main_key = getattr(winreg, main_key)
try:
key = winreg.OpenKey(main_key, subkey_str, 0, winreg.KEY_READ)
except OSError as e:
if e.errno != ENOENT:
raise
return None, None
try:
value_tuple = winreg.QueryValueEx(key, value_name)
value_value = value_tuple[0]
if isinstance(value_value, str):
value_value = value_value.strip()
value_type = value_tuple[1]
return value_value, value_type
except Exception:
# [WinError 2] The system cannot find the file specified
winreg.CloseKey(key)
return None, None
finally:
winreg.CloseKey(key)
def _write_windows_registry(target_path, value_value, value_type): # pragma: no cover
main_key, the_rest = target_path.split("\\", 1)
subkey_str, value_name = the_rest.rsplit("\\", 1)
main_key = getattr(winreg, main_key)
try:
key = winreg.OpenKey(main_key, subkey_str, 0, winreg.KEY_WRITE)
except OSError as e:
if e.errno != ENOENT:
raise
key = winreg.CreateKey(main_key, subkey_str)
try:
winreg.SetValueEx(key, value_name, 0, value_type, value_value)
finally:
winreg.CloseKey(key)
def init_cmd_exe_registry(target_path, conda_prefix, reverse=False):
# HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
# HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
prev_value, value_type = _read_windows_registry(target_path)
if prev_value is None:
prev_value = ""
value_type = winreg.REG_EXPAND_SZ
old_hook_path = '"{}"'.format(join(conda_prefix, "condabin", "conda_hook.bat"))
new_hook = f"if exist {old_hook_path} {old_hook_path}"
if reverse:
# we can't just reset it to None and remove it, because there may be other contents here.
# We need to strip out our part, and if there's nothing left, remove the key.
# Break up string by parts joined with "&"
autorun_parts = prev_value.split("&")
autorun_parts = [part.strip() for part in autorun_parts if new_hook not in part]
# We must remove the old hook path too if it is there
autorun_parts = [
part.strip() for part in autorun_parts if old_hook_path not in part
]
new_value = " & ".join(autorun_parts)
else:
replace_str = "__CONDA_REPLACE_ME_123__"
# Replace new (if exist checked) hook
new_value = re.sub(
r"(if exist \"[^\"]*?conda[-_]hook\.bat\" \"[^\"]*?conda[-_]hook\.bat\")",
replace_str,
prev_value,
count=1,
flags=re.IGNORECASE | re.UNICODE,
)
# Replace old hook
new_value = re.sub(
r"(\"[^\"]*?conda[-_]hook\.bat\")",
replace_str,
new_value,
flags=re.IGNORECASE | re.UNICODE,
)
# Fold repeats of 'HOOK & HOOK'
new_value_2 = new_value.replace(replace_str + " & " + replace_str, replace_str)
while new_value_2 != new_value:
new_value = new_value_2
new_value_2 = new_value.replace(
replace_str + " & " + replace_str, replace_str
)
new_value = new_value_2.replace(replace_str, new_hook)
if new_hook not in new_value:
if new_value:
new_value += " & " + new_hook
else:
new_value = new_hook
if prev_value != new_value:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(prev_value, new_value))
if not context.dry_run:
_write_windows_registry(target_path, new_value, value_type)
return Result.MODIFIED
else:
return Result.NO_CHANGE
def add_condabin_to_path_registry(target_path, conda_prefix, reverse=False):
# Modifies the PATH environment variable stored in the Windows registry.
# target_path examples:
# - HKEY_CURRENT_USER\Environment\PATH
# - HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PATH
prev_value, value_type = _read_windows_registry(target_path)
if prev_value is None:
prev_value = ""
# PATH is typically REG_EXPAND_SZ, allowing variables like %SystemRoot%
value_type = 2 # winreg.REG_EXPAND_SZ
# The Windows registry always wants backslashes!
condabin_path = join(conda_prefix, "condabin").replace("/", "\\")
# Normalize for case-insensitive comparison, though registry might preserve case
normalized_condabin_path = condabin_path.lower()
# Split PATH, handling potential empty strings from leading/trailing/double semicolons
path_parts = [part for part in prev_value.split(";") if part.strip()]
normalized_path_parts = [part.lower() for part in path_parts]
if reverse:
# Remove condabin_path if present
new_path_parts = [
part
for part, normalized_part in zip(path_parts, normalized_path_parts)
if normalized_part != normalized_condabin_path
]
new_value = ";".join(new_path_parts)
else:
# Add condabin_path if not already present (typically at the beginning)
if normalized_condabin_path not in normalized_path_parts:
# Prepend condabin_path
path_parts.insert(0, condabin_path)
new_value = ";".join(path_parts)
if prev_value != new_value:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(prev_value, new_value))
if not context.dry_run:
_write_windows_registry(target_path, new_value, value_type)
# Notify the system about the environment change (requires user logoff/logon or restart for full effect)
# This part is complex and might require ctypes/pywin32 calls to SendMessageTimeout with HWND_BROADCAST
# For simplicity, we'll rely on the message printed by print_plan_results
return Result.MODIFIED
else:
return Result.NO_CHANGE
def init_long_path(target_path):
win_ver, _, win_rev = context.os_distribution_name_version[1].split(".")
# win10, build 14352 was the first preview release that supported this
if int(win_ver) >= 10 and int(win_rev) >= 14352:
prev_value, value_type = _read_windows_registry(target_path)
if str(prev_value) != "1":
if context.verbose:
print("\n")
print(target_path)
print(make_diff(str(prev_value), "1"))
if not context.dry_run:
_write_windows_registry(target_path, 1, winreg.REG_DWORD)
return Result.MODIFIED
else:
return Result.NO_CHANGE
else:
if context.verbose:
print("\n")
print(
"Not setting long path registry key; Windows version must be at least 10 with "
'the fall 2016 "Anniversary update" or newer.'
)
return Result.NO_CHANGE
def _powershell_profile_content(conda_prefix):
conda_exe = join(conda_prefix, BIN_DIRECTORY, "conda.exe" if on_win else "conda")
conda_powershell_module = dals(
f"""
#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
If (Test-Path "{conda_exe}") {{
(& "{conda_exe}" "shell.powershell" "hook") | Out-String | ?{{$_}} | Invoke-Expression
}}
#endregion
"""
)
return conda_powershell_module
def _powershell_profile_content_to_add_condabin_to_path(conda_prefix):
condabin_dir = join(conda_prefix, "condabin")
return dals(
f"""
#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
$Env:Path = "{condabin_dir}" + [IO.Path]::PathSeparator + $Env:Path
#endregion
"""
)
def init_powershell_user(
target_path,
conda_prefix,
reverse=False,
content_type: ContentTypeOptions = "initialize",
):
# target_path: $PROFILE
profile_path = target_path
# NB: the user may not have created a profile. We need to check
# if the file exists first.
if os.path.exists(profile_path):
with open_utf8(profile_path) as fp:
profile_content = fp.read()
else:
profile_content = ""
profile_original_content = profile_content
# TODO: comment out old ipmos and Import-Modules.
if reverse:
profile_content = re.sub(
CONDA_INITIALIZE_PS_RE_BLOCK,
"",
profile_content,
count=1,
flags=re.DOTALL | re.MULTILINE,
)
else:
# Find what content we need to add.
if content_type == "initialize":
conda_initialize_content = _powershell_profile_content(conda_prefix)
elif content_type == "add_condabin_to_path":
conda_initialize_content = (
_powershell_profile_content_to_add_condabin_to_path(conda_prefix)
)
else:
raise ValueError(
f"Unknown content_type='{content_type}'. Use 'initialize' or 'add_condabin_to_path'."
)
if "#region conda initialize" not in profile_content:
profile_content += f"\n{conda_initialize_content}\n"
else:
profile_content = re.sub(
CONDA_INITIALIZE_PS_RE_BLOCK,
"__CONDA_REPLACE_ME_123__",
profile_content,
count=1,
flags=re.DOTALL | re.MULTILINE,
).replace("__CONDA_REPLACE_ME_123__", conda_initialize_content)
if profile_content != profile_original_content:
if context.verbose:
print("\n")
print(target_path)
print(make_diff(profile_original_content, profile_content))
if not context.dry_run:
# Make the directory if needed.
if not exists(dirname(profile_path)):
mkdir_p(dirname(profile_path))
with open_utf8(profile_path, "w") as fp:
fp.write(profile_content)
return Result.MODIFIED
else:
return Result.NO_CHANGE
def remove_conda_in_sp_dir(target_path):
# target_path: site_packages_dir
modified = False
site_packages_dir = target_path
rm_rf_these = chain.from_iterable(
(
glob(join(site_packages_dir, "conda-*info")),
glob(join(site_packages_dir, "conda.*")),
glob(join(site_packages_dir, "conda-*.egg")),
)
)
rm_rf_these = (p for p in rm_rf_these if not p.endswith("conda.egg-link"))
for fn in rm_rf_these:
print(f"rm -rf {join(site_packages_dir, fn)}", file=sys.stderr)
if not context.dry_run:
rm_rf(join(site_packages_dir, fn))
modified = True
others = (
"conda",
"conda_env",
)
for other in others:
path = join(site_packages_dir, other)
if lexists(path):
print(f"rm -rf {path}", file=sys.stderr)
if not context.dry_run:
rm_rf(path)
modified = True
if modified:
return Result.MODIFIED
else:
return Result.NO_CHANGE
def make_conda_egg_link(target_path, conda_source_root):
# target_path: join(site_packages_dir, 'conda.egg-link')
conda_egg_link_contents = conda_source_root + os.linesep
if isfile(target_path):
with open_utf8(target_path, "rb") as fh:
conda_egg_link_contents_old = fh.read()
else:
conda_egg_link_contents_old = ""
if conda_egg_link_contents_old != conda_egg_link_contents:
if context.verbose:
print("\n", file=sys.stderr)
print(target_path, file=sys.stderr)
print(
make_diff(conda_egg_link_contents_old, conda_egg_link_contents),
file=sys.stderr,
)
if not context.dry_run:
with open_utf8(target_path, "wb") as fh:
fh.write(ensure_utf8_encoding(conda_egg_link_contents))
return Result.MODIFIED
else:
return Result.NO_CHANGE
def modify_easy_install_pth(target_path, conda_source_root):
# target_path: join(site_packages_dir, 'easy-install.pth')
easy_install_new_line = conda_source_root
if isfile(target_path):
with open_utf8(target_path) as fh:
old_contents = fh.read()
else:
old_contents = ""
old_contents_lines = old_contents.splitlines()
if easy_install_new_line in old_contents_lines:
return Result.NO_CHANGE
ln_end = os.sep + "conda"
old_contents_lines = tuple(
ln for ln in old_contents_lines if not ln.endswith(ln_end)
)
new_contents = (
easy_install_new_line
+ os.linesep
+ os.linesep.join(old_contents_lines)
+ os.linesep
)
if context.verbose:
print("\n", file=sys.stderr)
print(target_path, file=sys.stderr)
print(make_diff(old_contents, new_contents), file=sys.stderr)
if not context.dry_run:
with open_utf8(target_path, "wb") as fh:
fh.write(ensure_utf8_encoding(new_contents))
return Result.MODIFIED
def make_dev_egg_info_file(target_path):
# target_path: join(conda_source_root, 'conda.egg-info')
if isfile(target_path):
with open_utf8(target_path) as fh:
old_contents = fh.read()
else:
old_contents = ""
new_contents = (
dals(
"""
Metadata-Version: 1.1
Name: conda
Version: %s
Platform: UNKNOWN
Summary: OS-agnostic, system-level binary package manager.
"""
)
% CONDA_VERSION
)
if old_contents == new_contents:
return Result.NO_CHANGE
if context.verbose:
print("\n", file=sys.stderr)
print(target_path, file=sys.stderr)
print(make_diff(old_contents, new_contents), file=sys.stderr)
if not context.dry_run:
if lexists(target_path):
rm_rf(target_path)
with open_utf8(target_path, "w") as fh:
fh.write(new_contents)
return Result.MODIFIED
# #####################################################
# helper functions
# #####################################################
def make_diff(old, new):
return "\n".join(unified_diff(old.splitlines(), new.splitlines()))
def _get_python_info(prefix):
python_exe = join(prefix, get_python_short_path())
result = subprocess_call(f"{python_exe} --version")
stdout, stderr = result.stdout.strip(), result.stderr.strip()
if stderr:
python_version = stderr.split()[1]
elif stdout: # pragma: no cover
python_version = stdout.split()[1]
else: # pragma: no cover
raise ValueError("No python version information available.")
site_packages_dir = join(
prefix, win_path_ok(get_python_site_packages_short_path(python_version))
)
return python_exe, python_version, site_packages_dir
if __name__ == "__main__":
if on_win:
temp_path = sys.argv[1]
run_plan_from_temp_file(temp_path)
else:
run_plan_from_stdin()
| Result |
python | pydantic__pydantic | pydantic/types.py | {
"start": 13239,
"end": 13942
} | class ____(BaseModel):
positive_float: PositiveFloat
m = Model(positive_float=1.0)
print(repr(m))
#> Model(positive_float=1.0)
try:
Model(positive_float=-1.0)
except ValidationError as e:
print(e.errors())
'''
[
{
'type': 'greater_than',
'loc': ('positive_float',),
'msg': 'Input should be greater than 0',
'input': -1.0,
'ctx': {'gt': 0.0},
'url': 'https://errors.pydantic.dev/2/v/greater_than',
}
]
'''
```
"""
NegativeFloat = Annotated[float, annotated_types.Lt(0)]
"""A float that must be less than zero.
```python
from pydantic import BaseModel, NegativeFloat, ValidationError
| Model |
python | viewflow__viewflow | viewflow/urls/sites.py | {
"start": 1433,
"end": 2885
} | class ____(IndexViewMixin, Viewset):
title = ""
icon: Icon | str = Icon("view_module")
menu_template_name = "viewflow/includes/app_menu.html"
base_template_name = "viewflow/base_page.html"
permission = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
if isinstance(self.icon, str):
self.icon = Icon(self.icon)
def __getattribute__(self, name):
attr = super().__getattribute__(name)
if name == "title" and attr is not None and not attr:
title = camel_case_to_title(
strip_suffixes(
self.__class__.__name__,
["Application", "Viewset", "Admin", "App", "Flow"],
)
)
if not title:
raise ValueError("Application needs a title")
return title
return attr
def _get_resolver_extra(self):
return {"viewset": self, "app": self}
def get_context_data(self, request):
return {}
def has_view_permission(self, user, obj=None):
if self.permission is not None:
if callable(self.permission):
return self.permission(user)
return user.is_authenticated and user.has_perm(self.permission)
return True
def menu_items(self):
for viewset in self._children:
if isinstance(viewset, AppMenuMixin):
yield viewset
| Application |
python | encode__django-rest-framework | tests/test_routers.py | {
"start": 2709,
"end": 4404
} | class ____(viewsets.ViewSet):
@action(detail=False, url_path='list/<int:kwarg>')
def url_path_list(self, request, *args, **kwargs):
kwarg = self.kwargs.get('kwarg', '')
return Response({'kwarg': kwarg})
@action(detail=True, url_path='detail/<int:kwarg>')
def url_path_detail(self, request, *args, **kwargs):
pk = self.kwargs.get('pk', '')
kwarg = self.kwargs.get('kwarg', '')
return Response({'pk': pk, 'kwarg': kwarg})
@action(detail=True, url_path='detail/<int:kwarg>/detail/<int:param>')
def url_path_detail_multiple_params(self, request, *args, **kwargs):
pk = self.kwargs.get('pk', '')
kwarg = self.kwargs.get('kwarg', '')
param = self.kwargs.get('param', '')
return Response({'pk': pk, 'kwarg': kwarg, 'param': param})
notes_router = SimpleRouter()
notes_router.register(r'notes', NoteViewSet)
notes_path_router = SimpleRouter(use_regex_path=False)
notes_path_router.register('notes', NoteViewSet)
notes_path_default_router = DefaultRouter(use_regex_path=False)
notes_path_default_router.register('notes', NoteViewSet)
kwarged_notes_router = SimpleRouter()
kwarged_notes_router.register(r'notes', KWargedNoteViewSet)
namespaced_router = DefaultRouter()
namespaced_router.register(r'example', MockViewSet, basename='example')
empty_prefix_router = SimpleRouter()
empty_prefix_router.register(r'', EmptyPrefixViewSet, basename='empty_prefix')
regex_url_path_router = SimpleRouter()
regex_url_path_router.register(r'', RegexUrlPathViewSet, basename='regex')
url_path_router = SimpleRouter(use_regex_path=False)
url_path_router.register('', UrlPathViewSet, basename='path')
| UrlPathViewSet |
python | wandb__wandb | wandb/sdk/data_types/_dtypes.py | {
"start": 19173,
"end": 23126
} | class ____(Type):
"""A list of homogeneous types."""
name = "list"
types: t.ClassVar[t.List[type]] = [list, tuple, set, frozenset]
def __init__(
self,
element_type: t.Optional[ConvertibleToType] = None,
length: t.Optional[int] = None,
):
if element_type is None:
wb_type: Type = UnknownType()
else:
wb_type = TypeRegistry.type_from_dtype(element_type)
self.params.update({"element_type": wb_type, "length": length})
@classmethod
def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "ListType":
if py_obj is None or not hasattr(py_obj, "__iter__"):
raise TypeError("ListType.from_obj expects py_obj to by list-like")
else:
if hasattr(py_obj, "tolist"):
py_list = py_obj.tolist()
else:
py_list = list(py_obj)
elm_type: Type
if None not in py_list:
elm_type = UnknownType()
else:
elm_type = OptionalType(UnknownType())
for item in py_list:
_elm_type = elm_type.assign(item)
# Commenting this out since we don't want to crash user code at this point, but rather
# retain an invalid internal list type.
# if isinstance(_elm_type, InvalidType):
# raise TypeError(
# "List contained incompatible types. Item at index {}: \n{}".format(
# ndx, elm_type.explain(item, 1)
# )
# )
elm_type = _elm_type
return cls(elm_type, len(py_list))
def assign_type(self, wb_type: "Type") -> t.Union["ListType", InvalidType]:
if isinstance(wb_type, ListType):
assigned_type = self.params["element_type"].assign_type(
wb_type.params["element_type"]
)
if not isinstance(assigned_type, InvalidType):
return ListType(
assigned_type,
None
if self.params["length"] != wb_type.params["length"]
else self.params["length"],
)
return InvalidType()
def assign(
self, py_obj: t.Optional[t.Any] = None
) -> t.Union["ListType", InvalidType]:
if hasattr(py_obj, "__iter__"):
new_element_type = self.params["element_type"]
# The following ignore is needed since the above hasattr(py_obj, "__iter__") enforces iteration
# error: Argument 1 to "list" has incompatible type "Optional[Any]"; expected "Iterable[Any]"
py_list = list(py_obj) # type: ignore
for obj in py_list:
new_element_type = new_element_type.assign(obj)
if isinstance(new_element_type, InvalidType):
return InvalidType()
return ListType(new_element_type, len(py_list))
return InvalidType()
def explain(self, other: t.Any, depth=0) -> str:
exp = super().explain(other, depth)
gap = "".join(["\t"] * depth)
if ( # yes, this is a bit verbose, but the mypy typechecker likes it this way
isinstance(other, list)
or isinstance(other, tuple)
or isinstance(other, set)
or isinstance(other, frozenset)
):
new_element_type = self.params["element_type"]
for ndx, obj in enumerate(list(other)):
_new_element_type = new_element_type.assign(obj)
if isinstance(_new_element_type, InvalidType):
exp += f"\n{gap}Index {ndx}:\n{new_element_type.explain(obj, depth + 1)}"
break
new_element_type = _new_element_type
return exp
def __repr__(self):
return "{}[]".format(self.params["element_type"])
| ListType |
python | ApeWorX__ape | src/ape_networks/config.py | {
"start": 121,
"end": 962
} | class ____(PluginConfig):
"""
A custom network config.
"""
name: str
"""Name of the network e.g. mainnet."""
chain_id: int
"""Chain ID (required)."""
ecosystem: str
"""The name of the ecosystem."""
base_ecosystem_plugin: Optional[str] = None
"""The base ecosystem plugin to use, when applicable. Defaults to the default ecosystem."""
default_provider: str = "node"
"""The default provider plugin to use. Default is the default node provider."""
request_header: dict = {}
"""The HTTP request header."""
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_NETWORKS_")
@property
def is_fork(self) -> bool:
"""
``True`` when the name of the network ends in ``"-fork"``.
"""
return self.name.endswith("-fork")
| CustomNetwork |
python | mlflow__mlflow | tests/tensorflow/test_tensorflow2_autolog.py | {
"start": 17161,
"end": 17795
} | class ____(tf.keras.utils.Sequence):
def __init__(self, batch_size):
self.batch_size = batch_size
def __len__(self):
return 10
def __getitem__(self, idx):
return (np.random.rand(self.batch_size), np.random.rand(self.batch_size)), np.random.rand(
self.batch_size
)
def __generator_multi_input(data, target, batch_size):
data_batches = np.split(data, data.shape[1] // batch_size, axis=1)
target_batches = np.split(target, target.shape[0] // batch_size)
for inputs, output in zip(data_batches, target_batches):
yield tuple(inputs), output
| __SequenceMultiInput |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 238025,
"end": 238326
} | class ____(sgqlc.types.Input):
"""A command to delete the file at the given path as part of a
commit.
"""
__schema__ = github_schema
__field_names__ = ("path",)
path = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="path")
"""The path to delete"""
| FileDeletion |
python | getsentry__sentry | tests/sentry/integrations/api/bases/test_integration.py | {
"start": 381,
"end": 2962
} | class ____(TestCase):
# Since both `IntegrationEndpoint.handle_exception_with_details` and `Endpoint.handle_exception_with_details` potentially
# run, and they both call their own module's copy of `capture_exception`, in order to prove that
# neither one is not called, we assert on the underlying method from the SDK
@patch("sentry_sdk.capture_exception")
def test_handle_rest_framework_exception(
self, mock_capture_exception: MagicMock, mock_stderror_write: MagicMock
):
exc = APIException("There was a problem!")
exc.status_code = 400 # not possible to set in init
request = Request(HttpRequest())
resp = IntegrationEndpoint().handle_exception_with_details(request, exc)
# `APIException`s are handled by Django REST Framework's built-in exception handler, which
# doesn't log errors or report them to Sentry
assert mock_capture_exception.call_count == 0
assert mock_stderror_write.call_count == 0
assert resp.status_code == 400
assert resp.exception is True
@patch("sentry.integrations.api.bases.integration.capture_exception")
def test_handle_exception_503(
self, mock_capture_exception: MagicMock, mock_stderror_write: MagicMock
):
try:
raise ApiError("This is an error", code=503)
except ApiError as exc:
request = Request(HttpRequest())
resp = IntegrationEndpoint().handle_exception_with_details(request, exc)
mock_capture_exception.assert_called_with(exc)
(((s,), _),) = mock_stderror_write.call_args_list
assert (
s.splitlines()[-1]
== "sentry.shared_integrations.exceptions.ApiError: This is an error"
)
assert resp.status_code == 503
assert resp.exception is True
@patch("sentry.api.base.capture_exception")
def test_handle_exception_stdlib(
self, mock_capture_exception: MagicMock, mock_stderror_write: MagicMock
):
try:
raise ValueError("This is an error")
except ValueError as exc:
request = Request(HttpRequest())
resp = IntegrationEndpoint().handle_exception_with_details(request, exc)
assert mock_capture_exception.call_args.args[0] == exc
(((s,), _),) = mock_stderror_write.call_args_list
assert s.splitlines()[-1] == "ValueError: This is an error"
assert resp.status_code == 500
assert resp.exception is True
| IntegrationEndpointTest |
python | TheAlgorithms__Python | conversions/length_conversion.py | {
"start": 1027,
"end": 4019
} | class ____(NamedTuple):
from_factor: float
to_factor: float
TYPE_CONVERSION = {
"millimeter": "mm",
"centimeter": "cm",
"meter": "m",
"kilometer": "km",
"inch": "in",
"inche": "in", # Trailing 's' has been stripped off
"feet": "ft",
"foot": "ft",
"yard": "yd",
"mile": "mi",
}
METRIC_CONVERSION = {
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}
def length_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between length units.
>>> length_conversion(4, "METER", "FEET")
13.12336
>>> length_conversion(4, "M", "FT")
13.12336
>>> length_conversion(1, "meter", "kilometer")
0.001
>>> length_conversion(1, "kilometer", "inch")
39370.1
>>> length_conversion(3, "kilometer", "mile")
1.8641130000000001
>>> length_conversion(2, "feet", "meter")
0.6096
>>> length_conversion(4, "feet", "yard")
1.333329312
>>> length_conversion(1, "inch", "meter")
0.0254
>>> length_conversion(2, "inch", "mile")
3.15656468e-05
>>> length_conversion(2, "centimeter", "millimeter")
20.0
>>> length_conversion(2, "centimeter", "yard")
0.0218722
>>> length_conversion(4, "yard", "meter")
3.6576
>>> length_conversion(4, "yard", "kilometer")
0.0036576
>>> length_conversion(3, "foot", "meter")
0.9144000000000001
>>> length_conversion(3, "foot", "inch")
36.00001944
>>> length_conversion(4, "mile", "kilometer")
6.43736
>>> length_conversion(2, "miles", "InChEs")
126719.753468
>>> length_conversion(3, "millimeter", "centimeter")
0.3
>>> length_conversion(3, "mm", "in")
0.1181103
>>> length_conversion(4, "wrongUnit", "inch")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit'.
Conversion abbreviations are: mm, cm, m, km, in, ft, yd, mi
"""
new_from = from_type.lower().rstrip("s")
new_from = TYPE_CONVERSION.get(new_from, new_from)
new_to = to_type.lower().rstrip("s")
new_to = TYPE_CONVERSION.get(new_to, new_to)
if new_from not in METRIC_CONVERSION:
msg = (
f"Invalid 'from_type' value: {from_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
if new_to not in METRIC_CONVERSION:
msg = (
f"Invalid 'to_type' value: {to_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| FromTo |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 254887,
"end": 255333
} | class ____(sgqlc.types.Input):
"""Ordering options for milestone connections."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(MilestoneOrderField), graphql_name="field")
"""The field to order milestones by."""
direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name="direction")
"""The ordering direction."""
| MilestoneOrder |
python | openai__gym | gym/error.py | {
"start": 4323,
"end": 4453
} | class ____(Error):
"""Error message for retries exceeding set number."""
# Vectorized environments errors
| RetriesExceededError |
python | python__mypy | mypy/server/update.py | {
"start": 22345,
"end": 22602
} | class ____(NamedTuple):
module: str
path: str
remaining: list[tuple[str, str]]
tree: MypyFile | None
# The result of update_module_isolated when there is a blocking error. Items
# are similar to NormalUpdate (but there are fewer).
| NormalUpdate |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/monitoring_job/event_stream.py | {
"start": 1551,
"end": 1936
} | class ____(ABC):
@property
@abstractmethod
def timestamp(self) -> float:
pass
@abstractmethod
def persist_state(
self,
context: OpExecutionContext,
airflow_data: AirflowDefinitionsData,
airflow_instance: AirflowInstance,
) -> None:
"""Persist the state of the event to Dagster."""
pass
@record
| AirflowEvent |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py | {
"start": 5949,
"end": 7260
} | class ____(Benchmark):
r"""
BiggsExp05 objective function.
The BiggsExp05 [1]_ global optimization problem is a multimodal minimization
problem defined as follows
.. math::
\begin{matrix}\ f_{\text{BiggsExp05}}(x) = \sum_{i=1}^{11}
(x_3 e^{-t_i x_1} - x_4 e^{-t_i x_2} + 3 e^{-t_i x_5} - y_i)^2\\
t_i = 0.1i\\
y_i = e^{-t_i} - 5e^{-10 t_i} + 3e^{-4 t_i}\\
\end{matrix}
with :math:`x_i \in [0, 20]` for :math:`i=1, ..., 5`.
*Global optimum*: :math:`f(x) = 0` for :math:`x = [1, 10, 1, 5, 4]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=5):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0.] * 5,
[20.] * 5))
self.global_optimum = [[1., 10., 1., 5., 4.]]
self.fglob = 0
def fun(self, x, *args):
self.nfev += 1
t = arange(1, 12.) * 0.1
y = exp(-t) - 5 * exp(-10 * t) + 3 * exp(-4 * t)
vec = (x[2] * exp(-t * x[0]) - x[3] * exp(-t * x[1])
+ 3 * exp(-t * x[4]) - y) ** 2
return sum(vec)
| BiggsExp05 |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 206969,
"end": 207832
} | class ____(TestCase):
def test_basic(self) -> None:
result = list(mi.takewhile_inclusive(lambda x: x < 5, [1, 4, 6, 4, 1]))
expected = [1, 4, 6]
self.assertEqual(result, expected)
def test_empty_iterator(self) -> None:
result = list(mi.takewhile_inclusive(lambda x: True, []))
expected = []
self.assertEqual(result, expected)
def test_collatz_sequence(self) -> None:
is_even = lambda n: n % 2 == 0
start = 11
result = list(
mi.takewhile_inclusive(
lambda n: n != 1,
mi.iterate(
lambda n: n // 2 if is_even(n) else 3 * n + 1, start
),
)
)
expected = [11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
self.assertEqual(result, expected)
| TakewhileInclusiveTests |
python | python__mypy | mypy/traverser.py | {
"start": 27991,
"end": 28325
} | class ____(FuncCollectorBase):
def __init__(self) -> None:
super().__init__()
self.found = False
def visit_yield_expr(self, o: YieldExpr) -> None:
self.found = True
def has_yield_expression(fdef: FuncBase) -> bool:
seeker = YieldSeeker()
fdef.accept(seeker)
return seeker.found
| YieldSeeker |
python | apache__airflow | providers/teradata/tests/unit/teradata/operators/test_tpt.py | {
"start": 2217,
"end": 12796
} | class ____:
"""
Tests for DdlOperator.
This test suite validates the DdlOperator functionality for:
- Executing DDL statements on Teradata databases
- Parameter validation
- Error handling and error code management
- Template rendering
- Resource cleanup
"""
def setup_method(self, method):
# No MagicMock connections needed; use only string conn_ids in tests
pass
# ----- DDL Execution Tests -----
@patch("airflow.providers.teradata.operators.tpt.TptHook")
def test_ddl_execution(self, mock_tpt_hook):
mock_hook_instance = mock_tpt_hook.return_value
mock_hook_instance.get_conn.return_value = {
"host": "mock_host",
"login": "mock_user",
"password": "mock_pass",
}
mock_hook_instance.execute_ddl.return_value = 0
operator = DdlOperator(
task_id="test_ddl",
ddl=["CREATE TABLE test_db.test_table (id INT)", "CREATE INDEX idx ON test_db.test_table (id)"],
teradata_conn_id="teradata_default",
ddl_job_name="test_ddl_job",
)
result = operator.execute({})
assert result == 0
@patch("airflow.providers.teradata.operators.tpt.TptHook")
def test_ddl_execution_with_multiple_statements(self, mock_tpt_hook):
mock_hook_instance = mock_tpt_hook.return_value
mock_hook_instance.get_conn.return_value = {
"host": "mock_host",
"login": "mock_user",
"password": "mock_pass",
}
mock_hook_instance.execute_ddl.return_value = 0
ddl_statements = [
"CREATE TABLE test_db.customers (customer_id INTEGER, name VARCHAR(100), email VARCHAR(255))",
"CREATE INDEX idx_customer_name ON test_db.customers (name)",
"""CREATE TABLE test_db.orders (
order_id INTEGER,
customer_id INTEGER,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES test_db.customers(customer_id)
)""",
"CREATE PROCEDURE test_db.get_customer(IN p_id INTEGER) BEGIN SELECT * FROM test_db.customers WHERE customer_id = p_id; END;",
]
operator = DdlOperator(
task_id="test_multiple_ddl",
ddl=ddl_statements,
teradata_conn_id="teradata_default",
)
result = operator.execute({})
assert result == 0
# ----- Parameter Validation Tests -----
def test_ddl_parameter_validation(self):
# Test empty DDL list
with pytest.raises(ValueError, match="ddl parameter must be a non-empty list"):
DdlOperator(
task_id="test_empty_ddl",
ddl=[],
teradata_conn_id="teradata_default",
).execute({})
# Test non-list DDL parameter
with pytest.raises(ValueError, match="ddl parameter must be a non-empty list"):
DdlOperator(
task_id="test_non_list_ddl",
ddl="CREATE TABLE test_table (id INT)", # string instead of list
teradata_conn_id="teradata_default",
).execute({})
# Test DDL with empty string
with pytest.raises(ValueError, match="ddl parameter must be a non-empty list"):
DdlOperator(
task_id="test_empty_string_ddl",
ddl=["CREATE TABLE test_table (id INT)", ""],
teradata_conn_id="teradata_default",
).execute({})
# Test DDL with None value
with pytest.raises(ValueError, match="ddl parameter must be a non-empty list"):
DdlOperator(
task_id="test_none_ddl",
ddl=None,
teradata_conn_id="teradata_default",
).execute({})
# Test DDL with list containing non-string values
with pytest.raises(ValueError, match="ddl parameter must be a non-empty list"):
DdlOperator(
task_id="test_non_string_ddl",
ddl=["CREATE TABLE test_table (id INT)", 123],
teradata_conn_id="teradata_default",
).execute({})
@patch("airflow.providers.teradata.operators.tpt.TptHook")
def test_error_list_validation(self, mock_tpt_hook):
mock_hook_instance = mock_tpt_hook.return_value
mock_hook_instance.get_conn.return_value = {
"host": "mock_host",
"login": "mock_user",
"password": "mock_pass",
}
mock_hook_instance.execute_ddl.return_value = 0
# Test with integer error code
operator = DdlOperator(
task_id="test_int_error_list",
ddl=["CREATE TABLE test_table (id INT)"],
error_list=3803, # single integer
teradata_conn_id="teradata_default",
)
result = operator.execute({})
assert result == 0
assert operator.error_list == 3803 # Original value should remain unchanged
# Test with list of integers
operator = DdlOperator(
task_id="test_list_error_list",
ddl=["CREATE TABLE test_table (id INT)"],
error_list=[3803, 3807, 5495], # list of integers
teradata_conn_id="teradata_default",
)
result = operator.execute({})
assert result == 0
assert operator.error_list == [3803, 3807, 5495]
# Test with invalid error_list type (string)
with pytest.raises(ValueError, match="error_list must be an int or a list of ints"):
DdlOperator(
task_id="test_invalid_error_list_string",
ddl=["CREATE TABLE test_table (id INT)"],
error_list="3803", # string instead of int or list
teradata_conn_id="teradata_default",
).execute({})
# Test with invalid error_list type (dict)
with pytest.raises(ValueError, match="error_list must be an int or a list of ints"):
DdlOperator(
task_id="test_invalid_error_list_dict",
ddl=["CREATE TABLE test_table (id INT)"],
error_list={"code": 3803}, # dict instead of int or list
teradata_conn_id="teradata_default",
).execute({})
# ----- Error Handling Tests -----
@patch(
"airflow.providers.teradata.hooks.tpt.TptHook.get_conn",
side_effect=RuntimeError("Connection not found"),
)
def test_ddl_execution_with_error_handling(self, mock_get_conn):
# Configure operator with error list
operator = DdlOperator(
task_id="test_ddl_with_errors",
ddl=[
"DROP TABLE test_db.nonexistent_table", # This might generate error 3807 (object not found)
"CREATE TABLE test_db.new_table (id INT)",
],
error_list=[3807], # Ignore "object does not exist" errors
teradata_conn_id="teradata_default",
)
# Execute and verify RuntimeError is raised
with pytest.raises(RuntimeError, match="Connection not found"):
operator.execute({})
@patch(
"airflow.providers.teradata.hooks.tpt.TptHook.get_conn",
side_effect=RuntimeError("Connection not found"),
)
def test_ddl_execution_error(self, mock_get_conn):
# This test verifies the normal case since we can't easily simulate real DDL errors
# In a real environment, DDL errors would be handled by the TPT hooks
# Configure operator
operator = DdlOperator(
task_id="test_ddl_execution_error",
ddl=["CREATE TABLE test_db.test_table (id INT)"],
teradata_conn_id="teradata_default",
)
# Execute and verify RuntimeError is raised
with pytest.raises(RuntimeError, match="Connection not found"):
operator.execute({})
# ----- Resource Cleanup Tests -----
@patch("airflow.providers.teradata.hooks.tpt.TptHook")
def test_ddl_on_kill(self, mock_tpt_hook):
# Set up mocks
mock_hook_instance = mock_tpt_hook.return_value
# Configure operator
operator = DdlOperator(
task_id="test_ddl_on_kill",
ddl=["CREATE TABLE test_table (id INT)"],
teradata_conn_id="teradata_default",
)
# Set hook manually
operator._hook = mock_hook_instance
# Call on_kill
operator.on_kill()
# Verify hook was cleaned up
mock_hook_instance.on_kill.assert_called_once()
@patch("airflow.providers.teradata.hooks.tpt.TptHook")
def test_ddl_on_kill_no_hook(self, mock_tpt_hook):
# Configure operator
operator = DdlOperator(
task_id="test_ddl_on_kill_no_hook",
ddl=["CREATE TABLE test_table (id INT)"],
teradata_conn_id="teradata_default",
)
# Set hook to None
operator._hook = None
# Call on_kill (should not raise any exceptions)
operator.on_kill()
# ----- Templating Tests -----
@patch("airflow.providers.ssh.hooks.ssh.SSHHook")
@patch("airflow.providers.teradata.operators.tpt.TptHook")
def test_template_ext(self, mock_tpt_hook, mock_ssh_hook):
mock_hook_instance = mock_tpt_hook.return_value
mock_hook_instance.get_conn.return_value = {
"host": "mock_host",
"login": "mock_user",
"password": "mock_pass",
}
mock_hook_instance.execute_ddl.return_value = 0
# Verify template_ext contains .sql
assert ".sql" in DdlOperator.template_ext
operator = DdlOperator(
task_id="test_sql_file",
ddl=["SELECT * FROM test_table;"],
teradata_conn_id="teradata_default",
)
result = operator.execute({})
assert result == 0
# ----- SSL Connection Tests -----
@patch(
"airflow.providers.teradata.hooks.ttu.TtuHook.get_conn",
return_value={"host": "mock_host", "login": "mock_user", "password": "mock_pass"},
)
@patch("airflow.models.Connection")
def test_ddl_with_ssl_connection(self, mock_conn, mock_get_conn):
"""Test DDL operations with SSL-enabled Teradata connection"""
operator = DdlOperator(
task_id="test_ddl_with_ssl_connection",
ddl=["CREATE TABLE test_table (id INT)"],
teradata_conn_id="teradata_ssl",
)
result = operator.execute({})
assert result == 0
mock_get_conn.assert_called()
| TestDdlOperator |
python | ansible__ansible | lib/ansible/_internal/_ssh/_ssh_agent.py | {
"start": 2955,
"end": 3429
} | class ____(t.Protocol):
@classmethod
def from_blob(cls, blob: memoryview | bytes) -> t.Self: ...
@classmethod
def consume_from_blob(cls, blob: memoryview | bytes) -> tuple[t.Self, memoryview | bytes]: ...
def _split_blob(blob: memoryview | bytes, length: int) -> tuple[memoryview | bytes, memoryview | bytes]:
if len(blob) < length:
raise ValueError("_split_blob: unexpected data length")
return blob[:length], blob[length:]
| SupportsFromBlob |
python | sympy__sympy | sympy/tensor/array/expressions/array_expressions.py | {
"start": 63314,
"end": 63794
} | class ____:
"""
Index position, requiring two integers in the constructor:
- arg: the position of the argument in the tensor product,
- rel: the relative position of the index inside the argument.
"""
def __init__(self, arg: int, rel: int):
self.arg = arg
self.rel = rel
def __str__(self):
return f"_IndPos({self.arg}, {self.rel})"
__repr__ = __str__
def __iter__(self):
yield from [self.arg, self.rel]
| _IndPos |
python | wandb__wandb | wandb/vendor/promise-2.3.0/wandb_promise/promise.py | {
"start": 2161,
"end": 28218
} | class ____(Generic[T]):
"""
This is the Promise class that complies
Promises/A+ specification.
"""
# __slots__ = ('_state', '_is_final', '_is_bound', '_is_following', '_is_async_guaranteed',
# '_length', '_handlers', '_fulfillment_handler0', '_rejection_handler0', '_promise0',
# '_is_waiting', '_future', '_trace', '_event_instance'
# )
_state = STATE_PENDING # type: int
_is_final = False
_is_bound = False
_is_following = False
_is_async_guaranteed = False
_length = 0
_handlers = None # type: Dict[int, Union[Callable, Promise, None]]
_fulfillment_handler0 = None # type: Any
_rejection_handler0 = None # type: Any
_promise0 = None # type: Optional[Promise]
_future = None # type: Future
_traceback = None # type: Optional[TracebackType]
# _trace = None
_is_waiting = False
_scheduler = None
def __init__(self, executor=None, scheduler=None):
# type: (Optional[Callable[[Callable[[T], None], Callable[[Exception], None]], None]], Any) -> None
"""
Initialize the Promise into a pending state.
"""
# self._state = STATE_PENDING # type: int
# self._is_final = False
# self._is_bound = False
# self._is_following = False
# self._is_async_guaranteed = False
# self._length = 0
# self._handlers = None # type: Dict[int, Union[Callable, None]]
# self._fulfillment_handler0 = None # type: Union[Callable, partial]
# self._rejection_handler0 = None # type: Union[Callable, partial]
# self._promise0 = None # type: Promise
# self._future = None # type: Future
# self._event_instance = None # type: Event
# self._is_waiting = False
self._scheduler = scheduler
if executor is not None:
self._resolve_from_executor(executor)
# For compatibility reasons
# self.reject = self._deprecated_reject
# self.resolve = self._deprecated_resolve
@property
def scheduler(self):
# type: () -> ImmediateScheduler
return self._scheduler or default_scheduler
@property
def future(self):
# type: (Promise) -> Future
if not self._future:
self._future = Future() # type: ignore
self._then( # type: ignore
self._future.set_result, self._future.set_exception
)
return self._future
def __iter__(self):
# type: () -> Iterator
return iterate_promise(self._target()) # type: ignore
__await__ = __iter__
@deprecated(
"Rejecting directly in a Promise instance is deprecated, as Promise.reject() is now a class method. "
"Please use promise.do_reject() instead.",
name="reject",
)
def _deprecated_reject(self, e):
self.do_reject(e)
@deprecated(
"Resolving directly in a Promise instance is deprecated, as Promise.resolve() is now a class method. "
"Please use promise.do_resolve() instead.",
name="resolve",
)
def _deprecated_resolve(self, value):
self.do_resolve(value)
def _resolve_callback(self, value):
# type: (T) -> None
if value is self:
return self._reject_callback(make_self_resolution_error(), False)
if not self.is_thenable(value):
return self._fulfill(value)
promise = self._try_convert_to_promise(value)._target()
if promise == self:
self._reject(make_self_resolution_error())
return
if promise._state == STATE_PENDING:
len = self._length
if len > 0:
promise._migrate_callback0(self)
for i in range(1, len):
promise._migrate_callback_at(self, i)
self._is_following = True
self._length = 0
self._set_followee(promise)
elif promise._state == STATE_FULFILLED:
self._fulfill(promise._value())
elif promise._state == STATE_REJECTED:
self._reject(promise._reason(), promise._target()._traceback)
def _settled_value(self, _raise=False):
# type: (bool) -> Any
assert not self._is_following
if self._state == STATE_FULFILLED:
return self._rejection_handler0
elif self._state == STATE_REJECTED:
if _raise:
raise_val = self._fulfillment_handler0
raise raise_val.with_traceback(self._traceback)
return self._fulfillment_handler0
def _fulfill(self, value):
# type: (T) -> None
if value is self:
err = make_self_resolution_error()
# self._attach_extratrace(err)
return self._reject(err)
self._state = STATE_FULFILLED
self._rejection_handler0 = value
if self._length > 0:
if self._is_async_guaranteed:
self._settle_promises()
else:
async_instance.settle_promises(self)
def _reject(self, reason, traceback=None):
# type: (Exception, Optional[TracebackType]) -> None
self._state = STATE_REJECTED
self._fulfillment_handler0 = reason
self._traceback = traceback
if self._is_final:
assert self._length == 0
async_instance.fatal_error(reason, self.scheduler)
return
if self._length > 0:
async_instance.settle_promises(self)
else:
self._ensure_possible_rejection_handled()
if self._is_async_guaranteed:
self._settle_promises()
else:
async_instance.settle_promises(self)
def _ensure_possible_rejection_handled(self):
# type: () -> None
# self._rejection_is_unhandled = True
# async_instance.invoke_later(self._notify_unhandled_rejection, self)
pass
def _reject_callback(self, reason, synchronous=False, traceback=None):
# type: (Exception, bool, Optional[TracebackType]) -> None
assert isinstance(
reason, Exception
), "A promise was rejected with a non-error: {}".format(reason)
# trace = ensure_error_object(reason)
# has_stack = trace is reason
# self._attach_extratrace(trace, synchronous and has_stack)
self._reject(reason, traceback)
def _clear_callback_data_index_at(self, index):
# type: (int) -> None
assert not self._is_following
assert index > 0
base = index * CALLBACK_SIZE - CALLBACK_SIZE
self._handlers[base + CALLBACK_PROMISE_OFFSET] = None
self._handlers[base + CALLBACK_FULFILL_OFFSET] = None
self._handlers[base + CALLBACK_REJECT_OFFSET] = None
def _fulfill_promises(self, length, value):
# type: (int, T) -> None
for i in range(1, length):
handler = self._fulfillment_handler_at(i)
promise = self._promise_at(i)
self._clear_callback_data_index_at(i)
self._settle_promise(promise, handler, value, None)
def _reject_promises(self, length, reason):
# type: (int, Exception) -> None
for i in range(1, length):
handler = self._rejection_handler_at(i)
promise = self._promise_at(i)
self._clear_callback_data_index_at(i)
self._settle_promise(promise, handler, reason, None)
def _settle_promise(
self,
promise, # type: Optional[Promise]
handler, # type: Optional[Callable]
value, # type: Union[T, Exception]
traceback, # type: Optional[TracebackType]
):
# type: (...) -> None
assert not self._is_following
is_promise = isinstance(promise, self.__class__)
async_guaranteed = self._is_async_guaranteed
if callable(handler):
if not is_promise:
handler(value) # , promise
else:
if async_guaranteed:
promise._is_async_guaranteed = True # type: ignore
self._settle_promise_from_handler( # type: ignore
handler, value, promise # type: ignore
) # type: ignore
elif is_promise:
if async_guaranteed:
promise._is_async_guaranteed = True # type: ignore
if self._state == STATE_FULFILLED:
promise._fulfill(value) # type: ignore
else:
promise._reject(value, self._traceback) # type: ignore
def _settle_promise0(
self,
handler, # type: Optional[Callable]
value, # type: Any
traceback, # type: Optional[TracebackType]
):
# type: (...) -> None
promise = self._promise0
self._promise0 = None
self._settle_promise(promise, handler, value, traceback) # type: ignore
def _settle_promise_from_handler(self, handler, value, promise):
# type: (Callable, Any, Promise) -> None
value, error_with_tb = try_catch(handler, value) # , promise
if error_with_tb:
error, tb = error_with_tb
promise._reject_callback(error, False, tb)
else:
promise._resolve_callback(value)
def _promise_at(self, index):
# type: (int) -> Optional[Promise]
assert index > 0
assert not self._is_following
return self._handlers.get( # type: ignore
index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_PROMISE_OFFSET
)
def _fulfillment_handler_at(self, index):
# type: (int) -> Optional[Callable]
assert not self._is_following
assert index > 0
return self._handlers.get( # type: ignore
index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_FULFILL_OFFSET
)
def _rejection_handler_at(self, index):
# type: (int) -> Optional[Callable]
assert not self._is_following
assert index > 0
return self._handlers.get( # type: ignore
index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_REJECT_OFFSET
)
def _migrate_callback0(self, follower):
# type: (Promise) -> None
self._add_callbacks(
follower._fulfillment_handler0,
follower._rejection_handler0,
follower._promise0,
)
def _migrate_callback_at(self, follower, index):
self._add_callbacks(
follower._fulfillment_handler_at(index),
follower._rejection_handler_at(index),
follower._promise_at(index),
)
def _add_callbacks(
self,
fulfill, # type: Optional[Callable]
reject, # type: Optional[Callable]
promise, # type: Optional[Promise]
):
# type: (...) -> int
assert not self._is_following
if self._handlers is None:
self._handlers = {}
index = self._length
if index > MAX_LENGTH - CALLBACK_SIZE:
index = 0
self._length = 0
if index == 0:
assert not self._promise0
assert not self._fulfillment_handler0
assert not self._rejection_handler0
self._promise0 = promise
if callable(fulfill):
self._fulfillment_handler0 = fulfill
if callable(reject):
self._rejection_handler0 = reject
else:
base = index * CALLBACK_SIZE - CALLBACK_SIZE
assert (base + CALLBACK_PROMISE_OFFSET) not in self._handlers
assert (base + CALLBACK_FULFILL_OFFSET) not in self._handlers
assert (base + CALLBACK_REJECT_OFFSET) not in self._handlers
self._handlers[base + CALLBACK_PROMISE_OFFSET] = promise
if callable(fulfill):
self._handlers[base + CALLBACK_FULFILL_OFFSET] = fulfill
if callable(reject):
self._handlers[base + CALLBACK_REJECT_OFFSET] = reject
self._length = index + 1
return index
def _target(self):
# type: () -> Promise
ret = self
while ret._is_following:
ret = ret._followee()
return ret
def _followee(self):
# type: () -> Promise
assert self._is_following
assert isinstance(self._rejection_handler0, Promise)
return self._rejection_handler0
def _set_followee(self, promise):
# type: (Promise) -> None
assert self._is_following
assert not isinstance(self._rejection_handler0, Promise)
self._rejection_handler0 = promise
def _settle_promises(self):
# type: () -> None
length = self._length
if length > 0:
if self._state == STATE_REJECTED:
reason = self._fulfillment_handler0
traceback = self._traceback
self._settle_promise0(self._rejection_handler0, reason, traceback)
self._reject_promises(length, reason)
else:
value = self._rejection_handler0
self._settle_promise0(self._fulfillment_handler0, value, None)
self._fulfill_promises(length, value)
self._length = 0
def _resolve_from_executor(self, executor):
# type: (Callable[[Callable[[T], None], Callable[[Exception], None]], None]) -> None
# self._capture_stacktrace()
synchronous = True
def resolve(value):
# type: (T) -> None
self._resolve_callback(value)
def reject(reason, traceback=None):
# type: (Exception, TracebackType) -> None
self._reject_callback(reason, synchronous, traceback)
error = None
traceback = None
try:
executor(resolve, reject)
except Exception as e:
traceback = exc_info()[2]
error = e
synchronous = False
if error is not None:
self._reject_callback(error, True, traceback)
@classmethod
def wait(cls, promise, timeout=None):
# type: (Promise, Optional[float]) -> None
async_instance.wait(promise, timeout)
def _wait(self, timeout=None):
# type: (Optional[float]) -> None
self.wait(self, timeout)
def get(self, timeout=None):
# type: (Optional[float]) -> T
target = self._target()
self._wait(timeout or DEFAULT_TIMEOUT)
return self._target_settled_value(_raise=True)
def _target_settled_value(self, _raise=False):
# type: (bool) -> Any
return self._target()._settled_value(_raise)
_value = _reason = _target_settled_value
value = reason = property(_target_settled_value)
def __repr__(self):
# type: () -> str
hex_id = hex(id(self))
if self._is_following:
return "<Promise at {} following {}>".format(hex_id, self._target())
state = self._state
if state == STATE_PENDING:
return "<Promise at {} pending>".format(hex_id)
elif state == STATE_FULFILLED:
return "<Promise at {} fulfilled with {}>".format(
hex_id, repr(self._rejection_handler0)
)
elif state == STATE_REJECTED:
return "<Promise at {} rejected with {}>".format(
hex_id, repr(self._fulfillment_handler0)
)
return "<Promise unknown>"
@property
def is_pending(self):
# type: (Promise) -> bool
"""Indicate whether the Promise is still pending. Could be wrong the moment the function returns."""
return self._target()._state == STATE_PENDING
@property
def is_fulfilled(self):
# type: (Promise) -> bool
"""Indicate whether the Promise has been fulfilled. Could be wrong the moment the function returns."""
return self._target()._state == STATE_FULFILLED
@property
def is_rejected(self):
# type: (Promise) -> bool
"""Indicate whether the Promise has been rejected. Could be wrong the moment the function returns."""
return self._target()._state == STATE_REJECTED
def catch(self, on_rejection):
# type: (Promise, Callable[[Exception], Any]) -> Promise
"""
This method returns a Promise and deals with rejected cases only.
It behaves the same as calling Promise.then(None, on_rejection).
"""
return self.then(None, on_rejection)
def _then(
self,
did_fulfill=None, # type: Optional[Callable[[T], S]]
did_reject=None, # type: Optional[Callable[[Exception], S]]
):
# type: (...) -> Promise[S]
promise = self.__class__() # type: Promise
target = self._target()
state = target._state
if state == STATE_PENDING:
target._add_callbacks(did_fulfill, did_reject, promise)
else:
traceback = None
if state == STATE_FULFILLED:
value = target._rejection_handler0
handler = did_fulfill
elif state == STATE_REJECTED:
value = target._fulfillment_handler0
traceback = target._traceback
handler = did_reject # type: ignore
# target._rejection_is_unhandled = False
async_instance.invoke(
partial(target._settle_promise, promise, handler, value, traceback),
promise.scheduler
# target._settle_promise instead?
# settler,
# target,
)
return promise
fulfill = _resolve_callback
do_resolve = _resolve_callback
do_reject = _reject_callback
def then(self, did_fulfill=None, did_reject=None):
# type: (Promise, Callable[[T], S], Optional[Callable[[Exception], S]]) -> Promise[S]
"""
This method takes two optional arguments. The first argument
is used if the "self promise" is fulfilled and the other is
used if the "self promise" is rejected. In either case, this
method returns another promise that effectively represents
the result of either the first of the second argument (in the
case that the "self promise" is fulfilled or rejected,
respectively).
Each argument can be either:
* None - Meaning no action is taken
* A function - which will be called with either the value
of the "self promise" or the reason for rejection of
the "self promise". The function may return:
* A value - which will be used to fulfill the promise
returned by this method.
* A promise - which, when fulfilled or rejected, will
cascade its value or reason to the promise returned
by this method.
* A value - which will be assigned as either the value
or the reason for the promise returned by this method
when the "self promise" is either fulfilled or rejected,
respectively.
:type success: (Any) -> object
:type failure: (Any) -> object
:rtype : Promise
"""
return self._then(did_fulfill, did_reject)
def done(self, did_fulfill=None, did_reject=None):
# type: (Optional[Callable], Optional[Callable]) -> None
promise = self._then(did_fulfill, did_reject)
promise._is_final = True
def done_all(self, handlers=None):
# type: (Promise, Optional[List[Union[Dict[str, Optional[Callable]], Tuple[Callable, Callable], Callable]]]) -> None
"""
:type handlers: list[(Any) -> object] | list[((Any) -> object, (Any) -> object)]
"""
if not handlers:
return
for handler in handlers:
if isinstance(handler, tuple):
s, f = handler
self.done(s, f)
elif isinstance(handler, dict):
s = handler.get("success") # type: ignore
f = handler.get("failure") # type: ignore
self.done(s, f)
else:
self.done(handler)
def then_all(self, handlers=None):
# type: (Promise, List[Callable]) -> List[Promise]
"""
Utility function which calls 'then' for each handler provided. Handler can either
be a function in which case it is used as success handler, or a tuple containing
the success and the failure handler, where each of them could be None.
:type handlers: list[(Any) -> object] | list[((Any) -> object, (Any) -> object)]
:param handlers
:rtype : list[Promise]
"""
if not handlers:
return []
promises = [] # type: List[Promise]
for handler in handlers:
if isinstance(handler, tuple):
s, f = handler
promises.append(self.then(s, f))
elif isinstance(handler, dict):
s = handler.get("success")
f = handler.get("failure")
promises.append(self.then(s, f))
else:
promises.append(self.then(handler))
return promises
@classmethod
def _try_convert_to_promise(cls, obj):
# type: (Any) -> Promise
_type = obj.__class__
if issubclass(_type, Promise):
if cls is not Promise:
return cls(obj.then, obj._scheduler)
return obj
if iscoroutine(obj): # type: ignore
obj = ensure_future(obj) # type: ignore
_type = obj.__class__
if is_future_like(_type):
def executor(resolve, reject):
# type: (Callable, Callable) -> None
if obj.done():
_process_future_result(resolve, reject)(obj)
else:
obj.add_done_callback(_process_future_result(resolve, reject))
# _process_future_result(resolve, reject)(obj)
promise = cls(executor) # type: Promise
promise._future = obj
return promise
return obj
@classmethod
def reject(cls, reason):
# type: (Exception) -> Promise
ret = cls() # type: Promise
# ret._capture_stacktrace();
# ret._rejectCallback(reason, true);
ret._reject_callback(reason, True)
return ret
rejected = reject
@classmethod
def resolve(cls, obj):
# type: (T) -> Promise[T]
if not cls.is_thenable(obj):
ret = cls() # type: Promise
# ret._capture_stacktrace()
ret._state = STATE_FULFILLED
ret._rejection_handler0 = obj
return ret
return cls._try_convert_to_promise(obj)
cast = resolve
fulfilled = cast
@classmethod
def promisify(cls, f):
# type: (Callable) -> Callable[..., Promise]
if not callable(f):
warn(
"Promise.promisify is now a function decorator, please use Promise.resolve instead."
)
return cls.resolve(f)
@wraps(f)
def wrapper(*args, **kwargs):
# type: (*Any, **Any) -> Promise
def executor(resolve, reject):
# type: (Callable, Callable) -> Optional[Any]
return resolve(f(*args, **kwargs))
return cls(executor)
return wrapper
_safe_resolved_promise = None # type: Promise
@classmethod
def safe(cls, fn):
# type: (Callable) -> Callable
from functools import wraps
if not cls._safe_resolved_promise:
cls._safe_resolved_promise = Promise.resolve(None)
@wraps(fn)
def wrapper(*args, **kwargs):
# type: (*Any, **Any) -> Promise
return cls._safe_resolved_promise.then(lambda v: fn(*args, **kwargs))
return wrapper
@classmethod
def all(cls, promises):
# type: (Any) -> Promise
return PromiseList(promises, promise_class=cls).promise
@classmethod
def for_dict(cls, m):
# type: (Dict[Hashable, Promise[S]]) -> Promise[Dict[Hashable, S]]
"""
A special function that takes a dictionary of promises
and turns them into a promise for a dictionary of values.
In other words, this turns an dictionary of promises for values
into a promise for a dictionary of values.
"""
dict_type = type(m) # type: Type[Dict]
if not m:
return cls.resolve(dict_type()) # type: ignore
def handle_success(resolved_values):
# type: (List[S]) -> Dict[Hashable, S]
return dict_type(zip(m.keys(), resolved_values))
return cls.all(m.values()).then(handle_success)
@classmethod
def is_thenable(cls, obj):
# type: (Any) -> bool
"""
A utility function to determine if the specified
object is a promise using "duck typing".
"""
_type = obj.__class__
if obj is None or _type in BASE_TYPES:
return False
return (
issubclass(_type, Promise)
or iscoroutine(obj) # type: ignore
or is_future_like(_type)
)
_type_done_callbacks = WeakKeyDictionary() # type: MutableMapping[type, bool]
def is_future_like(_type):
# type: (type) -> bool
if _type not in _type_done_callbacks:
_type_done_callbacks[_type] = callable(
getattr(_type, "add_done_callback", None)
)
return _type_done_callbacks[_type]
promisify = Promise.promisify
promise_for_dict = Promise.for_dict
is_thenable = Promise.is_thenable
def _process_future_result(resolve, reject):
# type: (Callable, Callable) -> Callable
def handle_future_result(future):
# type: (Any) -> None
try:
resolve(future.result())
except Exception as e:
tb = exc_info()[2]
reject(e, tb)
return handle_future_result
| Promise |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 862324,
"end": 862726
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field(ProjectV2SortByField, graphql_name="node")
"""The item at the end of the edge."""
| ProjectV2SortByFieldEdge |
python | pytorch__pytorch | torch/_library/simple_registry.py | {
"start": 1922,
"end": 2949
} | class ____:
def __init__(self, qualname: str) -> None:
self._data: dict[type, Callable[..., Any]] = {}
self.qualname: str = qualname
def register(
self, torch_dispatch_class: type, func: Callable[..., Any]
) -> RegistrationHandle:
if self.find(torch_dispatch_class):
raise RuntimeError(
f"{torch_dispatch_class} already has a `__torch_dispatch__` rule registered for {self.qualname}"
)
self._data[torch_dispatch_class] = func
def deregister() -> None:
del self._data[torch_dispatch_class]
return RegistrationHandle(deregister)
def find(self, torch_dispatch_class: type) -> Optional[Callable[..., Any]]:
return self._data.get(torch_dispatch_class, None)
def find_torch_dispatch_rule(
op: Any, torch_dispatch_class: type
) -> Optional[Callable[..., Any]]:
return singleton.find(op.__qualname__).torch_dispatch_rules.find(
torch_dispatch_class
)
| GenericTorchDispatchRuleHolder |
python | wepe__MachineLearning | DeepLearning Tutorials/cnn_LeNet/convolutional_mlp_commentate.py | {
"start": 3363,
"end": 5124
} | class ____(object):
def __init__(self, rng, input, n_in, n_out, W=None, b=None,
activation=T.tanh):
self.input = input #类HiddenLayer的input即所传递进来的input
"""
注释:
代码要兼容GPU,则必须使用 dtype=theano.config.floatX,并且定义为theano.shared
另外,W的初始化有个规则:如果使用tanh函数,则在-sqrt(6./(n_in+n_hidden))到sqrt(6./(n_in+n_hidden))之间均匀
抽取数值来初始化W,若时sigmoid函数,则以上再乘4倍。
"""
#如果W未初始化,则根据上述方法初始化。
#加入这个判断的原因是:有时候我们可以用训练好的参数来初始化W,见我的上一篇文章。
if W is None:
W_values = numpy.asarray(
rng.uniform(
low=-numpy.sqrt(6. / (n_in + n_out)),
high=numpy.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)
),
dtype=theano.config.floatX
)
if activation == theano.tensor.nnet.sigmoid:
W_values *= 4
W = theano.shared(value=W_values, name='W', borrow=True)
if b is None:
b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
b = theano.shared(value=b_values, name='b', borrow=True)
#用上面定义的W、b来初始化类HiddenLayer的W、b
self.W = W
self.b = b
#隐含层的输出
lin_output = T.dot(input, self.W) + self.b
self.output = (
lin_output if activation is None
else activation(lin_output)
)
#隐含层的参数
self.params = [self.W, self.b]
"""
定义分类层LogisticRegression,也即Softmax回归
在deeplearning tutorial中,直接将LogisticRegression视为Softmax,
而我们所认识的二类别的逻辑回归就是当n_out=2时的LogisticRegression
"""
#参数说明:
#input,大小就是(n_example,n_in),其中n_example是一个batch的大小,
#因为我们训练时用的是Minibatch SGD,因此input这样定义
#n_in,即上一层(隐含层)的输出
#n_out,输出的类别数
| HiddenLayer |
python | getsentry__sentry | tests/sentry/codecov/endpoints/test_repository_tokens.py | {
"start": 1649,
"end": 6990
} | class ____(APITestCase):
endpoint_name = "sentry-api-0-repository-tokens"
def setUp(self) -> None:
super().setUp()
self.organization = self.create_organization(owner=self.user)
self.integration = self.create_integration(
organization=self.organization,
external_id="1234",
name="testowner",
provider="github",
status=ObjectStatus.ACTIVE,
)
self.login_as(user=self.user)
def reverse_url(self, owner="testowner"):
"""Custom reverse URL method to handle required URL parameters"""
return reverse(
self.endpoint_name,
kwargs={
"organization_id_or_slug": self.organization.slug,
"owner": self.integration.id,
},
)
@patch("sentry.codecov.endpoints.repository_tokens.repository_tokens.CodecovApiClient")
def test_get_returns_mock_response_with_default_variables(
self, mock_codecov_client_class: MagicMock
) -> None:
mock_codecov_client_instance = Mock()
mock_response = Mock()
mock_response.json.return_value = mock_graphql_response_populated
mock_codecov_client_instance.query.return_value = mock_response
mock_codecov_client_class.return_value = mock_codecov_client_instance
url = self.reverse_url()
response = self.client.get(url)
mock_codecov_client_class.assert_called_once_with(git_provider_org="testowner")
# Verify the correct variables are passed to the GraphQL query
expected_variables = {
"owner": "testowner",
"direction": "DESC",
"ordering": "COMMIT_DATE",
"first": 25,
"last": None,
"after": None,
"before": None,
}
mock_codecov_client_instance.query.assert_called_once()
call_args = mock_codecov_client_instance.query.call_args
assert call_args[1]["variables"] == expected_variables
assert response.status_code == 200
assert len(response.data["results"]) == 2
assert response.data["results"][0]["name"] == "test-repo-one"
assert response.data["results"][0]["token"] == "sk_test_token_12345abcdef"
assert response.data["results"][1]["name"] == "test-repo-two"
assert response.data["results"][1]["token"] == "sk_test_token_67890ghijkl"
assert response.data["pageInfo"]["endCursor"] == "cursor123"
assert response.data["pageInfo"]["hasNextPage"] is True
assert response.data["pageInfo"]["hasPreviousPage"] is False
assert response.data["pageInfo"]["startCursor"] == "cursor001"
assert response.data["totalCount"] == 2
serializer_fields = set(NodeSerializer().fields.keys())
response_keys = set(response.data["results"][0].keys())
assert (
response_keys == serializer_fields
), f"Response keys {response_keys} don't match serializer fields {serializer_fields}"
@patch("sentry.codecov.endpoints.repository_tokens.repository_tokens.CodecovApiClient")
def test_get_with_query_parameters(self, mock_codecov_client_class: MagicMock) -> None:
mock_codecov_client_instance = Mock()
mock_response = Mock()
mock_response.json.return_value = mock_graphql_response_empty
mock_codecov_client_instance.query.return_value = mock_response
mock_codecov_client_class.return_value = mock_codecov_client_instance
url = self.reverse_url()
query_params = {
"cursor": "cursor123",
"limit": "5",
"navigation": "prev",
"sortBy": "-NAME",
}
response = self.client.get(url, query_params)
expected_variables = {
"owner": "testowner",
"direction": "DESC",
"ordering": "NAME",
"first": None,
"last": 5,
"before": "cursor123",
"after": None,
}
call_args = mock_codecov_client_instance.query.call_args
assert call_args[1]["variables"] == expected_variables
assert response.status_code == 200
def test_get_with_negative_limit_returns_bad_request(self) -> None:
url = self.reverse_url()
query_params = {"limit": "-5"}
response = self.client.get(url, query_params)
assert response.status_code == 400
assert response.data == {"details": "provided `limit` parameter must be a positive integer"}
def test_get_with_zero_limit_returns_bad_request(self) -> None:
url = self.reverse_url()
query_params = {"limit": "0"}
response = self.client.get(url, query_params)
assert response.status_code == 400
assert response.data == {"details": "provided `limit` parameter must be a positive integer"}
def test_get_with_invalid_sort_field_returns_bad_request(self) -> None:
"""Test that invalid sort fields return 400 error."""
url = self.reverse_url()
query_params = {"sortBy": "INVALID_FIELD"}
response = self.client.get(url, query_params)
assert response.status_code == 400
assert response.data == {
"details": "Invalid sortBy parameter. Allowed values: COMMIT_DATE, NAME"
}
| RepositoryTokensEndpointTest |
python | pytorch__pytorch | torch/_higher_order_ops/wrap.py | {
"start": 2979,
"end": 4114
} | class ____(HigherOrderOperator):
def __init__(self):
super().__init__("wrap_with_autocast")
def __call__(
self,
device_type: str,
dtype: Optional[_dtype],
enabled: bool,
cache_enabled: Optional[bool],
wrapped_func,
*args,
**kwargs,
):
# Dynamo already traces the body of HigherOrderOp beforehand when it
# so no need to trace into it.
import torch._dynamo # noqa: F401
from torch._dynamo import disable
@disable
def wrapper():
with torch.autocast(device_type, dtype, enabled, cache_enabled):
return wrapped_func(*args, **kwargs)
return wrapper()
wrap_with_autocast = WrapWithAutocast()
# This HOP allows you to bypass dynamo tracing of the wrapper function while
# still tracing the inner function.
# Takes two callables: The first, `wrapper_fn`, accepts `inner_fn` and returns a
# callable with the same signature. The second is the `inner_fn` itself. Any
# extra *args and **kwargs are forwarded to `wrapper_fn(inner_fn)` when it is
# executed.
| WrapWithAutocast |
python | justquick__django-activity-stream | actstream/feeds.py | {
"start": 6960,
"end": 7615
} | class ____(AbstractActivityStream, View):
"""
Feed that generates feeds compatible with the v1.0 JSON Activity Stream spec
"""
def dispatch(self, request, *args, **kwargs):
return HttpResponse(self.serialize(request, *args, **kwargs),
content_type='application/json')
def serialize(self, request, *args, **kwargs):
items = self.items(request, *args, **kwargs)
return json.dumps({
'totalItems': len(items),
'items': [self.format(action) for action in items]
}, indent=4 if 'pretty' in request.GET or 'pretty' in request.POST else None)
| JSONActivityFeed |
python | pydata__xarray | xarray/indexes/nd_point_index.py | {
"start": 3095,
"end": 13370
} | class ____(Index, Generic[T_TreeAdapter]):
"""Xarray index for irregular, n-dimensional data.
This index may be associated with a set of coordinate variables representing
the arbitrary location of data points in an n-dimensional space. All
coordinates must have the same shape and dimensions. The number of
associated coordinate variables must correspond to the number of dimensions
of the space.
This index supports label-based selection (nearest neighbor lookup). It also
has limited support for alignment.
By default, this index relies on :py:class:`scipy.spatial.KDTree` for fast
lookup.
Do not use :py:meth:`~xarray.indexes.NDPointIndex.__init__` directly. Instead
use :py:meth:`xarray.Dataset.set_xindex` or
:py:meth:`xarray.DataArray.set_xindex` to create and set the index from
existing coordinates (see the example below).
Examples
--------
An example using a dataset with 2-dimensional coordinates.
>>> xx = [[1.0, 2.0], [3.0, 0.0]]
>>> yy = [[11.0, 21.0], [29.0, 9.0]]
>>> ds = xr.Dataset(coords={"xx": (("y", "x"), xx), "yy": (("y", "x"), yy)})
>>> ds
<xarray.Dataset> Size: 64B
Dimensions: (y: 2, x: 2)
Coordinates:
xx (y, x) float64 32B 1.0 2.0 3.0 0.0
yy (y, x) float64 32B 11.0 21.0 29.0 9.0
Dimensions without coordinates: y, x
Data variables:
*empty*
Creation of a NDPointIndex from the "xx" and "yy" coordinate variables:
>>> ds = ds.set_xindex(("xx", "yy"), xr.indexes.NDPointIndex)
>>> ds
<xarray.Dataset> Size: 64B
Dimensions: (y: 2, x: 2)
Coordinates:
* xx (y, x) float64 32B 1.0 2.0 3.0 0.0
* yy (y, x) float64 32B 11.0 21.0 29.0 9.0
Dimensions without coordinates: y, x
Data variables:
*empty*
Indexes:
┌ xx NDPointIndex (ScipyKDTreeAdapter)
└ yy
Point-wise (nearest-neighbor) data selection using Xarray's advanced
indexing, i.e., using arbitrary dimension(s) for the Variable objects passed
as labels:
>>> ds.sel(
... xx=xr.Variable("points", [1.9, 0.1]),
... yy=xr.Variable("points", [13.0, 8.0]),
... method="nearest",
... )
<xarray.Dataset> Size: 32B
Dimensions: (points: 2)
Coordinates:
xx (points) float64 16B 1.0 0.0
yy (points) float64 16B 11.0 9.0
Dimensions without coordinates: points
Data variables:
*empty*
Data selection with scalar labels:
>>> ds.sel(xx=1.9, yy=13.0, method="nearest")
<xarray.Dataset> Size: 16B
Dimensions: ()
Coordinates:
xx float64 8B 1.0
yy float64 8B 11.0
Data variables:
*empty*
Data selection with broadcasting the input labels:
>>> ds.sel(xx=1.9, yy=xr.Variable("points", [13.0, 8.0]), method="nearest")
<xarray.Dataset> Size: 32B
Dimensions: (points: 2)
Coordinates:
xx (points) float64 16B 1.0 0.0
yy (points) float64 16B 11.0 9.0
Dimensions without coordinates: points
Data variables:
*empty*
>>> da = xr.DataArray(
... [[45.1, 53.3], [65.4, 78.2]],
... coords={"u": [1.9, 0.1], "v": [13.0, 8.0]},
... dims=("u", "v"),
... )
>>> ds.sel(xx=da.u, yy=da.v, method="nearest")
<xarray.Dataset> Size: 64B
Dimensions: (u: 2, v: 2)
Coordinates:
xx (u, v) float64 32B 1.0 0.0 1.0 0.0
yy (u, v) float64 32B 11.0 9.0 11.0 9.0
Dimensions without coordinates: u, v
Data variables:
*empty*
Data selection with array-like labels (implicit dimensions):
>>> ds.sel(xx=[[1.9], [0.1]], yy=[[13.0], [8.0]], method="nearest")
<xarray.Dataset> Size: 32B
Dimensions: (y: 2, x: 1)
Coordinates:
xx (y, x) float64 16B 1.0 0.0
yy (y, x) float64 16B 11.0 9.0
Dimensions without coordinates: y, x
Data variables:
*empty*
"""
_tree_obj: T_TreeAdapter
_coord_names: tuple[Hashable, ...]
_dims: tuple[Hashable, ...]
_shape: tuple[int, ...]
def __init__(
self,
tree_obj: T_TreeAdapter,
*,
coord_names: tuple[Hashable, ...],
dims: tuple[Hashable, ...],
shape: tuple[int, ...],
):
# this constructor is "private"
assert isinstance(tree_obj, TreeAdapter)
self._tree_obj = tree_obj
assert len(coord_names) == len(dims) == len(shape)
self._coord_names = coord_names
self._dims = dims
self._shape = shape
@classmethod
def from_variables(
cls,
variables: Mapping[Any, Variable],
*,
options: Mapping[str, Any],
) -> Self:
if len({var.dims for var in variables.values()}) > 1:
var_names = ",".join(vn for vn in variables)
raise ValueError(
f"variables {var_names} must all have the same dimensions and the same shape"
)
var0 = next(iter(variables.values()))
if len(variables) != len(var0.dims):
raise ValueError(
f"the number of variables {len(variables)} doesn't match "
f"the number of dimensions {len(var0.dims)}"
)
opts = dict(options)
tree_adapter_cls: type[T_TreeAdapter] = opts.pop("tree_adapter_cls", None)
if tree_adapter_cls is None:
tree_adapter_cls = ScipyKDTreeAdapter
points = get_points(variables.values())
return cls(
tree_adapter_cls(points, options=opts),
coord_names=tuple(variables),
dims=var0.dims,
shape=var0.shape,
)
def create_variables(
self, variables: Mapping[Any, Variable] | None = None
) -> dict[Any, Variable]:
if variables is not None:
for var in variables.values():
# maybe re-sync variable dimensions with the index object
# returned by NDPointIndex.rename()
if var.dims != self._dims:
var.dims = self._dims
return dict(**variables)
else:
return {}
def equals(
self, other: Index, *, exclude: frozenset[Hashable] | None = None
) -> bool:
if not isinstance(other, NDPointIndex):
return False
if type(self._tree_obj) is not type(other._tree_obj):
return False
return self._tree_obj.equals(other._tree_obj)
def _get_dim_indexers(
self,
indices: np.ndarray,
label_dims: tuple[Hashable, ...],
label_shape: tuple[int, ...],
) -> dict[Hashable, Variable]:
"""Returns dimension indexers based on the query results (indices) and
the original label dimensions and shape.
1. Unravel the flat indices returned from the query
2. Reshape the unraveled indices according to indexers shapes
3. Wrap the indices in xarray.Variable objects.
"""
dim_indexers = {}
u_indices = list(np.unravel_index(indices.ravel(), self._shape))
for dim, ind in zip(self._dims, u_indices, strict=False):
dim_indexers[dim] = Variable(label_dims, ind.reshape(label_shape))
return dim_indexers
def sel(
self, labels: dict[Any, Any], method=None, tolerance=None
) -> IndexSelResult:
if method != "nearest":
raise ValueError(
"NDPointIndex only supports selection with method='nearest'"
)
missing_labels = set(self._coord_names) - set(labels)
if missing_labels:
missing_labels_str = ",".join([f"{name}" for name in missing_labels])
raise ValueError(f"missing labels for coordinate(s): {missing_labels_str}.")
# maybe convert labels into xarray DataArray objects
xr_labels: dict[Any, DataArray] = {}
for name, lbl in labels.items():
if isinstance(lbl, DataArray):
xr_labels[name] = lbl
elif isinstance(lbl, Variable):
xr_labels[name] = DataArray(lbl)
elif is_scalar(lbl):
xr_labels[name] = DataArray(lbl, dims=())
elif np.asarray(lbl).ndim == len(self._dims):
xr_labels[name] = DataArray(lbl, dims=self._dims)
else:
raise ValueError(
"invalid label value. NDPointIndex only supports advanced (point-wise) indexing "
"with the following label value kinds:\n"
"- xarray.DataArray or xarray.Variable objects\n"
"- scalar values\n"
"- unlabelled array-like objects with the same number of dimensions "
f"than the {self._coord_names} coordinate variables ({len(self._dims)})"
)
# broadcast xarray labels against one another and determine labels shape and dimensions
broadcasted = broadcast(*xr_labels.values())
label_dims = broadcasted[0].dims
label_shape = broadcasted[0].shape
xr_labels = dict(zip(xr_labels, broadcasted, strict=True))
# get and return dimension indexers
points = get_points(xr_labels[name] for name in self._coord_names)
_, indices = self._tree_obj.query(points)
dim_indexers = self._get_dim_indexers(indices, label_dims, label_shape)
return IndexSelResult(dim_indexers=dim_indexers)
def rename(
self,
name_dict: Mapping[Any, Hashable],
dims_dict: Mapping[Any, Hashable],
) -> Self:
if not set(self._coord_names) & set(name_dict) and not set(self._dims) & set(
dims_dict
):
return self
new_coord_names = tuple(name_dict.get(n, n) for n in self._coord_names)
new_dims = tuple(dims_dict.get(d, d) for d in self._dims)
return type(self)(
self._tree_obj,
coord_names=new_coord_names,
dims=new_dims,
shape=self._shape,
)
def _repr_inline_(self, max_width: int) -> str:
tree_obj_type = self._tree_obj.__class__.__name__
return f"{self.__class__.__name__} ({tree_obj_type})"
| NDPointIndex |
python | ray-project__ray | python/ray/data/_internal/iterator/stream_split_iterator.py | {
"start": 761,
"end": 952
} | class ____:
# A temporary workaround for https://github.com/ray-project/ray/issues/52549
def __init__(self, dataset: "Dataset") -> None:
self._dataset = dataset
| _DatasetWrapper |
python | eth-brownie__brownie | brownie/network/gas/bases.py | {
"start": 507,
"end": 2709
} | class ____(GasABC):
"""
Base ABC for scaling gas strategies.
This class should not be directly subclassed from.
Instead, use `BlockGasStrategy` or `TimeGasStrategy`.
"""
duration: int
def __new__(cls, *args: Any, **kwargs: Any) -> object:
obj = super().__new__(cls)
if not inspect.isgeneratorfunction(cls.get_gas_price):
raise TypeError("Scaling strategy must implement get_gas_price as a generator function")
return obj
@abstractmethod
def interval(self) -> int:
"""
Return "now" as it relates to the scaling strategy.
This can be e.g. the current time or block height. It is used in combination
with `duration` to determine when to rebroadcast a transaction.
"""
raise NotImplementedError
def _loop(self, receipt: Any, gas_iter: Iterator) -> None:
# retain the initial `silent` setting - tx's with required_confs=0 are set to
# silent prior to confirmation, so if we don't do this the console output is
# silenced by the 2nd replacement
silent = receipt._silent
while web3.eth.get_transaction_count(str(receipt.sender)) < receipt.nonce:
# do not run scaling strategy while prior tx's are still pending
time.sleep(5)
latest_interval = self.interval()
while True:
if web3.eth.get_transaction_count(str(receipt.sender)) > receipt.nonce:
break
if self.interval() - latest_interval >= self.duration:
gas_price = next(gas_iter)
if gas_price >= int(receipt.gas_price * 1.1):
try:
receipt = receipt.replace(gas_price=gas_price, silent=silent)
latest_interval = self.interval()
except ValueError:
pass
time.sleep(2)
def run(self, receipt: Any, gas_iter: Iterator) -> None:
thread = threading.Thread(
target=self._loop,
args=(receipt, gas_iter),
daemon=True,
name=f"Gas strategy {receipt.txid}",
)
thread.start()
| ScalingGasABC |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/io_management/input_managers.py | {
"start": 1097,
"end": 1835
} | class ____(PandasIOManager):
def load_input(self, context: dg.InputContext) -> np.ndarray: # pyright: ignore[reportIncompatibleMethodOverride]
file_path = "path/to/dataframe"
array = np.genfromtxt(file_path, delimiter=",", dtype=None)
return array
@dg.op(ins={"np_array_input": dg.In(input_manager_key="numpy_manager")})
def analyze_as_numpy(np_array_input: np.ndarray):
assert isinstance(np_array_input, np.ndarray)
@dg.job(
resource_defs={"numpy_manager": MyNumpyLoader(), "io_manager": PandasIOManager()}
)
def my_job():
df = produce_pandas_output()
analyze_as_numpy(df)
# end_plain_input_manager
# start_better_input_manager
# this IO Manager is owned by a different team
| MyNumpyLoader |
python | pypa__pip | src/pip/_vendor/urllib3/contrib/securetransport.py | {
"start": 29652,
"end": 34446
} | class ____(object):
"""
I am a wrapper class for the SecureTransport library, to translate the
interface of the standard library ``SSLContext`` object to calls into
SecureTransport.
"""
def __init__(self, protocol):
self._min_version, self._max_version = _protocol_to_min_max[protocol]
self._options = 0
self._verify = False
self._trust_bundle = None
self._client_cert = None
self._client_key = None
self._client_key_passphrase = None
self._alpn_protocols = None
@property
def check_hostname(self):
"""
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
"""
return True
@check_hostname.setter
def check_hostname(self, value):
"""
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
"""
pass
@property
def options(self):
# TODO: Well, crap.
#
# So this is the bit of the code that is the most likely to cause us
# trouble. Essentially we need to enumerate all of the SSL options that
# users might want to use and try to see if we can sensibly translate
# them, or whether we should just ignore them.
return self._options
@options.setter
def options(self, value):
# TODO: Update in line with above.
self._options = value
@property
def verify_mode(self):
return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE
@verify_mode.setter
def verify_mode(self, value):
self._verify = True if value == ssl.CERT_REQUIRED else False
def set_default_verify_paths(self):
# So, this has to do something a bit weird. Specifically, what it does
# is nothing.
#
# This means that, if we had previously had load_verify_locations
# called, this does not undo that. We need to do that because it turns
# out that the rest of the urllib3 code will attempt to load the
# default verify paths if it hasn't been told about any paths, even if
# the context itself was sometime earlier. We resolve that by just
# ignoring it.
pass
def load_default_certs(self):
return self.set_default_verify_paths()
def set_ciphers(self, ciphers):
# For now, we just require the default cipher string.
if ciphers != util.ssl_.DEFAULT_CIPHERS:
raise ValueError("SecureTransport doesn't support custom cipher strings")
def load_verify_locations(self, cafile=None, capath=None, cadata=None):
# OK, we only really support cadata and cafile.
if capath is not None:
raise ValueError("SecureTransport does not support cert directories")
# Raise if cafile does not exist.
if cafile is not None:
with open(cafile):
pass
self._trust_bundle = cafile or cadata
def load_cert_chain(self, certfile, keyfile=None, password=None):
self._client_cert = certfile
self._client_key = keyfile
self._client_cert_passphrase = password
def set_alpn_protocols(self, protocols):
"""
Sets the ALPN protocols that will later be set on the context.
Raises a NotImplementedError if ALPN is not supported.
"""
if not hasattr(Security, "SSLSetALPNProtocols"):
raise NotImplementedError(
"SecureTransport supports ALPN only in macOS 10.12+"
)
self._alpn_protocols = [six.ensure_binary(p) for p in protocols]
def wrap_socket(
self,
sock,
server_side=False,
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
server_hostname=None,
):
# So, what do we do here? Firstly, we assert some properties. This is a
# stripped down shim, so there is some functionality we don't support.
# See PEP 543 for the real deal.
assert not server_side
assert do_handshake_on_connect
assert suppress_ragged_eofs
# Ok, we're good to go. Now we want to create the wrapped socket object
# and store it in the appropriate place.
wrapped_socket = WrappedSocket(sock)
# Now we can handshake
wrapped_socket.handshake(
server_hostname,
self._verify,
self._trust_bundle,
self._min_version,
self._max_version,
self._client_cert,
self._client_key,
self._client_key_passphrase,
self._alpn_protocols,
)
return wrapped_socket
| SecureTransportContext |
python | Lightning-AI__lightning | src/lightning/pytorch/_graveyard/hpu.py | {
"start": 1440,
"end": 1638
} | class ____:
def __init__(self, *_: Any, **__: Any) -> None:
raise NotImplementedError("The `HPUCheckpointIO` class has been removed. Please contact developer@lightning.ai")
| HPUCheckpointIO |
python | ansible__ansible | lib/ansible/utils/encrypt.py | {
"start": 7879,
"end": 12646
} | class ____(BaseHash):
def __init__(self, algorithm):
super(PasslibHash, self).__init__(algorithm)
if not PASSLIB_AVAILABLE:
raise AnsibleError(f"The passlib Python package must be installed to hash with the {algorithm!r} algorithm.") from PASSLIB_E
try:
self.crypt_algo = getattr(passlib.hash, algorithm)
except Exception:
raise AnsibleError(f"Installed passlib version {passlib.__version__} does not support the {algorithm!r} algorithm.") from None
def hash(self, secret, salt=None, salt_size=None, rounds=None, ident=None):
salt = self._clean_salt(salt)
rounds = self._clean_rounds(rounds)
ident = self._clean_ident(ident)
if salt_size is not None and not isinstance(salt_size, int):
raise TypeError("salt_size must be an integer")
return self._hash(secret, salt=salt, salt_size=salt_size, rounds=rounds, ident=ident)
def _clean_ident(self, ident):
ret = None
if not ident:
if self.algorithm in self.algorithms:
return self.algorithms.get(self.algorithm).implicit_ident
return ret
if self.algorithm == 'bcrypt':
return ident
return ret
def _clean_salt(self, salt):
if not salt:
return None
elif issubclass(self.crypt_algo.wrapped if isinstance(self.crypt_algo, PrefixWrapper) else self.crypt_algo, HasRawSalt):
ret = to_bytes(salt, encoding='ascii', errors='strict')
else:
ret = to_text(salt, encoding='ascii', errors='strict')
# Ensure the salt has the correct padding
if self.algorithm == 'bcrypt':
ret = bcrypt64.repair_unused(ret)
return ret
def _clean_rounds(self, rounds):
algo_data = self.algorithms.get(self.algorithm)
if rounds:
return rounds
elif algo_data and algo_data.implicit_rounds:
# The default rounds used by passlib depend on the passlib version.
# For consistency ensure that passlib behaves the same as crypt in case no rounds were specified.
# Thus use the crypt defaults.
return algo_data.implicit_rounds
else:
return None
def _hash(self, secret, salt, salt_size, rounds, ident):
# Not every hash algorithm supports every parameter.
# Thus create the settings dict only with set parameters.
settings = {}
if salt:
settings['salt'] = salt
if salt_size:
settings['salt_size'] = salt_size
if rounds:
settings['rounds'] = rounds
if ident:
settings['ident'] = ident
# starting with passlib 1.7 'using' and 'hash' should be used instead of 'encrypt'
try:
if hasattr(self.crypt_algo, 'hash'):
result = self.crypt_algo.using(**settings).hash(secret)
elif hasattr(self.crypt_algo, 'encrypt'):
result = self.crypt_algo.encrypt(secret, **settings)
else:
raise ValueError(f"Installed passlib version {passlib.__version__} is not supported.")
except ValueError as ex:
raise AnsibleError("Could not hash the secret.") from ex
# passlib.hash should always return something or raise an exception.
# Still ensure that there is always a result.
# Otherwise an empty password might be assumed by some modules, like the user module.
if not result:
raise AnsibleError(f"Failed to hash with passlib using the {self.algorithm!r} algorithm.")
# Hashes from passlib.hash should be represented as ascii strings of hex
# digits so this should not traceback. If it's not representable as such
# we need to traceback and then block such algorithms because it may
# impact calling code.
return to_text(result, errors='strict')
def do_encrypt(result, algorithm, salt_size=None, salt=None, ident=None, rounds=None):
if HAS_CRYPT and algorithm in CryptHash.algorithms:
return CryptHash(algorithm).hash(result, salt=salt, salt_size=salt_size, rounds=rounds, ident=ident)
elif PASSLIB_AVAILABLE:
# TODO: deprecate passlib
return PasslibHash(algorithm).hash(result, salt=salt, salt_size=salt_size, rounds=rounds, ident=ident)
elif not PASSLIB_AVAILABLE and algorithm not in CryptHash.algorithms:
# When passlib support is removed, this branch can be removed too
raise AnsibleError(f"crypt does not support {algorithm!r} algorithm")
raise AnsibleError("Unable to encrypt nor hash, either libxcrypt (recommended), crypt, or passlib must be installed.") from CRYPT_E
| PasslibHash |
python | eth-brownie__brownie | brownie/typing.py | {
"start": 1189,
"end": 1355
} | class ____(TypedDict):
contractName: ContractName
abi: List[ABIElement]
sha1: HexStr
dependencies: NotRequired[List[ContractName]]
@final
| _BuildJsonBase |
python | django-haystack__django-haystack | test_haystack/elasticsearch_tests/test_elasticsearch_backend.py | {
"start": 65003,
"end": 68910
} | class ____(TestCase):
def setUp(self):
super().setUp()
# Wipe it clean.
clear_elasticsearch_index()
# Stow.
self.old_ui = connections["elasticsearch"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = ElasticsearchFacetingMockSearchIndex()
self.ui.build(indexes=[self.smmi])
connections["elasticsearch"]._index = self.ui
self.sb = connections["elasticsearch"].get_backend()
# Force the backend to rebuild the mapping each time.
self.sb.existing_mapping = {}
self.sb.setup()
self.sample_objs = []
for i in range(1, 10):
mock = AFourthMockModel()
mock.id = i
if i > 5:
mock.editor = "George Taylor"
else:
mock.editor = "Perry White"
if i % 2:
mock.author = "Daniel Lindsley"
else:
mock.author = "Dan Watson"
mock.pub_date = datetime.date(2013, 9, (i % 4) + 1)
self.sample_objs.append(mock)
def tearDown(self):
connections["elasticsearch"]._index = self.old_ui
super().tearDown()
def test_facet(self):
self.sb.update(self.smmi, self.sample_objs)
counts = (
SearchQuerySet("elasticsearch")
.facet("author")
.facet("editor")
.facet_counts()
)
self.assertEqual(
counts["fields"]["author"], [("Daniel Lindsley", 5), ("Dan Watson", 4)]
)
self.assertEqual(
counts["fields"]["editor"], [("Perry White", 5), ("George Taylor", 4)]
)
counts = (
SearchQuerySet("elasticsearch")
.filter(content="white")
.facet("facet_field", order="reverse_count")
.facet_counts()
)
self.assertEqual(
counts["fields"]["facet_field"], [("Dan Watson", 2), ("Daniel Lindsley", 3)]
)
def test_multiple_narrow(self):
self.sb.update(self.smmi, self.sample_objs)
counts = (
SearchQuerySet("elasticsearch")
.narrow('editor_exact:"Perry White"')
.narrow('author_exact:"Daniel Lindsley"')
.facet("author")
.facet_counts()
)
self.assertEqual(counts["fields"]["author"], [("Daniel Lindsley", 3)])
def test_narrow(self):
self.sb.update(self.smmi, self.sample_objs)
counts = (
SearchQuerySet("elasticsearch")
.facet("author")
.facet("editor")
.narrow('editor_exact:"Perry White"')
.facet_counts()
)
self.assertEqual(
counts["fields"]["author"], [("Daniel Lindsley", 3), ("Dan Watson", 2)]
)
self.assertEqual(counts["fields"]["editor"], [("Perry White", 5)])
def test_date_facet(self):
self.sb.update(self.smmi, self.sample_objs)
start = datetime.date(2013, 9, 1)
end = datetime.date(2013, 9, 30)
# Facet by day
counts = (
SearchQuerySet("elasticsearch")
.date_facet("pub_date", start_date=start, end_date=end, gap_by="day")
.facet_counts()
)
self.assertEqual(
counts["dates"]["pub_date"],
[
(datetime.datetime(2013, 9, 1), 2),
(datetime.datetime(2013, 9, 2), 3),
(datetime.datetime(2013, 9, 3), 2),
(datetime.datetime(2013, 9, 4), 2),
],
)
# By month
counts = (
SearchQuerySet("elasticsearch")
.date_facet("pub_date", start_date=start, end_date=end, gap_by="month")
.facet_counts()
)
self.assertEqual(
counts["dates"]["pub_date"], [(datetime.datetime(2013, 9, 1), 9)]
)
| ElasticsearchFacetingTestCase |
python | weaviate__weaviate-python-client | weaviate/warnings.py | {
"start": 258,
"end": 13216
} | class ____:
@staticmethod
def auth_with_anon_weaviate() -> None:
warnings.warn(
message="""Auth001: The client is configured to use authentication, but weaviate is configured without
authentication. Are you sure this is correct?""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def auth_no_refresh_token(auth_len: Optional[int] = None) -> None:
if auth_len is not None:
msg = f"The current access token is only valid for {auth_len}s."
else:
msg = "Also, no expiration time was given."
warnings.warn(
message=f"""Auth002: The token your identity provider returned does not contain a refresh token. {msg}
Access to your weaviate instance is not possible after the token expires. This client returns an
authentication exception.
Things to try:
- You might need to enable refresh tokens in your authentication provider settings.
- You might need to send the correct scope. For some providers, the scope needs to include "offline_access".
""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def auth_negative_expiration_time(expires_in: int) -> None:
msg = f"""Auth003: Access token expiration time is negative: {expires_in}."""
warnings.warn(message=msg, category=UserWarning, stacklevel=1)
@staticmethod
def auth_header_and_auth_secret() -> None:
msg = """Auth004: Received an authentication header and an auth_client_secret parameter.
The auth_client_secret takes precedence over the header. The authentication header will be ignored.
Use weaviate.auth.AuthBearerToken(..) to supply an access token via auth_client_secret parameter and,
if available with your provider, to supply refresh tokens and token lifetimes.
"""
warnings.warn(message=msg, category=UserWarning, stacklevel=1)
@staticmethod
def auth_cannot_parse_oidc_config(url: str) -> None:
msg = f"""Auth005: Could not parse Weaviate's OIDC configuration, using unauthenticated access. If you added
an authorization header yourself it will be unaffected.
This can happen if weaviate is miss-configured or if you have a proxy between the client and weaviate.
You can test this by visiting {url}."""
warnings.warn(message=msg, category=UserWarning, stacklevel=1)
@staticmethod
def token_refresh_failed(exc: Exception) -> None:
warnings.warn(
message=f"""Con001: Could not reach token issuer for the periodic refresh. This client will automatically
retry to refresh. If the retry does not succeed, the client will become unauthenticated.
The cause might be an unstable internet connection or a problem with your authentication provider.
Exception: {exc}
""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def weaviate_too_old_vs_latest(server_version: str) -> None:
warnings.warn(
message=f"""Dep004: You are connected to Weaviate {server_version}.
Consider upgrading to the latest version. See https://www.weaviate.io/developers/weaviate for details.""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def weaviate_client_too_old_vs_latest(client_version: str, latest_version: str) -> None:
warnings.warn(
message=f"""Dep005: You are using weaviate-client version {client_version}. The latest version is {latest_version}.
Consider upgrading to the latest version. See https://weaviate.io/developers/weaviate/client-libraries/python for details.""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def root_module_import(name: str, loc: str) -> None:
warnings.warn(
f"Dep010: Importing {name} from weaviate is deprecated. "
f"Import {name} from its module: weaviate.{loc}",
DeprecationWarning,
stacklevel=2, # don't increase stacklevel, as this otherwise writes the auth-secrets into the log
)
@staticmethod
def palm_to_google_t2v() -> None:
warnings.warn(
"Dep011: text2vec-palm is deprecated and will be removed in Q2 25. Use text2vec-google instead.",
DeprecationWarning,
stacklevel=1,
)
@staticmethod
def palm_to_google_m2v() -> None:
warnings.warn(
"Dep012: multi2vec-palm is deprecated and will be removed in Q2 25. Use multi2vec-google instead.",
DeprecationWarning,
stacklevel=1,
)
@staticmethod
def palm_to_google_gen() -> None:
warnings.warn(
"Dep013: generative.palm is deprecated and will be removed in Q2 25. Use generative.google instead.",
DeprecationWarning,
stacklevel=1,
)
@staticmethod
def vector_index_config_in_config_update() -> None:
warnings.warn(
message="""Dep017: You are using the `vector_index_config` argument in the `collection.config.update()` method, which is deprecated.
Use the `vector_config` argument instead.
""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def sharding_actual_count_is_deprecated(argument: str) -> None:
warnings.warn(
message=f"""Dep018: You are using the {argument} argument in the `Configure.sharding` method, which is deprecated.
This field is read-only, the argument has no effect. It will be removed in a future release.""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def bit_compression_in_pq_config() -> None:
warnings.warn(
message="""Dep019: The `bit_compression` argument in `PQConfig` is deprecated and will be removed by Q4 2024.""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def batch_results_objects_all_responses_attribute() -> None:
warnings.warn(
message="""Dep020: The `all_responses` attribute in the `BatchResults` object is deprecated and will be removed by Q4 2024. Please instead use the `errors` and `uuids` attributes.""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def deprecated_tenant_type(old: str, new: str) -> None:
warnings.warn(
message=f"""Dep021: The tenant status {old} is deprecated and will be removed by Q1 2025. Please use {new} instead.""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def oidc_with_wcd_deprecated() -> None:
warnings.warn(
message="""Dep022: connecting to Weaviate Cloud (WCD) using OIDC is deprecated and will be removed in August 2025. Please use API keys instead.""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def vectorizer_config_in_config_update() -> None:
warnings.warn(
message="""Dep023: You are using the `vectorizer_config` argument in the `collection.config.update()` method with a collection with named vectors, which is deprecated.
Use the `vector_config` argument instead.
""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def vectorizer_config_in_config_create() -> None:
warnings.warn(
message="""Dep024: You are using the `vectorizer_config` argument in `collection.config.create()`, which is deprecated.
Use the `vector_config` argument instead.
""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def vector_index_config_in_config_create() -> None:
warnings.warn(
message="""Dep025: You are using the `vector_index_config` argument in `collection.config.create()`, which is deprecated.
Use the `vector_config` argument instead defining `vector_index_config` as a sub-argument.
""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def named_vector_syntax_in_config_add_vector(name: str) -> None:
warnings.warn(
message=f"""Dep026: You are using the named vector syntax for vector {name}, e.g. `Configure.NamedVectors` in `collection.config.add_vector()`, which is deprecated.
Use `Configure.Vectors` or `Configure.MultiVectors` instead.`
""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def encoding_in_multi_vector_config() -> None:
warnings.warn(
message="""Dep026: You are using the `encoding` argument in `Configure.VectorIndex.MultiVectors.multi_vector()`, which is deprecated.
Use the `encoding` argument inside `Configure.MultiVectors.module()` instead.
""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def multi_vector_in_hnsw_config() -> None:
warnings.warn(
message="""Dep027: You are using the `multi_vector` argument in `Configure.VectorIndex.hnsw()`, which is deprecated.
Use the `multi_vector` argument inside `Configure.MultiVectors.module()` instead.
""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def min_occurrences_metric_deprecated() -> None:
warnings.warn(
message="""Dep028: You are using the `min_occurrences` argument in the `Metrics.text()` method, which is deprecated.
Use the `limit` argument instead.
""",
category=DeprecationWarning,
stacklevel=1,
)
@staticmethod
def datetime_insertion_with_no_specified_timezone(date: datetime) -> None:
warnings.warn(
message=f"""Con002: You are using the datetime object {date} without a timezone. The timezone will be set to UTC.
To use a different timezone, specify it in the datetime object. For example:
datetime.datetime(2021, 1, 1, 0, 0, 0, tzinfo=datetime.timezone(-datetime.timedelta(hours=2))).isoformat() = 2021-01-01T00:00:00-02:00
""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def datetime_year_zero(date: str) -> None:
warnings.warn(
message=f"""Con004: Received a date {date} with year 0. The year 0 does not exist in the Gregorian calendar
and cannot be parsed by the datetime library. The year will be set to {datetime.min}.
See https://en.wikipedia.org/wiki/Year_zero for more information.""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def batch_refresh_failed(err: str) -> None:
warnings.warn(
message=f"""Bat003: The dynamic batch-size could not be refreshed successfully: error {err}""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def batch_rate_limit_reached(msg: str, seconds: int) -> None:
warnings.warn(
message=f"""Bat005: Rate limit reached with error {msg}.
Sleeping for {seconds} seconds.""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def unknown_type_encountered(field: str) -> None:
warnings.warn(
message=f"""Grpc002: Unknown return type {field} received, skipping value and returning None.""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def unclosed_connection() -> None:
warnings.warn(
message="""Con004: The connection to Weaviate was not closed properly. This can lead to memory leaks.
Please make sure to close the connection using `client.close()`.""",
category=ResourceWarning,
stacklevel=1,
)
@staticmethod
def grpc_max_msg_size_not_found() -> None:
warnings.warn(
message="""Con005: Could not retrieve the maximum GRPC message size from the weaviate server. Using the default
value of 10mb. If you need a larger message size, please update weaviate.""",
category=UserWarning,
stacklevel=1,
)
@staticmethod
def unknown_permission_encountered(permission: Any) -> None:
warnings.warn(
message=f"""RBAC001: Unknown permission {permission} received, skipping value.""",
category=UserWarning,
stacklevel=1,
)
| _Warnings |
python | cython__cython | tests/run/test_named_expressions.py | {
"start": 12975,
"end": 18883
} | class ____(unittest.TestCase):
def test_named_expression_scope_01(self):
code = """def spam():
(a := 5)
print(a)"""
# FIXME for some reason the error message raised is a nonsense filename instead of "undeclared name not builtin"
# "name .* not"):
with self.assertRaisesRegex(SyntaxError if cython.compiled else NameError, ""):
exec(code, {}, {})
def test_named_expression_scope_02(self):
total = 0
partial_sums = [total := total + v for v in range(5)]
self.assertEqual(partial_sums, [0, 1, 3, 6, 10])
self.assertEqual(total, 10)
def test_named_expression_scope_03(self):
containsOne = any((lastNum := num) == 1 for num in [1, 2, 3])
self.assertTrue(containsOne)
self.assertEqual(lastNum, 1)
def test_named_expression_scope_04(self):
def spam(a):
return a
res = [[y := spam(x), x/y] for x in range(1, 5)]
self.assertEqual(y, 4)
def test_named_expression_scope_05(self):
def spam(a):
return a
input_data = [1, 2, 3]
res = [(x, y, x/y) for x in input_data if (y := spam(x)) > 0]
self.assertEqual(res, [(1, 1, 1.0), (2, 2, 1.0), (3, 3, 1.0)])
self.assertEqual(y, 3)
def test_named_expression_scope_06(self):
res = [[spam := i for i in range(3)] for j in range(2)]
self.assertEqual(res, [[0, 1, 2], [0, 1, 2]])
self.assertEqual(spam, 2)
def test_named_expression_scope_07(self):
len(lines := [1, 2])
self.assertEqual(lines, [1, 2])
def test_named_expression_scope_08(self):
def spam(a):
return a
def eggs(b):
return b * 2
res = [spam(a := eggs(b := h)) for h in range(2)]
self.assertEqual(res, [0, 2])
self.assertEqual(a, 2)
self.assertEqual(b, 1)
def test_named_expression_scope_09(self):
def spam(a):
return a
def eggs(b):
return b * 2
res = [spam(a := eggs(a := h)) for h in range(2)]
self.assertEqual(res, [0, 2])
self.assertEqual(a, 2)
def test_named_expression_scope_10(self):
res = [b := [a := 1 for i in range(2)] for j in range(2)]
self.assertEqual(res, [[1, 1], [1, 1]])
self.assertEqual(a, 1)
self.assertEqual(b, [1, 1])
def test_named_expression_scope_11(self):
res = [j := i for i in range(5)]
self.assertEqual(res, [0, 1, 2, 3, 4])
self.assertEqual(j, 4)
def test_named_expression_scope_17(self):
b = 0
res = [b := i + b for i in range(5)]
self.assertEqual(res, [0, 1, 3, 6, 10])
self.assertEqual(b, 10)
def test_named_expression_scope_18(self):
def spam(a):
return a
res = spam(b := 2)
self.assertEqual(res, 2)
self.assertEqual(b, 2)
def test_named_expression_scope_19(self):
def spam(a):
return a
res = spam((b := 2))
self.assertEqual(res, 2)
self.assertEqual(b, 2)
def test_named_expression_scope_20(self):
def spam(a):
return a
res = spam(a=(b := 2))
self.assertEqual(res, 2)
self.assertEqual(b, 2)
def test_named_expression_scope_21(self):
def spam(a, b):
return a + b
res = spam(c := 2, b=1)
self.assertEqual(res, 3)
self.assertEqual(c, 2)
def test_named_expression_scope_22(self):
def spam(a, b):
return a + b
res = spam((c := 2), b=1)
self.assertEqual(res, 3)
self.assertEqual(c, 2)
def test_named_expression_scope_23(self):
def spam(a, b):
return a + b
res = spam(b=(c := 2), a=1)
self.assertEqual(res, 3)
self.assertEqual(c, 2)
def test_named_expression_scope_24(self):
a = 10
def spam():
nonlocal a
(a := 20)
spam()
self.assertEqual(a, 20)
def test_named_expression_scope_25(self):
ns = {}
code = """a = 10
def spam():
global a
(a := 20)
spam()"""
exec(code, ns, {})
self.assertEqual(ns["a"], 20)
def test_named_expression_variable_reuse_in_comprehensions(self):
# The compiler is expected to raise syntax error for comprehension
# iteration variables, but should be fine with rebinding of other
# names (e.g. globals, nonlocals, other assignment expressions)
# The cases are all defined to produce the same expected result
# Each comprehension is checked at both function scope and module scope
rebinding = "[x := i for i in range(3) if (x := i) or not x]"
filter_ref = "[x := i for i in range(3) if x or not x]"
body_ref = "[x for i in range(3) if (x := i) or not x]"
nested_ref = "[j for i in range(3) if x or not x for j in range(3) if (x := i)][:-3]"
cases = [
("Rebind global", f"x = 1; result = {rebinding}"),
("Rebind nonlocal", f"result, x = (lambda x=1: ({rebinding}, x))()"),
("Filter global", f"x = 1; result = {filter_ref}"),
("Filter nonlocal", f"result, x = (lambda x=1: ({filter_ref}, x))()"),
("Body global", f"x = 1; result = {body_ref}"),
("Body nonlocal", f"result, x = (lambda x=1: ({body_ref}, x))()"),
("Nested global", f"x = 1; result = {nested_ref}"),
("Nested nonlocal", f"result, x = (lambda x=1: ({nested_ref}, x))()"),
]
for case, code in cases:
with self.subTest(case=case):
ns = {}
exec(code, ns)
self.assertEqual(ns["x"], 2)
self.assertEqual(ns["result"], [0, 1, 2])
if __name__ == "__main__":
unittest.main()
| NamedExpressionScopeTest |
python | skorch-dev__skorch | skorch/tests/callbacks/test_training.py | {
"start": 48286,
"end": 54033
} | class ____:
@pytest.fixture
def module_cls(self):
import torch
class Module(torch.nn.Module):
def __init__(self, input_dim=3):
super().__init__()
self.layer = torch.nn.Linear(input_dim, 2)
def forward(self, X):
return self.layer(X)
return Module
@pytest.fixture
def net_cls(self):
from skorch import NeuralNetClassifier
return NeuralNetClassifier
@pytest.fixture
def input_shape_setter_cls(self):
from skorch.callbacks import InputShapeSetter
return InputShapeSetter
def generate_data(self, n_input):
from sklearn.datasets import make_classification
X, y = make_classification(
1000,
n_input,
n_informative=n_input,
n_redundant=0,
random_state=0,
)
return X.astype(np.float32), y
@pytest.fixture
def data_fixed(self):
return self.generate_data(n_input=10)
@pytest.fixture(params=[2, 10, 20])
def data_parametrized(self, request):
return self.generate_data(n_input=request.param)
def test_shape_set(
self, net_cls, module_cls, input_shape_setter_cls, data_parametrized,
):
net = net_cls(module_cls, max_epochs=2, callbacks=[
input_shape_setter_cls(),
])
X, y = data_parametrized
n_input = X.shape[1]
net.fit(X, y)
assert net.module_.layer.in_features == n_input
def test_one_dimensional_x_raises(
self, net_cls, module_cls, input_shape_setter_cls,
):
net = net_cls(module_cls, max_epochs=2, callbacks=[
input_shape_setter_cls(),
])
X, y = np.zeros(10), np.zeros(10)
with pytest.raises(ValueError) as e:
net.fit(X, y)
assert (
"Expected at least two-dimensional input data for X. "
"If your data is one-dimensional, please use the `input_dim_fn` "
"parameter to infer the correct input shape."
) in str(e)
def test_shape_set_using_fn(
self, net_cls, module_cls, input_shape_setter_cls, data_parametrized,
):
fn_calls = 0
def input_dim_fn(X):
nonlocal fn_calls
fn_calls += 1
return X.shape[1]
net = net_cls(module_cls, max_epochs=2, callbacks=[
input_shape_setter_cls(input_dim_fn=input_dim_fn),
])
X, y = data_parametrized
n_input = X.shape[1]
net.fit(X, y)
assert net.module_.layer.in_features == n_input
assert fn_calls == 1
def test_parameter_name(
self, net_cls, input_shape_setter_cls, data_parametrized,
):
class MyModule(torch.nn.Module):
def __init__(self, other_input_dim=22):
super().__init__()
self.layer = torch.nn.Linear(other_input_dim, 2)
def forward(self, X):
return self.layer(X)
net = net_cls(MyModule, max_epochs=2, callbacks=[
input_shape_setter_cls(param_name='other_input_dim'),
])
X, y = data_parametrized
n_input = X.shape[1]
net.fit(X, y)
assert net.module_.layer.in_features == n_input
def test_module_name(
self, net_cls, module_cls, input_shape_setter_cls, data_parametrized,
):
class MyNet(net_cls):
def initialize_module(self):
kwargs = self.get_params_for('module')
self.module_ = self.module(**kwargs)
kwargs = self.get_params_for('module2')
self.module2_ = self.module(**kwargs)
net = MyNet(
module=module_cls,
max_epochs=2,
callbacks=[
input_shape_setter_cls(module_name='module'),
input_shape_setter_cls(module_name='module2'),
],
)
X, y = data_parametrized
n_input = X.shape[1]
net.fit(X, y)
assert net.module_.layer.in_features == n_input
assert net.module2_.layer.in_features == n_input
def test_no_module_reinit_when_already_correct(
self, net_cls, module_cls, input_shape_setter_cls, data_fixed,
):
with patch('skorch.classifier.NeuralNetClassifier.initialize_module',
side_effect=net_cls.initialize_module, autospec=True):
net = net_cls(
module_cls, max_epochs=2, callbacks=[input_shape_setter_cls()],
# set the input dim to the correct shape beforehand
module__input_dim=data_fixed[0].shape[-1],
)
net.fit(*data_fixed)
# first initialization due to `initialize()` but not
# a second one since the input shape is already correct.
assert net.initialize_module.call_count == 1
def test_no_module_reinit_partial_fit(
self, net_cls, module_cls, input_shape_setter_cls, data_fixed,
):
with patch('skorch.classifier.NeuralNetClassifier.initialize_module',
side_effect=net_cls.initialize_module, autospec=True):
net = net_cls(
module_cls, max_epochs=2, callbacks=[input_shape_setter_cls()],
)
net.fit(*data_fixed)
# first initialization due to `initialize()`, second
# by setting the input dimension in `on_train_begin`
assert net.initialize_module.call_count == 2
net.partial_fit(*data_fixed)
# no re-initialization when there was no change in
# input dimension.
assert net.initialize_module.call_count == 2
| TestInputShapeSetter |
python | getsentry__sentry | src/sentry/types/grouphash_metadata.py | {
"start": 2946,
"end": 3121
} | class ____(StacktraceHashingMetadata, FingerprintHashingMetadata):
"""
Data from stacktrace-based bybrid fingerprinting
"""
pass
| SaltedStacktraceHashingMetadata |
python | Lightning-AI__lightning | tests/tests_pytorch/utilities/test_model_helpers.py | {
"start": 2348,
"end": 6543
} | class ____:
@_restricted_classmethod
def restricted_cmethod(cls):
# Can only be called on the class type
pass
@classmethod
def cmethod(cls):
# Can be called on instance or class type
pass
def test_restricted_classmethod():
restricted_method = RestrictedClass().restricted_cmethod # no exception when getting restricted method
with pytest.raises(TypeError, match="cannot be called on an instance"):
restricted_method()
_ = inspect.getmembers(RestrictedClass()) # no exception on inspecting instance
def test_module_mode():
class ChildChildModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer = torch.nn.Linear(2, 2)
self.dropout = torch.nn.Dropout()
class ChildModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.child = ChildChildModule()
self.dropout = torch.nn.Dropout()
class RootModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.child1 = ChildModule()
self.child2 = ChildModule()
self.norm = torch.nn.BatchNorm1d(2)
# Model with all submodules in the same mode
model = RootModule()
model.train()
mode = _ModuleMode()
mode.capture(model)
model.eval()
assert all(not m.training for m in model.modules())
mode.restore(model)
assert model.training
assert all(m.training for m in model.modules())
model.eval()
mode = _ModuleMode()
mode.capture(model)
model.eval()
assert all(not m.training for m in model.modules())
mode.restore(model)
assert all(not m.training for m in model.modules())
model.train()
# Model with submodules in different modes
model.norm.eval()
model.child1.eval()
model.child2.train()
model.child2.child.eval()
model.child2.child.layer.train()
mode = _ModuleMode()
mode.capture(model)
model.eval()
assert all(not m.training for m in model.modules())
mode.restore(model)
assert model.training
assert not model.norm.training
assert all(not m.training for m in model.child1.modules())
assert model.child2.training
assert model.child2.dropout.training
assert not model.child2.child.training
assert model.child2.child.layer.training
assert not model.child2.child.dropout.training
def test_module_mode_restore_missing_module():
"""Test that restoring still works if the module drops a layer after it was captured."""
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.child1 = torch.nn.Linear(2, 2)
self.child2 = torch.nn.Linear(2, 2)
model = Model()
mode = _ModuleMode()
mode.capture(model)
model.child1.eval()
del model.child2
assert not hasattr(model, "child2")
mode.restore(model)
assert model.child1.training
def test_module_mode_restore_new_module(caplog):
"""Test that restoring ignores newly added submodules after the module was captured."""
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.child = torch.nn.Linear(2, 2)
model = Model()
mode = _ModuleMode()
mode.capture(model)
model.child.eval()
model.new_child = torch.nn.Linear(2, 2)
with caplog.at_level(logging.DEBUG, logger="lightning.pytorch.utilities.model_helpers"):
mode.restore(model)
assert "Restoring training mode on module 'new_child' not possible" in caplog.text
def test_module_mode_clear():
class Model1(torch.nn.Module):
def __init__(self):
super().__init__()
self.child1 = torch.nn.Linear(2, 2)
class Model2(torch.nn.Module):
def __init__(self):
super().__init__()
self.child2 = torch.nn.Linear(2, 2)
model1 = Model1()
model2 = Model2()
mode = _ModuleMode()
mode.capture(model1)
assert mode.mode == {"": True, "child1": True}
mode.capture(model2)
assert mode.mode == {"": True, "child2": True} # child1 is not included anymore
| RestrictedClass |
python | davidhalter__jedi | jedi/api/strings.py | {
"start": 611,
"end": 3711
} | class ____(AbstractArbitraryName):
api_type = 'string'
is_value_name = False
def complete_dict(module_context, code_lines, leaf, position, string, fuzzy):
bracket_leaf = leaf
if bracket_leaf != '[':
bracket_leaf = leaf.get_previous_leaf()
cut_end_quote = ''
if string:
cut_end_quote = get_quote_ending(string, code_lines, position, invert_result=True)
if bracket_leaf == '[':
if string is None and leaf is not bracket_leaf:
string = cut_value_at_position(leaf, position)
context = module_context.create_context(bracket_leaf)
before_node = before_bracket_leaf = bracket_leaf.get_previous_leaf()
if before_node in (')', ']', '}'):
before_node = before_node.parent
if before_node.type in ('atom', 'trailer', 'name'):
values = infer_call_of_leaf(context, before_bracket_leaf)
return list(_completions_for_dicts(
module_context.inference_state,
values,
'' if string is None else string,
cut_end_quote,
fuzzy=fuzzy,
))
return []
def _completions_for_dicts(inference_state, dicts, literal_string, cut_end_quote, fuzzy):
for dict_key in sorted(_get_python_keys(dicts), key=lambda x: repr(x)):
dict_key_str = _create_repr_string(literal_string, dict_key)
if dict_key_str.startswith(literal_string):
name = StringName(inference_state, dict_key_str[:-len(cut_end_quote) or None])
yield Completion(
inference_state,
name,
stack=None,
like_name_length=len(literal_string),
is_fuzzy=fuzzy
)
def _create_repr_string(literal_string, dict_key):
if not isinstance(dict_key, (str, bytes)) or not literal_string:
return repr(dict_key)
r = repr(dict_key)
prefix, quote = _get_string_prefix_and_quote(literal_string)
if quote is None:
return r
if quote == r[0]:
return prefix + r
return prefix + quote + r[1:-1] + quote
def _get_python_keys(dicts):
for dct in dicts:
if dct.array_type == 'dict':
for key in dct.get_key_values():
dict_key = key.get_safe_value(default=_sentinel)
if dict_key is not _sentinel:
yield dict_key
def _get_string_prefix_and_quote(string):
match = re.match(r'(\w*)("""|\'{3}|"|\')', string)
if match is None:
return None, None
return match.group(1), match.group(2)
def _matches_quote_at_position(code_lines, quote, position):
string = code_lines[position[0] - 1][position[1]:position[1] + len(quote)]
return string == quote
def get_quote_ending(string, code_lines, position, invert_result=False):
_, quote = _get_string_prefix_and_quote(string)
if quote is None:
return ''
# Add a quote only if it's not already there.
if _matches_quote_at_position(code_lines, quote, position) != invert_result:
return ''
return quote
| StringName |
python | getsentry__sentry | src/sentry/consumers/__init__.py | {
"start": 25497,
"end": 26317
} | class ____(ProcessingStrategyFactory):
"""
A wrapper that tracks the minimum partition index being processed by the consumer
and adds it as a global metric tag. This helps with monitoring partition distribution
and debugging partition-specific issues.
"""
def __init__(self, inner: ProcessingStrategyFactory):
self.inner = inner
def create_with_partitions(self, commit, partitions):
from sentry.metrics.middleware import add_global_tags
# Update the min_partition global tag based on current partition assignment
if partitions:
min_partition = min(p.index for p in partitions)
add_global_tags(tags={"min_partition": str(min_partition)})
return self.inner.create_with_partitions(commit, partitions)
| MinPartitionMetricTagWrapper |
python | scikit-learn__scikit-learn | sklearn/cluster/_kmeans.py | {
"start": 39944,
"end": 58140
} | class ____(_BaseKMeans):
"""K-Means clustering.
Read more in the :ref:`User Guide <k_means>`.
Parameters
----------
n_clusters : int, default=8
The number of clusters to form as well as the number of
centroids to generate.
For an example of how to choose an optimal value for `n_clusters` refer to
:ref:`sphx_glr_auto_examples_cluster_plot_kmeans_silhouette_analysis.py`.
init : {'k-means++', 'random'}, callable or array-like of shape \
(n_clusters, n_features), default='k-means++'
Method for initialization:
* 'k-means++' : selects initial cluster centroids using sampling \
based on an empirical probability distribution of the points' \
contribution to the overall inertia. This technique speeds up \
convergence. The algorithm implemented is "greedy k-means++". It \
differs from the vanilla k-means++ by making several trials at \
each sampling step and choosing the best centroid among them.
* 'random': choose `n_clusters` observations (rows) at random from \
data for the initial centroids.
* If an array is passed, it should be of shape (n_clusters, n_features)\
and gives the initial centers.
* If a callable is passed, it should take arguments X, n_clusters and a\
random state and return an initialization.
For an example of how to use the different `init` strategies, see
:ref:`sphx_glr_auto_examples_cluster_plot_kmeans_digits.py`.
For an evaluation of the impact of initialization, see the example
:ref:`sphx_glr_auto_examples_cluster_plot_kmeans_stability_low_dim_dense.py`.
n_init : 'auto' or int, default='auto'
Number of times the k-means algorithm is run with different centroid
seeds. The final results is the best output of `n_init` consecutive runs
in terms of inertia. Several runs are recommended for sparse
high-dimensional problems (see :ref:`kmeans_sparse_high_dim`).
When `n_init='auto'`, the number of runs depends on the value of init:
10 if using `init='random'` or `init` is a callable;
1 if using `init='k-means++'` or `init` is an array-like.
.. versionadded:: 1.2
Added 'auto' option for `n_init`.
.. versionchanged:: 1.4
Default value for `n_init` changed to `'auto'`.
max_iter : int, default=300
Maximum number of iterations of the k-means algorithm for a
single run.
tol : float, default=1e-4
Relative tolerance with regards to Frobenius norm of the difference
in the cluster centers of two consecutive iterations to declare
convergence.
verbose : int, default=0
Verbosity mode.
random_state : int, RandomState instance or None, default=None
Determines random number generation for centroid initialization. Use
an int to make the randomness deterministic.
See :term:`Glossary <random_state>`.
copy_x : bool, default=True
When pre-computing distances it is more numerically accurate to center
the data first. If copy_x is True (default), then the original data is
not modified. If False, the original data is modified, and put back
before the function returns, but small numerical differences may be
introduced by subtracting and then adding the data mean. Note that if
the original data is not C-contiguous, a copy will be made even if
copy_x is False. If the original data is sparse, but not in CSR format,
a copy will be made even if copy_x is False.
algorithm : {"lloyd", "elkan"}, default="lloyd"
K-means algorithm to use. The classical EM-style algorithm is `"lloyd"`.
The `"elkan"` variation can be more efficient on some datasets with
well-defined clusters, by using the triangle inequality. However it's
more memory intensive due to the allocation of an extra array of shape
`(n_samples, n_clusters)`.
.. versionchanged:: 0.18
Added Elkan algorithm
.. versionchanged:: 1.1
Renamed "full" to "lloyd", and deprecated "auto" and "full".
Changed "auto" to use "lloyd" instead of "elkan".
Attributes
----------
cluster_centers_ : ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers. If the algorithm stops before fully
converging (see ``tol`` and ``max_iter``), these will not be
consistent with ``labels_``.
labels_ : ndarray of shape (n_samples,)
Labels of each point
inertia_ : float
Sum of squared distances of samples to their closest cluster center,
weighted by the sample weights if provided.
n_iter_ : int
Number of iterations run.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
MiniBatchKMeans : Alternative online implementation that does incremental
updates of the centers positions using mini-batches.
For large scale learning (say n_samples > 10k) MiniBatchKMeans is
probably much faster than the default batch implementation.
Notes
-----
The k-means problem is solved using either Lloyd's or Elkan's algorithm.
The average complexity is given by O(k n T), where n is the number of
samples and T is the number of iteration.
The worst case complexity is given by O(n^(k+2/p)) with
n = n_samples, p = n_features.
Refer to :doi:`"How slow is the k-means method?" D. Arthur and S. Vassilvitskii -
SoCG2006.<10.1145/1137856.1137880>` for more details.
In practice, the k-means algorithm is very fast (one of the fastest
clustering algorithms available), but it falls in local minima. That's why
it can be useful to restart it several times.
If the algorithm stops before fully converging (because of ``tol`` or
``max_iter``), ``labels_`` and ``cluster_centers_`` will not be consistent,
i.e. the ``cluster_centers_`` will not be the means of the points in each
cluster. Also, the estimator will reassign ``labels_`` after the last
iteration to make ``labels_`` consistent with ``predict`` on the training
set.
Examples
--------
>>> from sklearn.cluster import KMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [10, 2], [10, 4], [10, 0]])
>>> kmeans = KMeans(n_clusters=2, random_state=0, n_init="auto").fit(X)
>>> kmeans.labels_
array([1, 1, 1, 0, 0, 0], dtype=int32)
>>> kmeans.predict([[0, 0], [12, 3]])
array([1, 0], dtype=int32)
>>> kmeans.cluster_centers_
array([[10., 2.],
[ 1., 2.]])
For examples of common problems with K-Means and how to address them see
:ref:`sphx_glr_auto_examples_cluster_plot_kmeans_assumptions.py`.
For a demonstration of how K-Means can be used to cluster text documents see
:ref:`sphx_glr_auto_examples_text_plot_document_clustering.py`.
For a comparison between K-Means and MiniBatchKMeans refer to example
:ref:`sphx_glr_auto_examples_cluster_plot_mini_batch_kmeans.py`.
For a comparison between K-Means and BisectingKMeans refer to example
:ref:`sphx_glr_auto_examples_cluster_plot_bisect_kmeans.py`.
"""
_parameter_constraints: dict = {
**_BaseKMeans._parameter_constraints,
"copy_x": ["boolean"],
"algorithm": [StrOptions({"lloyd", "elkan"})],
}
def __init__(
self,
n_clusters=8,
*,
init="k-means++",
n_init="auto",
max_iter=300,
tol=1e-4,
verbose=0,
random_state=None,
copy_x=True,
algorithm="lloyd",
):
super().__init__(
n_clusters=n_clusters,
init=init,
n_init=n_init,
max_iter=max_iter,
tol=tol,
verbose=verbose,
random_state=random_state,
)
self.copy_x = copy_x
self.algorithm = algorithm
def _check_params_vs_input(self, X):
super()._check_params_vs_input(X, default_n_init=10)
self._algorithm = self.algorithm
if self._algorithm == "elkan" and self.n_clusters == 1:
warnings.warn(
(
"algorithm='elkan' doesn't make sense for a single "
"cluster. Using 'lloyd' instead."
),
RuntimeWarning,
)
self._algorithm = "lloyd"
def _warn_mkl_vcomp(self, n_active_threads):
"""Warn when vcomp and mkl are both present"""
warnings.warn(
"KMeans is known to have a memory leak on Windows "
"with MKL, when there are less chunks than available "
"threads. You can avoid it by setting the environment"
f" variable OMP_NUM_THREADS={n_active_threads}."
)
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y=None, sample_weight=None):
"""Compute k-means clustering.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data
will be converted to C ordering, which will cause a memory
copy if the given data is not C-contiguous.
If a sparse matrix is passed, a copy will be made if it's not in
CSR format.
y : Ignored
Not used, present here for API consistency by convention.
sample_weight : array-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations
are assigned equal weight. `sample_weight` is not used during
initialization if `init` is a callable or a user provided array.
.. versionadded:: 0.20
Returns
-------
self : object
Fitted estimator.
"""
X = validate_data(
self,
X,
accept_sparse="csr",
dtype=[np.float64, np.float32],
order="C",
copy=self.copy_x,
accept_large_sparse=False,
)
self._check_params_vs_input(X)
random_state = check_random_state(self.random_state)
sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
self._n_threads = _openmp_effective_n_threads()
# Validate init array
init = self.init
init_is_array_like = _is_arraylike_not_scalar(init)
if init_is_array_like:
init = check_array(init, dtype=X.dtype, copy=True, order="C")
self._validate_center_shape(X, init)
# subtract of mean of x for more accurate distance computations
if not sp.issparse(X):
X_mean = X.mean(axis=0)
# The copy was already done above
X -= X_mean
if init_is_array_like:
init -= X_mean
# precompute squared norms of data points
x_squared_norms = row_norms(X, squared=True)
if self._algorithm == "elkan":
kmeans_single = _kmeans_single_elkan
else:
kmeans_single = _kmeans_single_lloyd
self._check_mkl_vcomp(X, X.shape[0])
best_inertia, best_labels = None, None
for i in range(self._n_init):
# Initialize centers
centers_init = self._init_centroids(
X,
x_squared_norms=x_squared_norms,
init=init,
random_state=random_state,
sample_weight=sample_weight,
)
if self.verbose:
print("Initialization complete")
# run a k-means once
labels, inertia, centers, n_iter_ = kmeans_single(
X,
sample_weight,
centers_init,
max_iter=self.max_iter,
verbose=self.verbose,
tol=self._tol,
n_threads=self._n_threads,
)
# determine if these results are the best so far
# we chose a new run if it has a better inertia and the clustering is
# different from the best so far (it's possible that the inertia is
# slightly better even if the clustering is the same with potentially
# permuted labels, due to rounding errors)
if best_inertia is None or (
inertia < best_inertia
and not _is_same_clustering(labels, best_labels, self.n_clusters)
):
best_labels = labels
best_centers = centers
best_inertia = inertia
best_n_iter = n_iter_
if not sp.issparse(X):
if not self.copy_x:
X += X_mean
best_centers += X_mean
distinct_clusters = len(set(best_labels))
if distinct_clusters < self.n_clusters:
warnings.warn(
"Number of distinct clusters ({}) found smaller than "
"n_clusters ({}). Possibly due to duplicate points "
"in X.".format(distinct_clusters, self.n_clusters),
ConvergenceWarning,
stacklevel=2,
)
self.cluster_centers_ = best_centers
self._n_features_out = self.cluster_centers_.shape[0]
self.labels_ = best_labels
self.inertia_ = best_inertia
self.n_iter_ = best_n_iter
return self
def _mini_batch_step(
X,
sample_weight,
centers,
centers_new,
weight_sums,
random_state,
random_reassign=False,
reassignment_ratio=0.01,
verbose=False,
n_threads=1,
):
"""Incremental update of the centers for the Minibatch K-Means algorithm.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The original data array. If sparse, must be in CSR format.
x_squared_norms : ndarray of shape (n_samples,)
Squared euclidean norm of each data point.
sample_weight : ndarray of shape (n_samples,)
The weights for each observation in `X`.
centers : ndarray of shape (n_clusters, n_features)
The cluster centers before the current iteration
centers_new : ndarray of shape (n_clusters, n_features)
The cluster centers after the current iteration. Modified in-place.
weight_sums : ndarray of shape (n_clusters,)
The vector in which we keep track of the numbers of points in a
cluster. This array is modified in place.
random_state : RandomState instance
Determines random number generation for low count centers reassignment.
See :term:`Glossary <random_state>`.
random_reassign : boolean, default=False
If True, centers with very low counts are randomly reassigned
to observations.
reassignment_ratio : float, default=0.01
Control the fraction of the maximum number of counts for a
center to be reassigned. A higher value means that low count
centers are more likely to be reassigned, which means that the
model will take longer to converge, but should converge in a
better clustering.
verbose : bool, default=False
Controls the verbosity.
n_threads : int, default=1
The number of OpenMP threads to use for the computation.
Returns
-------
inertia : float
Sum of squared distances of samples to their closest cluster center.
The inertia is computed after finding the labels and before updating
the centers.
"""
# Perform label assignment to nearest centers
# For better efficiency, it's better to run _mini_batch_step in a
# threadpool_limit context than using _labels_inertia_threadpool_limit here
labels, inertia = _labels_inertia(X, sample_weight, centers, n_threads=n_threads)
# Update centers according to the labels
if sp.issparse(X):
_minibatch_update_sparse(
X, sample_weight, centers, centers_new, weight_sums, labels, n_threads
)
else:
_minibatch_update_dense(
X,
sample_weight,
centers,
centers_new,
weight_sums,
labels,
n_threads,
)
# Reassign clusters that have very low weight
if random_reassign and reassignment_ratio > 0:
to_reassign = weight_sums < reassignment_ratio * weight_sums.max()
# pick at most .5 * batch_size samples as new centers
if to_reassign.sum() > 0.5 * X.shape[0]:
indices_dont_reassign = np.argsort(weight_sums)[int(0.5 * X.shape[0]) :]
to_reassign[indices_dont_reassign] = False
n_reassigns = to_reassign.sum()
if n_reassigns:
# Pick new clusters amongst observations with uniform probability
new_centers = random_state.choice(
X.shape[0], replace=False, size=n_reassigns
)
if verbose:
print(f"[MiniBatchKMeans] Reassigning {n_reassigns} cluster centers.")
if sp.issparse(X):
assign_rows_csr(
X,
new_centers.astype(np.intp, copy=False),
np.where(to_reassign)[0].astype(np.intp, copy=False),
centers_new,
)
else:
centers_new[to_reassign] = X[new_centers]
# reset counts of reassigned centers, but don't reset them too small
# to avoid instant reassignment. This is a pretty dirty hack as it
# also modifies the learning rates.
weight_sums[to_reassign] = np.min(weight_sums[~to_reassign])
return inertia
| KMeans |
python | scipy__scipy | scipy/integrate/tests/test_integrate.py | {
"start": 13628,
"end": 16413
} | class ____(ODE):
r"""
3 coupled decays suited for banded treatment
(banded mode makes it necessary when N>>3)
"""
stiff = True
stop_t = 0.5
z0 = [5.0, 7.0, 13.0]
lband = 1
uband = 0
lmbd = [0.17, 0.23, 0.29] # fictitious decay constants
def f(self, z, t):
lmbd = self.lmbd
return np.array([-lmbd[0]*z[0],
-lmbd[1]*z[1] + lmbd[0]*z[0],
-lmbd[2]*z[2] + lmbd[1]*z[1]])
def jac(self, z, t):
# The full Jacobian is
#
# [-lmbd[0] 0 0 ]
# [ lmbd[0] -lmbd[1] 0 ]
# [ 0 lmbd[1] -lmbd[2]]
#
# The lower and upper bandwidths are lband=1 and uband=0, resp.
# The representation of this array in packed format is
#
# [-lmbd[0] -lmbd[1] -lmbd[2]]
# [ lmbd[0] lmbd[1] 0 ]
lmbd = self.lmbd
j = np.zeros((self.lband + self.uband + 1, 3), order='F')
def set_j(ri, ci, val):
j[self.uband + ri - ci, ci] = val
set_j(0, 0, -lmbd[0])
set_j(1, 0, lmbd[0])
set_j(1, 1, -lmbd[1])
set_j(2, 1, lmbd[1])
set_j(2, 2, -lmbd[2])
return j
def verify(self, zs, t):
# Formulae derived by hand
lmbd = np.array(self.lmbd)
d10 = lmbd[1] - lmbd[0]
d21 = lmbd[2] - lmbd[1]
d20 = lmbd[2] - lmbd[0]
e0 = np.exp(-lmbd[0] * t)
e1 = np.exp(-lmbd[1] * t)
e2 = np.exp(-lmbd[2] * t)
u = np.vstack((
self.z0[0] * e0,
self.z0[1] * e1 + self.z0[0] * lmbd[0] / d10 * (e0 - e1),
self.z0[2] * e2 + self.z0[1] * lmbd[1] / d21 * (e1 - e2) +
lmbd[1] * lmbd[0] * self.z0[0] / d10 *
(1 / d20 * (e0 - e2) - 1 / d21 * (e1 - e2)))).transpose()
return allclose(u, zs, atol=self.atol, rtol=self.rtol)
PROBLEMS = [SimpleOscillator, ComplexExp, Pi, CoupledDecay]
#------------------------------------------------------------------------------
def f(t, x):
dxdt = [x[1], -x[0]]
return dxdt
def jac(t, x):
j = array([[0.0, 1.0],
[-1.0, 0.0]])
return j
def f1(t, x, omega):
dxdt = [omega*x[1], -omega*x[0]]
return dxdt
def jac1(t, x, omega):
j = array([[0.0, omega],
[-omega, 0.0]])
return j
def f2(t, x, omega1, omega2):
dxdt = [omega1*x[1], -omega2*x[0]]
return dxdt
def jac2(t, x, omega1, omega2):
j = array([[0.0, omega1],
[-omega2, 0.0]])
return j
def fv(t, x, omega):
dxdt = [omega[0]*x[1], -omega[1]*x[0]]
return dxdt
def jacv(t, x, omega):
j = array([[0.0, omega[0]],
[-omega[1], 0.0]])
return j
| CoupledDecay |
python | geekcomputers__Python | Quizzler Using Tkinter and Trivia DB API/ui.py | {
"start": 520,
"end": 5868
} | class ____:
def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.window = Tk()
self.window.title("Quizzler")
self.window.config(padx=20, pady=20, bg=BACKGROUND)
self.score_label = Label(text="Score: 0", fg="white", bg=BACKGROUND, font=("Lucida sans", 15, "bold"))
self.score_label.grid(row=0, column=1)
self.canvas = Canvas(width=1000, height=550, bg=CANVAS)
self.question_text = self.canvas.create_text(
500, 100, width=800, text="Some question text", fill=TEXT, font=FONT, anchor="center", justify="center"
)
self.canvas.grid(row=1, column=0, columnspan=2, pady=50)
self.opt_selected = IntVar()
self.options = self.create_radio_buttons()
self.submit_button = Button(
text="Submit", command=self.submit_answer, fg=TEXT, font=FONT
)
self.submit_button.grid(row=3, column=0, columnspan=2)
if error_message:
self.display_error_message(error_message)
else:
self.get_next_question()
self.window.mainloop()
def create_radio_buttons(self):
radio_buttons = []
y_position = 230
for i in range(4):
radio_button = Radiobutton(
self.canvas, text="", variable=self.opt_selected, value=i + 1, font=FONT, bg=CANVAS, anchor="w",
justify="left", fg=TEXT, wraplength=900
)
radio_buttons.append(radio_button)
self.canvas.create_window(50, y_position, window=radio_button, anchor="w")
y_position += 65
return radio_buttons
def get_next_question(self):
if self.quiz.still_has_questions():
self.opt_selected.set(0) # Reset selection
q_text = self.quiz.next_question()
self.canvas.itemconfig(self.question_text, text=q_text)
self.canvas.config(bg=CANVAS)
self.window.config(bg=BACKGROUND)
for option in self.options:
option.config(bg=CANVAS, fg=TEXT)
self.display_options()
self.score_label.config(bg=BACKGROUND, text=f"Score: {self.quiz.score}")
self.canvas.itemconfig(self.question_text, fill=TEXT)
else:
self.display_result()
def display_options(self):
current_options = self.quiz.current_question.options
for i, option in enumerate(current_options):
self.options[i].config(text=option)
def submit_answer(self):
selected_option_index = self.opt_selected.get() - 1
if selected_option_index >= 0:
user_answer = self.quiz.current_question.options[selected_option_index]
self.quiz.check_answer(user_answer)
if self.quiz.check_answer(user_answer):
self.quiz.score += 1
self.canvas.config(bg=R_CANVAS)
self.window.config(bg=R_BACKGROUND)
for option in self.options:
option.config(bg=R_CANVAS, fg=R_TEXT)
self.canvas.itemconfig(self.question_text, fill=R_TEXT)
self.score_label.config(bg=R_BACKGROUND)
else:
self.canvas.config(bg=W_CANVAS)
self.window.config(bg=W_BACKGROUND)
for option in self.options:
option.config(bg=W_CANVAS, fg=W_TEXT)
self.canvas.itemconfig(self.question_text, fill=W_TEXT)
self.score_label.config(bg=W_BACKGROUND)
self.window.after(1000, self.get_next_question)
def display_result(self):
for option in self.options:
option.config(bg=CANVAS, fg=TEXT)
option.destroy()
if self.quiz.score <= 3:
self.result_text = f"You've completed the quiz!\nYour final score: {self.quiz.score}/{self.quiz.question_number}\nBetter luck next time! Keep practicing!"
elif self.quiz.score <= 6:
self.result_text = f"You've completed the quiz!\nYour final score: {self.quiz.score}/{self.quiz.question_number}\nGood job! You're getting better!"
elif self.quiz.score <= 8:
self.result_text = f"You've completed the quiz!\nYour final score: {self.quiz.score}/{self.quiz.question_number}\nGreat work! You're almost there!"
else:
self.result_text = f"You've completed the quiz!\nYour final score: {self.quiz.score}/{self.quiz.question_number}\nExcellent! You're a Quiz Master!"
self.score_label.config(bg=BACKGROUND, text=f"Score: {self.quiz.score}")
self.canvas.config(bg=CANVAS)
self.window.config(bg=BACKGROUND)
self.canvas.itemconfig(self.question_text, fill=TEXT)
self.score_label.config(bg=BACKGROUND)
self.canvas.itemconfig(self.question_text, text=self.result_text)
self.canvas.coords(self.question_text, 500, 225) # Centered position
self.submit_button.config(state="disabled")
def display_error_message(self, message):
for option in self.options:
option.config(bg=CANVAS, fg=TEXT)
option.destroy()
self.canvas.itemconfig(self.question_text, text=message)
self.canvas.coords(self.question_text, 500, 225) # Centered position
self.submit_button.config(state="disabled")
| QuizInterface |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.