Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/docs/source/src/rust/user-guide/expressions/expression-expansion.rs
7889 views
1
fn main() -> Result<(), Box<dyn std::error::Error>> {
2
// --8<-- [start:df]
3
use polars::prelude::*;
4
5
// Data as of 14th October 2024, ~3pm UTC
6
let df = df!(
7
"ticker" => ["AAPL", "NVDA", "MSFT", "GOOG", "AMZN"],
8
"company_name" => ["Apple", "NVIDIA", "Microsoft", "Alphabet (Google)", "Amazon"],
9
"price" => [229.9, 138.93, 420.56, 166.41, 188.4],
10
"day_high" => [231.31, 139.6, 424.04, 167.62, 189.83],
11
"day_low" => [228.6, 136.3, 417.52, 164.78, 188.44],
12
"year_high" => [237.23, 140.76, 468.35, 193.31, 201.2],
13
"year_low" => [164.08, 39.23, 324.39, 121.46, 118.35],
14
)?;
15
16
println!("{df}");
17
// --8<-- [end:df]
18
19
// --8<-- [start:col-with-names]
20
let eur_usd_rate = 1.09; // As of 14th October 2024
21
22
let result = df
23
.clone()
24
.lazy()
25
.with_column(
26
(cols(["price", "day_high", "day_low", "year_high", "year_low"]).as_expr()
27
/ lit(eur_usd_rate))
28
.round(2, RoundMode::default()),
29
)
30
.collect()?;
31
println!("{result}");
32
// --8<-- [end:col-with-names]
33
34
// --8<-- [start:expression-list]
35
let exprs = [
36
(col("price") / lit(eur_usd_rate)).round(2, RoundMode::default()),
37
(col("day_high") / lit(eur_usd_rate)).round(2, RoundMode::default()),
38
(col("day_low") / lit(eur_usd_rate)).round(2, RoundMode::default()),
39
(col("year_high") / lit(eur_usd_rate)).round(2, RoundMode::default()),
40
(col("year_low") / lit(eur_usd_rate)).round(2, RoundMode::default()),
41
];
42
43
let result2 = df.clone().lazy().with_columns(exprs).collect()?;
44
println!("{}", result.equals(&result2));
45
// --8<-- [end:expression-list]
46
47
// --8<-- [start:col-with-dtype]
48
let result = df
49
.clone()
50
.lazy()
51
.with_column(
52
(dtype_col(&DataType::Float64).as_selector().as_expr() / lit(eur_usd_rate))
53
.round(2, RoundMode::default()),
54
)
55
.collect()?;
56
println!("{result}");
57
// --8<-- [end:col-with-dtype]
58
59
// --8<-- [start:col-with-dtypes]
60
let result2 = df
61
.clone()
62
.lazy()
63
.with_column(
64
(dtype_cols([DataType::Float32, DataType::Float64])
65
.as_selector()
66
.as_expr()
67
/ lit(eur_usd_rate))
68
.round(2, RoundMode::default()),
69
)
70
.collect()?;
71
println!("{}", result.equals(&result2));
72
// --8<-- [end:col-with-dtypes]
73
74
// --8<-- [start:col-with-regex]
75
// NOTE: Using regex inside `col`/`cols` requires the feature flag `regex`.
76
let result = df
77
.clone()
78
.lazy()
79
.select([cols(["ticker", "^.*_high$", "^.*_low$"]).as_expr()])
80
.collect()?;
81
println!("{result}");
82
// --8<-- [end:col-with-regex]
83
84
// --8<-- [start:all]
85
let result = df.clone().lazy().select([all().as_expr()]).collect()?;
86
println!("{}", result.equals(&df));
87
// --8<-- [end:all]
88
89
// --8<-- [start:all-exclude]
90
let result = df
91
.clone()
92
.lazy()
93
.select([all().exclude_cols(["^day_.*$"]).as_expr()])
94
.collect()?;
95
println!("{result}");
96
// --8<-- [end:all-exclude]
97
98
// --8<-- [start:col-exclude]
99
let result = df
100
.clone()
101
.lazy()
102
.select([dtype_col(&DataType::Float64)
103
.as_selector()
104
.exclude_cols(["^day_.*$"])
105
.as_expr()])
106
.collect()?;
107
println!("{result}");
108
// --8<-- [end:col-exclude]
109
110
// --8<-- [start:duplicate-error]
111
let gbp_usd_rate = 1.31; // As of 14th October 2024
112
113
let result = df
114
.clone()
115
.lazy()
116
.select([
117
col("price") / lit(gbp_usd_rate),
118
col("price") / lit(eur_usd_rate),
119
])
120
.collect();
121
match result {
122
Ok(df) => println!("{df}"),
123
Err(e) => println!("{e}"),
124
};
125
// --8<-- [end:duplicate-error]
126
127
// --8<-- [start:alias]
128
let _result = df
129
.clone()
130
.lazy()
131
.select([
132
(col("price") / lit(gbp_usd_rate)).alias("price (GBP)"),
133
(col("price") / lit(eur_usd_rate)).alias("price (EUR)"),
134
])
135
.collect()?;
136
// --8<-- [end:alias]
137
138
// --8<-- [start:prefix-suffix]
139
let result = df
140
.clone()
141
.lazy()
142
.select([
143
(col("^year_.*$") / lit(eur_usd_rate))
144
.name()
145
.prefix("in_eur_"),
146
(cols(["day_high", "day_low"]).as_expr() / lit(gbp_usd_rate))
147
.name()
148
.suffix("_gbp"),
149
])
150
.collect()?;
151
println!("{result}");
152
// --8<-- [end:prefix-suffix]
153
154
// --8<-- [start:name-map]
155
// There is also `name().to_uppercase()`, so this usage of `map` is moot.
156
let result = df
157
.clone()
158
.lazy()
159
.select([all()
160
.as_expr()
161
.name()
162
.map(PlanCallback::new(|name: PlSmallStr| {
163
Ok(PlSmallStr::from_string(name.to_ascii_uppercase()))
164
}))])
165
.collect()?;
166
println!("{result}");
167
// --8<-- [end:name-map]
168
169
// --8<-- [start:for-with_columns]
170
let mut result = df.clone().lazy();
171
for tp in ["day", "year"] {
172
let high = format!("{tp}_high");
173
let low = format!("{tp}_low");
174
let aliased = format!("{tp}_amplitude");
175
result = result.with_column((col(high) - col(low)).alias(aliased))
176
}
177
let result = result.collect()?;
178
println!("{result}");
179
// --8<-- [end:for-with_columns]
180
181
// --8<-- [start:yield-expressions]
182
let mut exprs: Vec<Expr> = vec![];
183
for tp in ["day", "year"] {
184
let high = format!("{tp}_high");
185
let low = format!("{tp}_low");
186
let aliased = format!("{tp}_amplitude");
187
exprs.push((col(high) - col(low)).alias(aliased))
188
}
189
let result = df.lazy().with_columns(exprs).collect()?;
190
println!("{result}");
191
// --8<-- [end:yield-expressions]
192
193
// --8<-- [start:selectors]
194
// Selectors are not available in Rust yet.
195
// Refer to https://github.com/pola-rs/polars/issues/10594
196
// --8<-- [end:selectors]
197
198
// --8<-- [start:selectors-set-operations]
199
// Selectors are not available in Rust yet.
200
// Refer to https://github.com/pola-rs/polars/issues/10594
201
// --8<-- [end:selectors-set-operations]
202
203
// --8<-- [start:selectors-expressions]
204
// Selectors are not available in Rust yet.
205
// Refer to https://github.com/pola-rs/polars/issues/10594
206
// --8<-- [end:selectors-expressions]
207
208
// --8<-- [start:selector-ambiguity]
209
// Selectors are not available in Rust yet.
210
// Refer to https://github.com/pola-rs/polars/issues/10594
211
// --8<-- [end:selector-ambiguity]
212
213
// --8<-- [start:as_expr]
214
// Selectors are not available in Rust yet.
215
// Refer to https://github.com/pola-rs/polars/issues/10594
216
// --8<-- [end:as_expr]
217
218
// --8<-- [start:is_selector]
219
// Selectors are not available in Rust yet.
220
// Refer to https://github.com/pola-rs/polars/issues/10594
221
// --8<-- [end:is_selector]
222
223
// --8<-- [start:expand_selector]
224
// Selectors are not available in Rust yet.
225
// Refer to https://github.com/pola-rs/polars/issues/10594
226
// --8<-- [end:expand_selector]
227
228
Ok(())
229
}
230
231