Code Monkey home page Code Monkey logo

Comments (6)

mkleinbort-ic avatar mkleinbort-ic commented on May 28, 2024 1

I'd add that polars lets you create a "mixed-dtype" list, it just coerces everything to some overarching dtype

df_for_testing = pl.DataFrame({
    'A1': [1,2,3],
    'A2': [2,8,7],
    'B1':[[2.2,4.4,6.6],[12,16,14],[152,257,252]],
    'B2':[[1,1],[1,2],[2,1]],
    'C1':['Hello', 'World','!'],
    'C2':['The Test', 'Was For', 'The Takers']
}).with_columns([
    pl.struct(['A1','A2']).alias('As'),
    pl.struct(['B1','B2']).alias('Bs'),
]).with_columns(
    D1 = pl.col('C1').cast(pl.Categorical), 
    D2 = pl.col('C2').cast(pl.Categorical)
)

shape: (3, 10)
┌─────┬─────┬──────────────────┬───────────┬───┬───────────┬──────────────────┬───────┬────────────┐
│ A1A2B1B2        ┆ … ┆ AsBsD1D2         │
│ ------------       ┆   ┆ ------------        │
│ i64i64list[f64]        ┆ list[i64] ┆   ┆ struct[2] ┆ struct[2]        ┆ catcat        │
╞═════╪═════╪══════════════════╪═══════════╪═══╪═══════════╪══════════════════╪═══════╪════════════╡
│ 12   ┆ [2.2, 4.4, 6.6]  ┆ [1, 1]    ┆ … ┆ {1,2}     ┆ {[2.2, 4.4,      ┆ HelloThe Test   │
│     ┆     ┆                  ┆           ┆   ┆           ┆ 6.6],[1, 1]}     ┆       ┆            │
│ 28   ┆ [12.0, 16.0,     ┆ [1, 2]    ┆ … ┆ {2,8}     ┆ {[12.0, 16.0,    ┆ WorldWas For    │
│     ┆     ┆ 14.0]            ┆           ┆   ┆           ┆ 14.0],[1, 2]}    ┆       ┆            │
│ 37   ┆ [152.0, 257.0,   ┆ [2, 1]    ┆ … ┆ {3,7}     ┆ {[152.0, 257.0,  ┆ !     ┆ The Takers │
│     ┆     ┆ 252.0]           ┆           ┆   ┆           ┆ 252.0],[2, 1]}   ┆       ┆            │
└─────┴─────┴──────────────────┴───────────┴───┴───────────┴──────────────────┴───────┴────────────┘

df_for_testing.select(pl.concat_list(pl.all()))

shape: (3, 1)
┌────────────────────────────┐
│ A1                         │
│ ---                        │
│ list[str]                  │
╞════════════════════════════╡
│ ["1", "2", … "The Test"]   │
│ ["2", "8", … "Was For"]    │
│ ["3", "7", … "The Takers"] │
└────────────────────────────┘

What I'm asking for is no more dangerous than

(df
  .unnest('structColumn')
  .with_columns(values= pl.concat_list(<<the_field_names_of_the_struct>>))
  .drop(<<the_field_names_of_the_struct>>)
)

from polars.

deanm0000 avatar deanm0000 commented on May 28, 2024 1

Until it's officially added you can monkey patch this:

pl.Expr.struct_to_list=lambda col: (
    col.map_batches(lambda x: (
    x.to_frame().unnest(x.name).select(pl.concat_list(pl.all())).to_series()
))
)

Then you can do

df.with_columns(pl.col('As','Bs').struct_to_list())

Note: I don't know how to monkey-patch it to the struct namespace since it's not just inserting .struct.

from polars.

cmdlineluser avatar cmdlineluser commented on May 28, 2024 1

They're in pl.expr.*.Expr*NameSpace

pl.expr.struct.ExprStructNameSpace
pl.expr.datetime.ExprDateTimeNameSpace
pl.expr.list.ExprListNameSpace

from polars.

deanm0000 avatar deanm0000 commented on May 28, 2024 1

That got a little tricky but I think this is it then...

pl.expr.struct.ExprStructNameSpace.to_list=lambda col: (
    pl.Expr._from_pyexpr(col._pyexpr).map_batches(lambda x: (
    x.to_frame().unnest(x.name).select(pl.concat_list(pl.all())).to_series()
))
)

Essentially when you access self (or col as I've named it) you don't get access to .map_batches directly but I think this is the right trick.

from polars.

cmdlineluser avatar cmdlineluser commented on May 28, 2024

I had previously gone looking for a .struct.values() / .struct.to_list() type function.

I assumed the reason it did not exist is because struct values are not guaranteed to be of the same type.

Would be useful for when that is the case though.

from polars.

mkleinbort-ic avatar mkleinbort-ic commented on May 28, 2024

Note: I don't know how to monkey-patch it to the struct namespace since it's not just inserting .struct.

Yes, it'd be nice to be able to monkey patch methods in the namespaces - it came up for me when trying to add a .dt.day_name()

from polars.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.