Comments (6)
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)
┌─────┬─────┬──────────────────┬───────────┬───┬───────────┬──────────────────┬───────┬────────────┐
│ A1 ┆ A2 ┆ B1 ┆ B2 ┆ … ┆ As ┆ Bs ┆ D1 ┆ D2 │
│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ list[f64] ┆ list[i64] ┆ ┆ struct[2] ┆ struct[2] ┆ cat ┆ cat │
╞═════╪═════╪══════════════════╪═══════════╪═══╪═══════════╪══════════════════╪═══════╪════════════╡
│ 1 ┆ 2 ┆ [2.2, 4.4, 6.6] ┆ [1, 1] ┆ … ┆ {1,2} ┆ {[2.2, 4.4, ┆ Hello ┆ The Test │
│ ┆ ┆ ┆ ┆ ┆ ┆ 6.6],[1, 1]} ┆ ┆ │
│ 2 ┆ 8 ┆ [12.0, 16.0, ┆ [1, 2] ┆ … ┆ {2,8} ┆ {[12.0, 16.0, ┆ World ┆ Was For │
│ ┆ ┆ 14.0] ┆ ┆ ┆ ┆ 14.0],[1, 2]} ┆ ┆ │
│ 3 ┆ 7 ┆ [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.
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.
They're in pl.expr.*.Expr*NameSpace
pl.expr.struct.ExprStructNameSpace
pl.expr.datetime.ExprDateTimeNameSpace
pl.expr.list.ExprListNameSpace
from polars.
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.
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.
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)
- depr: enforce `ignore_nulls` default change in 1.0 HOT 1
- Multiplying or dividing pl.duration converts to float HOT 1
- Post-join `panic` on `select` after joining on keys with different names with "coalesce=False"
- `df.group_by(series).agg(...)` fails if df was built using `pl.concat` (ShapeError) HOT 2
- `concat_list` PanicException inside `agg()`
- A regression in numpy-to-series conversion
- PanicException when using `collect(streaming=True)` on an empty `.parquet` file with joins.
- Regression: `.collect()` no longer generates `unexpected keywords` error. HOT 1
- Shift() fails if the argument is contained in a column
- Support boolean iterable for argument `descending` in `DataFrame.set_sorted()`
- polars.exceptions.ComputeError: could not append value: "2024-03-05T17:39:39Z" of type: str to the builder; make sure that all rows have the same schema or consider increasing `infer_schema_length` HOT 1
- Re-aliasing existing `LazyFrame` column name does not return the last version HOT 2
- dt.trunctate is 3-4x slower in polars compared to pandas HOT 2
- `.struct.with_fields` PanicException inside `agg`
- add `show` method for syntax compatibility with pyspark/duckdb/etc dataframe API
- `gather` in `agg` context gathers values from other groups
- ShapeError: filter's length: 155 differs from that of the series: 0 HOT 6
- Version 0.20.30 bug HOT 3
- `.list.to_array()` fails if first element of a list column is excluded HOT 1
- `scan_parquet` + `with_row_index` causing `pl.len()` to return 0
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from polars.