golars

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 12, 2026 License: MIT Imports: 15 Imported by: 0

README

Golars

Go Reference

A high-performance DataFrame library for Go, modeled after Polars.

Golars brings the power of columnar data processing to Go with an expression-based API, lazy evaluation with query optimization, and comprehensive I/O support.

import "github.com/msjurset/golars"

Features

  • Columnar storage with offset-based strings and null bitmaps
  • Expression DSL — composable, type-safe column operations with math, string, temporal, cumulative, and rolling namespaces
  • Lazy evaluation — query optimization with predicate pushdown, projection pushdown, constant folding, and CSE
  • GroupBy & Join — hash-based grouping (map-based and expression-based) and all 7 join types
  • Window functions — SQL-style Over(partitionBy...) expressions
  • SQL interface — register DataFrames and query with standard SQL, including full JOIN and table alias resolution (SELECT e.name FROM emps e)
  • I/O — CSV, JSON, NDJSON, Parquet (with Snappy compression), Excel (.xlsx), database/sql
  • Temporal types — Date, DateTime, Time, Duration with .Dt() namespace
  • Go 1.24+ — uses generics and range-over-func iterators

Quick Start

package main

import (
    "fmt"
    "log"

    "github.com/msjurset/golars"
)

func main() {
    // Create a DataFrame
    df, err := golars.NewDataFrame(
        golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie", "Diana"}),
        golars.NewInt64Series("age", []int64{25, 30, 35, 40}),
        golars.NewFloat64Series("score", []float64{88.5, 92.3, 76.1, 95.0}),
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(df)
}

Output:

┌─────────┬─────┬───────┐
│ name    │ age │ score │
│ ---     │ --- │ ---   │
│ str     │ i64 │ f64   │
╞═════════╪═════╪═══════╡
│ Alice   │  25 │ 88.50 │
│ Bob     │  30 │ 92.30 │
│ Charlie │  35 │ 76.10 │
│ Diana   │  40 │ 95.00 │
└─────────┴─────┴───────┘

Core Concepts

DataFrames

An immutable collection of named, typed columns (Series). All operations return new DataFrames.

// Select columns
selected, _ := df.Select("name", "score")

// Drop columns
trimmed, _ := df.Drop("age")

// Add a computed column
df2, _ := df.WithColumn(golars.NewBooleanSeries("senior", []bool{false, false, true, true}))

// Sort
sorted, _ := df.Sort("score", true) // descending

// Head / Tail / Slice
first2 := df.Head(2)
last2 := df.Tail(2)
middle := df.Slice(1, 3)

// Sampling
sample := df.Sample(2, 42)
fraction := df.SampleFraction(0.5, 42)
Expressions

Expressions are the heart of golars. They compose into computation trees that can be evaluated eagerly or deferred for lazy optimization.

// Filter with expressions
ctx := &golars.ExprContext{DF: df}
mask, _ := golars.Col("age").Gt(golars.Lit(30)).Evaluate(ctx)
filtered, _ := df.Filter(mask)

// Arithmetic (Add, Sub, Mul, Div, Mod, Pow)
curved, _ := golars.Col("score").Mul(golars.Lit(1.1)).Alias("curved").Evaluate(ctx)
df2, _ := df.WithColumn(curved)

// Conditional (When/Then/Otherwise)
tier, _ := golars.When(golars.Col("age").Gt(golars.Lit(35))).
    Then(golars.Lit("senior")).
    Otherwise(golars.Lit("junior")).
    Evaluate(ctx)
Numeric Math

All common math functions are available as expression methods:

ctx := &golars.ExprContext{DF: df}

// Absolute value
abs, _ := golars.Col("profit").Abs().Evaluate(ctx)

// Square root, log, exp
sqrt, _ := golars.Col("variance").Sqrt().Evaluate(ctx)
logVal, _ := golars.Col("x").Log().Evaluate(ctx)
expVal, _ := golars.Col("x").Exp().Evaluate(ctx)

// Rounding
rounded, _ := golars.Col("price").Round(2).Evaluate(ctx)
floored, _ := golars.Col("price").Floor().Evaluate(ctx)
ceiled, _ := golars.Col("price").Ceil().Evaluate(ctx)
Predicates
// Membership testing
inSet, _ := golars.Col("status").IsIn("active", "pending").Evaluate(ctx)

// Range checking
inRange, _ := golars.Col("age").IsBetween(golars.Lit(18), golars.Lit(65)).Evaluate(ctx)
Selection & Sorting
// First/Last aggregation
first, _ := golars.Col("name").First().Evaluate(ctx)
last, _ := golars.Col("name").Last().Evaluate(ctx)

// Head/Tail on expressions
top3, _ := golars.Col("score").Head(3).Evaluate(ctx)
bot3, _ := golars.Col("score").Tail(3).Evaluate(ctx)

// Gather by indices
picked, _ := golars.Col("name").Gather([]int{0, 2, 4}).Evaluate(ctx)

// Unique values
uniq, _ := golars.Col("category").Unique().Evaluate(ctx)

// Sort one column by another
sorted, _ := golars.Col("name").SortBy(golars.Col("score"), true).Evaluate(ctx)
GroupBy & Aggregation
// Map-based aggregation
grouped, _ := df.GroupBy("department")
result, _ := grouped.Agg(map[string]golars.AggFunc{
    "salary": golars.AggMean,
    "bonus":  golars.AggSum,
    "name":   golars.AggCount,
})

// Expression-based aggregation (Polars-style)
result, _ = golars.GroupByAgg(grouped,
    golars.Col("salary").Mean().Alias("avg_salary"),
    golars.Col("salary").Sum().Alias("total_salary"),
    golars.Col("name").Count().Alias("headcount"),
)

Available aggregations: Sum, Mean, Min, Max, Count, First, Last, Std, Var, NUnique, Median, Quantile(p).

Joins

All 7 join types are supported:

result, _ := left.Join(right, []string{"id"}, golars.InnerJoin)
result, _ = left.Join(right, []string{"id"}, golars.LeftJoin)
result, _ = left.Join(right, []string{"id"}, golars.RightJoin)
result, _ = left.Join(right, []string{"id"}, golars.FullJoin)
result, _ = left.Join(right, []string{"id"}, golars.SemiJoin)
result, _ = left.Join(right, []string{"id"}, golars.AntiJoin)
result, _ = left.Join(right, []string{"id"}, golars.CrossJoin)
Window Functions

SQL-style window functions compute per-partition aggregates broadcast back to the original row order:

ctx := &golars.ExprContext{DF: df}
avgByDept, _ := golars.Col("salary").Mean().Over("department").Evaluate(ctx)
Row Transforms
// Shift values by n positions
shifted, _ := golars.Col("price").Shift(1).Evaluate(ctx)

// Element-wise difference
diff, _ := golars.Col("price").Diff(1).Evaluate(ctx)

// Percentage change
pctChg, _ := golars.Col("price").PctChange(1).Evaluate(ctx)

// Rank
ranked, _ := golars.Col("score").Rank().Evaluate(ctx)
Cumulative Operations
cumSum, _ := golars.Col("revenue").Cum().Sum().Evaluate(ctx)
cumProd, _ := golars.Col("growth").Cum().Prod().Evaluate(ctx)
cumMin, _ := golars.Col("price").Cum().Min().Evaluate(ctx)
cumMax, _ := golars.Col("price").Cum().Max().Evaluate(ctx)
Rolling Windows
rollMean, _ := golars.Col("price").Rolling(7).Mean().Evaluate(ctx)
rollSum, _ := golars.Col("volume").Rolling(7).Sum().Evaluate(ctx)
rollMin, _ := golars.Col("price").Rolling(7).Min().Evaluate(ctx)
rollMax, _ := golars.Col("price").Rolling(7).Max().Evaluate(ctx)
rollStd, _ := golars.Col("price").Rolling(7).Std().Evaluate(ctx)
Lazy Evaluation

Lazy evaluation records operations as a query plan, then optimizes and executes when you call Collect():

result, err := golars.Lazy(df).
    Filter(golars.Col("score").Gt(golars.Lit(80.0))).
    Sort("score", true).
    Head(10).
    Collect()

The optimizer applies:

  • Predicate pushdown — pushes filters closer to data sources
  • Projection pushdown — only reads needed columns
  • Constant folding — evaluates constant expressions at plan time
  • Common subexpression elimination — avoids redundant computation
  • Projection merging — combines adjacent select nodes

Inspect the query plan:

fmt.Println(golars.Lazy(df).
    Filter(golars.Col("score").Gt(golars.Lit(80.0))).
    Explain())

Lazy I/O scans — only materialize data when collected:

result, _ := golars.ScanCSV("large.csv").
    Filter(golars.Col("status").Eq(golars.Lit("active"))).
    Select(golars.Col("name"), golars.Col("email")).
    Collect()

result, _ = golars.ScanParquet("data.parquet").
    Filter(golars.Col("year").Gt(golars.Lit(2020))).
    Collect()
SQL Interface

Register DataFrames and query them with SQL:

ctx := golars.NewSQLContext()
ctx.Register("users", df)

result, err := ctx.Execute(`
    SELECT name, score
    FROM users
    WHERE age > 30
    ORDER BY score DESC
    LIMIT 5
`)

Supports: SELECT, FROM, WHERE, JOIN, GROUP BY, ORDER BY, LIMIT, aggregate functions, string functions.

Row Iteration

Use Go 1.23+ range-over-func iterators:

for row := range df.Rows() {
    name, _ := row.String("name")
    age, _ := row.Int64("age")
    fmt.Printf("%s: %d\n", name, age)
}
Series Operations

Series support rich analytics:

s := golars.NewFloat64Series("x", []float64{1, 2, 3, 4, 5})

// Aggregation
sum, _ := s.Sum()
mean, _ := s.Mean()
std, _ := s.Std()
median := ... // via expression: Col("x").Median()

// Rolling windows
rm := s.RollingMean(3)
rs := s.RollingSum(3)

// Cumulative
cs := s.CumSum()
cp := s.CumProd()

// Shifting
shifted := s.Shift(1)
diff := s.Diff(1)
pct := s.PctChange(1)

// Ranking
ranked := s.Rank("average") // "average", "min", "max", "dense", "ordinal"

// Interpolation
filled := s.Interpolate("linear") // "linear", "forward_fill", "backfill"
String Operations

The .Str() namespace provides string operations on both Series and expressions:

names := golars.NewStringSeries("name", []string{"Alice Smith", "Bob Jones", "Charlie Brown"})

// Checks
contains := names.Str().Contains("Smith")      // Boolean Series
starts := names.Str().StartsWith("Alice")      // Boolean Series
ends := names.Str().EndsWith("Brown")          // Boolean Series

// Transformations
upper := names.Str().ToUpper()                  // "ALICE SMITH", ...
lower := names.Str().ToLower()                  // "alice smith", ...
capped := names.Str().Capitalize()              // "Alice smith", ...

// Extraction
first := names.Str().Split(" ", 0)              // "Alice", "Bob", "Charlie"
sub := names.Str().Slice(0, 5)                  // "Alice", "Bob J", "Charl"
lengths := names.Str().Lengths()                // 11, 9, 13

// Manipulation
trimmed := names.Str().Trim()
replaced := names.Str().Replace("Smith", "Lee")
padded := names.Str().Pad(20, "right", ' ')
zfilled := names.Str().ZFill(15)
stripped := names.Str().Strip(" ")

// Regex
extracted := names.Str().Extract(`(\w+)`, 1)    // First word
count := names.Str().CountMatches(`[aeiou]`)    // Vowel count

// Parse to DateTime
dates := golars.NewStringSeries("d", []string{"2024-01-15", "2024-06-30"})
dt := dates.Str().ToDatetime("2006-01-02")      // DateTime Series
Temporal Operations

The .Dt() namespace provides temporal operations on Date, DateTime, Time, and Duration Series:

// Component extraction
year := golars.Col("timestamp").Dt().Year()
month := golars.Col("timestamp").Dt().Month()
day := golars.Col("timestamp").Dt().Day()
hour := golars.Col("timestamp").Dt().Hour()
weekday := golars.Col("timestamp").Dt().Weekday()
quarter := golars.Col("timestamp").Dt().Quarter()
dayOfYear := golars.Col("timestamp").Dt().DayOfYear()
isoWeek := golars.Col("timestamp").Dt().IsoWeek()

// Truncation
truncated := golars.Col("timestamp").Dt().Truncate("1d")  // "1h", "1d", "1mo", "1y"

// Formatting
formatted := golars.Col("timestamp").Dt().Strftime("2006-01-02")

// Offset
shifted := golars.Col("timestamp").Dt().OffsetBy("7d")    // "1d", "2mo", "-1y", "3h"

// Epoch conversion
epochSec := golars.Col("timestamp").Dt().Epoch("s")       // "s", "ms", "us", "ns"

// Duration total seconds
totalSec := golars.Col("duration").Dt().TotalSeconds()     // Float64
Name Namespace

Transform expression output names:

prefixed := golars.Col("score").Name().Prefix("raw_")   // "raw_score"
suffixed := golars.Col("score").Name().Suffix("_v2")     // "score_v2"
mapped := golars.Col("score").Name().Map(strings.ToUpper) // "SCORE"
Null Handling
// Create Series with nulls
s := golars.NewInt64SeriesWithValidity("x", []int64{1, 0, 3}, []bool{true, false, true})

s.IsNull(1)     // true
s.NullCount()   // 1
s.HasNulls()    // true

dropped := s.DropNulls()            // [1, 3]
filled := s.FillNullInt64(0)        // [1, 0, 3]

// Expression null handling
isNull := golars.Col("x").IsNull()
isNotNull := golars.Col("x").IsNotNull()
filled := golars.Col("x").FillNull(golars.Lit(0))

// DataFrame null handling
clean := df.DropNulls()
filled, _ := df.FillNull(map[string]any{"score": 0.0})
Type Casting
ints := golars.NewInt64Series("x", []int64{1, 2, 3})
floats, _ := ints.Cast(golars.Float64)
strings, _ := ints.Cast(golars.String)

// TryCast returns null instead of error on failure
safe, _ := s.TryCast(golars.Int64)

// Expression cast
casted := golars.Col("x").Cast(golars.Float64)
tryCasted := golars.Col("x").TryCast(golars.Float64)
Reshaping
// Pivot (long to wide)
pivoted, _ := df.Pivot("name", "subject", "score")

// Unpivot/Melt (wide to long)
melted, _ := df.Unpivot([]string{"id"}, []string{"math", "english"})

// Transpose
transposed, _ := df.Transpose()

// Explode
exploded, _ := df.Explode("tags")

I/O

CSV
// Read
df, _ := golars.ReadCSV("data.csv")
df, _ = golars.ReadCSV("data.tsv", golars.WithSeparator('\t'))
df, _ = golars.ReadCSV("data.csv",
    golars.WithNullValues([]string{"NA", ""}),
    golars.WithCSVColumns([]string{"name", "age"}),
    golars.WithInferSchemaLength(1000),
    golars.WithSkipRows(1),
    golars.WithNRows(100),
)

// Read with context (cancellation support)
df, _ = golars.ReadCSVWithContext(ctx, "data.csv")

// Write
golars.WriteCSVFile(df, "output.csv")

// io.Reader / io.Writer integration
golars.WriteCSV(df, os.Stdout)
df, _ = golars.ReadCSVFromReader(reader)
JSON / NDJSON
df, _ := golars.ReadJSON("data.json")
df, _ = golars.ReadNDJSON("data.ndjson")

golars.WriteJSONFile(df, "output.json")
golars.WriteNDJSONFile(df, "output.ndjson")
Parquet
df, _ := golars.ReadParquet("data.parquet")
golars.WriteParquetFile(df, "output.parquet")

// With Snappy compression
golars.WriteParquetFile(df, "compressed.parquet", golars.WithParquetCompression("snappy"))
Excel
df, _ := golars.ReadExcel("data.xlsx")
golars.WriteExcelFile(df, "output.xlsx")
Database
import "database/sql"

db, _ := sql.Open("sqlite3", "data.db")
df, _ := golars.ReadSQL(db, "SELECT * FROM users WHERE age > ?", 25)

Data Types

Type Go Storage Constructor
Int8/16/32/64 intN NewIntNSeries
UInt8/16/32/64 uintN NewUIntNSeries
Float32/64 floatN NewFloatNSeries
Boolean bool NewBooleanSeries
String offset-based NewStringSeries
Date int32 (days since epoch) NewDateSeries
DateTime int64 (microseconds since epoch) NewDateTimeSeries
Time int64 (nanoseconds since midnight) NewTimeSeries
Duration int64 (microseconds) NewDurationSeries

Convenience constructors from time.Time:

dates := golars.NewDateSeriesFromTime("d", []time.Time{...})
timestamps := golars.NewDateTimeSeriesFromTime("ts", []time.Time{...})

Concurrency

  • All read operations on DataFrame and Series are safe for concurrent use
  • Mutations return new values (copy-on-write semantics)
  • Internal operations parallelize across GOMAXPROCS for large datasets
  • Context-aware operations support cancellation via context.Context

Benchmarks

Run benchmarks:

go test -bench=. -benchtime=3s ./bench/

Compare with Python Polars:

python bench/bench_polars.py

Requirements

  • Go 1.24+

Acknowledgments

Golars is inspired by Polars, the blazing-fast DataFrame library for Python and Rust created by Ritchie Vink. The API design, expression system, and lazy evaluation concepts draw directly from Polars' excellent architecture.

License

MIT — see LICENSE for details.

Documentation

Overview

Package golars provides a high-performance DataFrame library for Go, inspired by Python's Polars. It offers columnar data storage, a composable expression DSL, lazy evaluation with query optimization, SQL querying, and comprehensive I/O support for CSV, JSON, Parquet, and Excel formats.

Import

import "github.com/msjurset/golars"

All public types and functions are re-exported at the top level. Internal sub-packages use Go's internal/ convention and cannot be imported directly.

Key Design Principles

Immutability: DataFrames and Series are immutable after construction. Every transformation returns a new value, making concurrent reads safe without synchronization. The underlying array storage is shared where possible to minimize copies.

Expression DSL: Rather than embedding logic in method chains on DataFrames, golars uses a composable expression system. Expressions like Col, Lit, and When build up computation trees that can be evaluated against a DataFrame context, enabling reuse, composition, and optimization.

Lazy Evaluation: The Lazy function wraps a DataFrame in a LazyFrame that records operations as a logical plan. The plan is optimized (predicate pushdown, projection pruning) and only executed when [LazyFrame.Collect] is called.

Constructing DataFrames

Create typed Series and combine them into a DataFrame:

df, err := golars.NewDataFrame(
    golars.NewInt64Series("id", []int64{1, 2, 3}),
    golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie"}),
    golars.NewFloat64Series("score", []float64{88.5, 92.3, 76.1}),
)

Series with nullable values use explicit validity bitmaps:

s := golars.NewInt64SeriesWithValidity("val", []int64{10, 0, 30}, []bool{true, false, true})

Selecting, Filtering, and Sorting

selected, err := df.Select("name", "score")
dropped, err := df.Drop("id")
sorted, err := df.Sort("score", true) // descending

Filtering uses the expression system to produce a boolean mask:

ctx := &golars.ExprContext{DF: df}
mask, err := golars.Col("score").Gt(golars.Lit(80.0)).Evaluate(ctx)
filtered, err := df.Filter(mask)

Expressions

Expressions are composable building blocks for column-level computation:

// Arithmetic
golars.Col("price").Mul(golars.Lit(1.1)).Alias("with_tax")

// Comparison and logical
golars.Col("age").Gte(golars.Lit(18)).And(golars.Col("active").Eq(golars.Lit(true)))

// Aggregation
golars.Col("score").Mean()
golars.Col("revenue").Sum().Over("region") // window function

// Conditional
golars.When(golars.Col("score").Gt(golars.Lit(90))).
    Then(golars.Lit("A")).
    Otherwise(golars.Lit("B"))

GroupBy and Aggregation

grouped, err := df.GroupBy("department")
result, err := grouped.Agg(map[string]golars.AggFunc{
    "salary": golars.AggMean,
    "id":     golars.AggCount,
})

Available aggregation functions: AggSum, AggMean, AggMin, AggMax, AggCount, AggFirst, AggLast.

Joins

joined, err := left.Join(right, []string{"id"}, golars.InnerJoin)

Supported join types: InnerJoin, LeftJoin, RightJoin, FullJoin, SemiJoin, AntiJoin, CrossJoin.

Reshaping

pivoted, err := df.Pivot("name", "subject", "score")
melted, err := df.Unpivot([]string{"id"}, []string{"math", "english"})
transposed, err := df.Transpose()

Lazy Evaluation

Build a query plan and execute it in one optimized pass:

result, err := golars.Lazy(df).
    Filter(golars.Col("age").Gt(golars.Lit(25))).
    Sort("score", true).
    Head(10).
    Collect()

Inspect the logical plan with Explain or ExplainOptimized:

plan := golars.Lazy(df).Filter(expr).Sort("col", false).Explain()

I/O

Read and write CSV, JSON, NDJSON, Parquet, and Excel files. All readers accept file paths; most also offer io.Reader variants for streaming:

df, err := golars.ReadCSV("data.csv", golars.WithSeparator('\t'))
df, err := golars.ReadCSVFromReader(r, golars.WithHasHeader(false))
err = golars.WriteCSV(df, w)

df, err = golars.ReadParquet("data.parquet")
err = golars.WriteParquetFile(df, "out.parquet")

df, err = golars.ReadJSON("data.json")
df, err = golars.ReadExcel("data.xlsx")

CSV options: WithSeparator, WithNullValues, WithCSVColumns, WithInferSchemaLength, WithSkipRows, WithNRows, WithHasHeader.

SQL

Register DataFrames and query them with standard SQL syntax:

ctx := golars.NewSQLContext()
ctx.Register("users", df)
result, err := ctx.Execute("SELECT name, AVG(score) FROM users GROUP BY name")

Series Operations

Series provide rich per-column operations:

s.Sum()              // aggregation (returns float64, bool)
s.Mean()
s.RollingMean(3)     // rolling window (returns *Series)
s.CumSum()           // cumulative operations
s.Shift(1)           // shift values
s.Str().ToUpper()    // string namespace methods
s.Cast(golars.Float64)

Row-Level Operations

row := df.Row(0)             // map[string]any
rows := df.ToMaps()          // []map[string]any
s := df.MapRows("sum", fn)   // apply function per row
Example (CumulativeRolling)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewInt64Series("x", []int64{1, 2, 3, 4, 5}),
	)
	ctx := &golars.ExprContext{DF: df}

	// Cumulative sum
	cumSum, _ := golars.Col("x").Cum().Sum().Evaluate(ctx)
	for i := 0; i < cumSum.Len(); i++ {
		v, _ := cumSum.GetInt64(i)
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Printf("%d", v)
	}
	fmt.Println()

	// Rolling mean (window=3)
	rollMean, _ := golars.Col("x").Cast(golars.Float64).Rolling(3).Mean().Evaluate(ctx)
	for i := 0; i < rollMean.Len(); i++ {
		if i > 0 {
			fmt.Print(" ")
		}
		if rollMean.IsNull(i) {
			fmt.Print("null")
		} else {
			v, _ := rollMean.GetFloat64(i)
			fmt.Printf("%.1f", v)
		}
	}
	fmt.Println()
}
Output:
1 3 6 10 15
null null 2.0 3.0 4.0
Example (FirstLastExpr)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie"}),
	)
	ctx := &golars.ExprContext{DF: df}

	first, _ := golars.Col("name").First().Evaluate(ctx)
	last, _ := golars.Col("name").Last().Evaluate(ctx)

	v1, _ := first.GetString(0)
	v2, _ := last.GetString(0)
	fmt.Printf("first=%s last=%s\n", v1, v2)
}
Output:
first=Alice last=Charlie
Example (MathExpressions)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewFloat64Series("x", []float64{-2.5, 4.0, 9.0, 1.0}),
	)
	ctx := &golars.ExprContext{DF: df}

	// Abs
	abs, _ := golars.Col("x").Abs().Evaluate(ctx)
	for i := 0; i < abs.Len(); i++ {
		v, _ := abs.GetFloat64(i)
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Printf("%.1f", v)
	}
	fmt.Println()

	// Round
	df2, _ := golars.NewDataFrame(golars.NewFloat64Series("v", []float64{3.14159, 2.71828}))
	ctx2 := &golars.ExprContext{DF: df2}
	rounded, _ := golars.Col("v").Round(2).Evaluate(ctx2)
	for i := 0; i < rounded.Len(); i++ {
		v, _ := rounded.GetFloat64(i)
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Printf("%.2f", v)
	}
	fmt.Println()
}
Output:
2.5 4.0 9.0 1.0
3.14 2.72
Example (ShiftDiffPctChange)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewFloat64Series("price", []float64{100, 105, 103, 110}),
	)
	ctx := &golars.ExprContext{DF: df}

	// Percentage change
	pct, _ := golars.Col("price").PctChange(1).Evaluate(ctx)
	for i := 0; i < pct.Len(); i++ {
		if pct.IsNull(i) {
			fmt.Print("null ")
		} else {
			v, _ := pct.GetFloat64(i)
			fmt.Printf("%.4f ", v)
		}
	}
	fmt.Println()
}
Output:
null 0.0500 -0.0190 0.0680
Example (SortBy)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie"}),
		golars.NewInt64Series("score", []int64{90, 70, 80}),
	)
	ctx := &golars.ExprContext{DF: df}

	// Sort names by score (ascending)
	sorted, _ := golars.Col("name").SortBy(golars.Col("score"), false).Evaluate(ctx)
	for i := 0; i < sorted.Len(); i++ {
		v, _ := sorted.GetString(i)
		fmt.Println(v)
	}
}
Output:
Bob
Charlie
Alice
Example (StrCapitalize)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewStringSeries("word", []string{"hello world", "FOO BAR", "go lang"}),
	)
	ctx := &golars.ExprContext{DF: df}

	capped, _ := golars.Col("word").Str().Capitalize().Evaluate(ctx)
	for i := 0; i < capped.Len(); i++ {
		v, _ := capped.GetString(i)
		fmt.Println(v)
	}
}
Output:
Hello world
Foo bar
Go lang
Example (WindowOver)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewStringSeries("team", []string{"A", "A", "B", "B"}),
		golars.NewFloat64Series("score", []float64{10, 20, 30, 40}),
	)

	ctx := &golars.ExprContext{DF: df}
	teamMean, _ := golars.Col("score").Mean().Over("team").Evaluate(ctx)

	teamCol, _ := df.Column("team")
	for i := 0; i < teamMean.Len(); i++ {
		team, _ := teamCol.GetString(i)
		mean, _ := teamMean.GetFloat64(i)
		fmt.Printf("%s: %.1f\n", team, mean)
	}
}
Output:
A: 15.0
A: 15.0
B: 35.0
B: 35.0

Index

Examples

Constants

View Source
const (
	Null     = dtype.Null
	Boolean  = dtype.Boolean
	Int8     = dtype.Int8
	Int16    = dtype.Int16
	Int32    = dtype.Int32
	Int64    = dtype.Int64
	UInt8    = dtype.UInt8
	UInt16   = dtype.UInt16
	UInt32   = dtype.UInt32
	UInt64   = dtype.UInt64
	Float32  = dtype.Float32
	Float64  = dtype.Float64
	Decimal  = dtype.Decimal
	String   = dtype.String
	Binary   = dtype.Binary
	Date     = dtype.Date
	DateTime = dtype.DateTime
	Time     = dtype.Time
	Duration = dtype.Duration

	// Sort direction constants for Sort operations.
	Ascending  SortDirection = false
	Descending SortDirection = true
)

Type constants for all supported data types.

View Source
const (
	Nanoseconds  = dtype.Nanoseconds
	Microseconds = dtype.Microseconds
	Milliseconds = dtype.Milliseconds
)

TimeUnit constants.

View Source
const (
	AggSum   = dataframe.AggSum
	AggMean  = dataframe.AggMean
	AggMin   = dataframe.AggMin
	AggMax   = dataframe.AggMax
	AggCount = dataframe.AggCount
	AggFirst = dataframe.AggFirst
	AggLast  = dataframe.AggLast
)

Aggregation function constants.

View Source
const (
	InnerJoin = dataframe.InnerJoin
	LeftJoin  = dataframe.LeftJoin
	RightJoin = dataframe.RightJoin
	FullJoin  = dataframe.FullJoin
	SemiJoin  = dataframe.SemiJoin
	AntiJoin  = dataframe.AntiJoin
	CrossJoin = dataframe.CrossJoin
)

Join type constants.

Variables

View Source
var (
	// WithSeparator sets the CSV field separator character.
	WithSeparator = csvio.WithSeparator
	// WithNullValues sets the strings treated as null in CSV reading.
	WithNullValues = csvio.WithNullValues
	// WithCSVColumns restricts CSV reading to the named columns.
	WithCSVColumns = csvio.WithColumns
	// WithInferSchemaLength sets how many rows to scan for CSV type inference.
	WithInferSchemaLength = csvio.WithInferSchemaLength
	// WithSkipRows skips the first n rows of a CSV file.
	WithSkipRows = csvio.WithSkipRows
	// WithNRows limits CSV reading to at most n data rows.
	WithNRows = csvio.WithNRows
	// WithHasHeader controls whether the first CSV row is a header.
	WithHasHeader = csvio.WithHasHeader
)

CSV option re-exports for convenience.

View Source
var WithParquetCompression = parquetio.WithCompression

WithParquetCompression sets the compression codec for Parquet writing. Supported values: "none" (or "uncompressed"), "snappy".

Functions

func WriteCSV

func WriteCSV(df *DataFrame, w io.Writer, opts ...csvio.WriteOption) error

WriteCSV writes a DataFrame to a CSV file.

func WriteCSVFile

func WriteCSVFile(df *DataFrame, path string, opts ...csvio.WriteOption) error

WriteCSVFile writes a DataFrame to a CSV file at the given path.

func WriteExcel

func WriteExcel(df *DataFrame, w io.Writer) error

WriteExcel writes a DataFrame as an Excel .xlsx file to an io.Writer.

func WriteExcelFile

func WriteExcelFile(df *DataFrame, path string) error

WriteExcelFile writes a DataFrame to an Excel .xlsx file at the given path.

func WriteJSON

func WriteJSON(df *DataFrame, w io.Writer) error

WriteJSON writes a DataFrame as JSON to an io.Writer.

func WriteJSONFile

func WriteJSONFile(df *DataFrame, path string) error

WriteJSONFile writes a DataFrame as JSON to a file.

func WriteNDJSON

func WriteNDJSON(df *DataFrame, w io.Writer) error

WriteNDJSON writes a DataFrame as NDJSON to an io.Writer.

func WriteNDJSONFile

func WriteNDJSONFile(df *DataFrame, path string) error

WriteNDJSONFile writes a DataFrame as NDJSON to a file.

func WriteParquet

func WriteParquet(df *DataFrame, w io.Writer, opts ...WriteParquetOption) error

WriteParquet writes a DataFrame as Parquet to an io.Writer.

func WriteParquetFile

func WriteParquetFile(df *DataFrame, path string, opts ...WriteParquetOption) error

WriteParquetFile writes a DataFrame to a Parquet file at the given path.

Types

type AggFunc

type AggFunc = dataframe.AggFunc

AggFunc represents an aggregation function for use with GroupBy.

type CumNamespace

type CumNamespace = expr.CumNamespace

CumNamespace provides cumulative operations on expressions.

type DataFrame

type DataFrame = dataframe.DataFrame

DataFrame is an immutable collection of named, typed columns (Series).

func ConcatDataFrames

func ConcatDataFrames(dfs ...*DataFrame) (*DataFrame, error)

ConcatDataFrames vertically concatenates DataFrames that share the same schema.

Example
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df1, _ := golars.NewDataFrame(
		golars.NewInt64Series("x", []int64{1, 2}),
	)
	df2, _ := golars.NewDataFrame(
		golars.NewInt64Series("x", []int64{3, 4}),
	)

	combined, _ := golars.ConcatDataFrames(df1, df2)
	fmt.Println(combined.Height())
}
Output:
4

func ConcatDataFramesHorizontal

func ConcatDataFramesHorizontal(dfs ...*DataFrame) (*DataFrame, error)

ConcatDataFramesHorizontal concatenates DataFrames side by side.

func DataFrameFromSchema

func DataFrameFromSchema(schema *Schema, height int) *DataFrame

DataFrameFromSchema creates an empty DataFrame with the given schema and row count.

func GroupByAgg

func GroupByAgg(g *GroupByResult, exprs ...Expr) (*DataFrame, error)

GroupByAgg performs expression-based groupby aggregation.

func NewDataFrame

func NewDataFrame(columns ...*Series) (*DataFrame, error)

NewDataFrame creates a new DataFrame from the given Series columns. All columns must have the same length and unique names.

Example
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewInt64Series("age", []int64{25, 30, 35}),
		golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie"}),
	)
	fmt.Println(df.Height(), df.Width())
}
Output:
3 2
Example (Basic)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, err := golars.NewDataFrame(
		golars.NewInt64Series("id", []int64{1, 2, 3}),
		golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie"}),
		golars.NewFloat64Series("score", []float64{88.5, 92.3, 76.1}),
	)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("rows=%d cols=%d\n", df.Height(), df.Width())

	col, _ := df.Column("name")
	for i := 0; i < col.Len(); i++ {
		v, _ := col.GetString(i)
		fmt.Println(v)
	}
}
Output:
rows=3 cols=3
Alice
Bob
Charlie

func ReadCSV

func ReadCSV(path string, opts ...ReadCSVOption) (*DataFrame, error)

ReadCSV reads a CSV file into a DataFrame.

Example
package main

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/msjurset/golars"
)

func main() {
	// Write CSV data to a buffer, then read it back with options.
	csvData := "name|age|active\nAlice|25|true\nBob|30|false\n"
	reader := strings.NewReader(csvData)

	df, err := golars.ReadCSVFromReader(reader, golars.WithSeparator('|'))
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("rows=%d cols=%d\n", df.Height(), df.Width())

	// Round-trip to CSV with default separator.
	var buf bytes.Buffer
	_ = golars.WriteCSV(df, &buf)
	fmt.Print(buf.String())
}
Output:
rows=2 cols=3
name,age,active
Alice,25,true
Bob,30,false

func ReadCSVFromReader

func ReadCSVFromReader(r io.Reader, opts ...ReadCSVOption) (*DataFrame, error)

ReadCSVFromReader reads CSV data from an io.Reader into a DataFrame.

func ReadCSVWithContext

func ReadCSVWithContext(ctx context.Context, path string, opts ...ReadCSVOption) (*DataFrame, error)

ReadCSVWithContext reads a CSV file into a DataFrame with cancellation support.

func ReadExcel

func ReadExcel(path string) (*DataFrame, error)

ReadExcel reads an Excel .xlsx file into a DataFrame.

func ReadExcelFromReader

func ReadExcelFromReader(r io.ReaderAt, size int64) (*DataFrame, error)

ReadExcelFromReader reads an Excel file from an io.ReaderAt with the given size.

func ReadJSON

func ReadJSON(path string) (*DataFrame, error)

ReadJSON reads a JSON array-of-objects file into a DataFrame.

func ReadJSONFromReader

func ReadJSONFromReader(r io.Reader) (*DataFrame, error)

ReadJSONFromReader reads JSON data from an io.Reader into a DataFrame.

func ReadNDJSON

func ReadNDJSON(path string) (*DataFrame, error)

ReadNDJSON reads a newline-delimited JSON file into a DataFrame.

func ReadNDJSONFromReader

func ReadNDJSONFromReader(r io.Reader) (*DataFrame, error)

ReadNDJSONFromReader reads NDJSON from an io.Reader into a DataFrame.

func ReadParquet

func ReadParquet(path string) (*DataFrame, error)

ReadParquet reads a Parquet file into a DataFrame.

func ReadParquetFromReader

func ReadParquetFromReader(r io.ReadSeeker) (*DataFrame, error)

ReadParquetFromReader reads Parquet data from an io.ReadSeeker into a DataFrame.

func ReadSQL

func ReadSQL(db *sql.DB, query string, args ...any) (*DataFrame, error)

ReadSQL executes a SQL query against a database and returns the result as a DataFrame. The caller must import the appropriate database driver (e.g., _ "github.com/mattn/go-sqlite3").

func ReadSQLRows

func ReadSQLRows(rows *sql.Rows) (*DataFrame, error)

ReadSQLRows converts *sql.Rows to a DataFrame.

type DataType

type DataType = dtype.DataType

DataType represents the logical data type of a column.

type DtNamespace

type DtNamespace = expr.DtNamespace

DtNamespace provides temporal operations on expressions.

type Expr

type Expr = expr.Expr

Expr represents a composable expression that can be evaluated against a DataFrame.

func AllCols

func AllCols() Expr

AllCols returns an expression representing all columns.

func Col

func Col(name string) Expr

Col creates a column reference expression.

func Cols

func Cols(names ...string) []Expr

Cols creates multiple column reference expressions.

func Lit

func Lit(value any) Expr

Lit creates a literal value expression. Supports int, int64, float64, string, bool.

type ExprContext

type ExprContext = expr.Context

ExprContext holds the evaluation context for expressions.

type Field

type Field = dtype.Field

Field represents a named column with its data type.

type GroupByExpr

type GroupByExpr = dataframe.GroupByExpr

GroupByExpr is an interface for expression-based GroupBy aggregation.

type GroupByResult

type GroupByResult = dataframe.GroupByResult

GroupByResult holds the result of a GroupBy operation.

type JoinType

type JoinType = dataframe.JoinType

JoinType represents the type of join operation.

type LazyFrame

type LazyFrame = lazy.LazyFrame

LazyFrame represents a lazy computation over a DataFrame. Operations are recorded and only executed when Collect is called.

func Lazy

func Lazy(df *DataFrame) *LazyFrame

Lazy creates a LazyFrame from an eager DataFrame.

Example
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie", "Diana"}),
		golars.NewInt64Series("age", []int64{25, 30, 35, 40}),
		golars.NewFloat64Series("score", []float64{88.5, 92.3, 76.1, 95.0}),
	)

	result, _ := golars.Lazy(df).
		Filter(golars.Col("age").Gt(golars.Lit(25))).
		Sort("score", true). // descending
		Head(2).
		Collect()

	nameCol, _ := result.Column("name")
	scoreCol, _ := result.Column("score")
	for i := 0; i < result.Height(); i++ {
		name, _ := nameCol.GetString(i)
		score, _ := scoreCol.GetFloat64(i)
		fmt.Printf("%s: %.1f\n", name, score)
	}
}
Output:
Diana: 95.0
Bob: 92.3

func ScanCSV

func ScanCSV(path string, opts ...ReadCSVOption) *LazyFrame

ScanCSV creates a LazyFrame that defers reading a CSV file until Collect.

func ScanParquet

func ScanParquet(path string) *LazyFrame

ScanParquet creates a LazyFrame that defers reading a Parquet file until Collect.

type LazyGroupBy

type LazyGroupBy = lazy.LazyGroupBy

LazyGroupBy holds a deferred groupby operation on a LazyFrame.

type NameNamespace

type NameNamespace = expr.NameNamespace

NameNamespace provides operations on expression output names.

type ReadCSVOption

type ReadCSVOption = csvio.ReadOption

ReadCSVOption is a functional option for CSV reading.

type RollingNamespace

type RollingNamespace = expr.RollingNamespace

RollingNamespace provides rolling window operations on expressions.

type RowAccessor

type RowAccessor = dataframe.RowAccessor

RowAccessor provides typed access to a single row of a DataFrame. Use with the DataFrame.Rows() iterator.

type SQLContext

type SQLContext = sql.Context

SQLContext holds registered DataFrames that can be queried via SQL.

Example
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewInt64Series("id", []int64{1, 2, 3, 4}),
		golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie", "Diana"}),
		golars.NewFloat64Series("score", []float64{88.5, 92.3, 76.1, 95.0}),
	)

	ctx := golars.NewSQLContext()
	ctx.Register("students", df)

	result, _ := ctx.Execute("SELECT name, score FROM students WHERE score > 80 ORDER BY score DESC LIMIT 3")

	nameCol, _ := result.Column("name")
	scoreCol, _ := result.Column("score")
	for i := 0; i < result.Height(); i++ {
		name, _ := nameCol.GetString(i)
		score, _ := scoreCol.GetFloat64(i)
		fmt.Printf("%s: %.1f\n", name, score)
	}
}
Output:
Diana: 95.0
Bob: 92.3
Alice: 88.5

func NewSQLContext

func NewSQLContext() *SQLContext

NewSQLContext creates a new SQL context for querying DataFrames with SQL.

type Schema

type Schema = dtype.Schema

Schema represents an ordered collection of named, typed fields.

func NewSchema

func NewSchema(fields ...Field) *Schema

NewSchema creates a new Schema from the given fields.

type Series

type Series = series.Series

Series is a named, typed column of data.

Example (Aggregation)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	s := golars.NewFloat64Series("values", []float64{10, 20, 30, 40, 50})

	sum, _ := s.Sum()
	mean, _ := s.Mean()
	min, _ := s.Min()
	max, _ := s.Max()

	fmt.Printf("sum=%.0f mean=%.0f min=%.0f max=%.0f\n", sum, mean, min, max)
	fmt.Println("count:", s.Count())
	fmt.Println("nunique:", s.NUnique())
}
Output:
sum=150 mean=30 min=10 max=50
count: 5
nunique: 5
Example (NullHandling)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	s := golars.NewInt64SeriesWithValidity("data",
		[]int64{10, 0, 30, 0, 50},
		[]bool{true, false, true, false, true},
	)

	fmt.Println("nulls:", s.NullCount())
	fmt.Println("has_nulls:", s.HasNulls())

	// Drop nulls.
	clean := s.DropNulls()
	fmt.Println("after drop:", clean.Len())

	// Fill nulls.
	filled := s.FillNullInt64(0)
	for i := 0; i < filled.Len(); i++ {
		v, _ := filled.GetInt64(i)
		fmt.Print(v, " ")
	}
	fmt.Println()
}
Output:
nulls: 2
has_nulls: true
after drop: 3
10 0 30 0 50
Example (Rolling)
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	s := golars.NewFloat64Series("x", []float64{1, 2, 3, 4, 5})

	rm := s.RollingMean(3)
	for i := 0; i < rm.Len(); i++ {
		if rm.IsNull(i) {
			fmt.Println("null")
		} else {
			v, _ := rm.GetFloat64(i)
			fmt.Printf("%.1f\n", v)
		}
	}
}
Output:
null
null
2.0
3.0
4.0

func NewBooleanSeries

func NewBooleanSeries(name string, data []bool) *Series

NewBooleanSeries creates a new Series of boolean values.

func NewBooleanSeriesWithValidity

func NewBooleanSeriesWithValidity(name string, data []bool, valid []bool) *Series

NewBooleanSeriesWithValidity creates a Boolean Series with explicit null tracking.

func NewDateSeries

func NewDateSeries(name string, data []int32) *Series

NewDateSeries creates a new Series of Date values (days since Unix epoch as int32).

func NewDateSeriesFromTime

func NewDateSeriesFromTime(name string, times []time.Time) *Series

NewDateSeriesFromTime creates a Date Series from a slice of time.Time values.

func NewDateTimeSeries

func NewDateTimeSeries(name string, data []int64) *Series

NewDateTimeSeries creates a new Series of DateTime values (microseconds since epoch as int64).

func NewDateTimeSeriesFromTime

func NewDateTimeSeriesFromTime(name string, times []time.Time) *Series

NewDateTimeSeriesFromTime creates a DateTime Series from a slice of time.Time values.

func NewDurationSeries

func NewDurationSeries(name string, data []int64) *Series

NewDurationSeries creates a new Series of Duration values (microseconds as int64).

func NewFloat32Series

func NewFloat32Series(name string, data []float32) *Series

NewFloat32Series creates a new Series of float32 values.

func NewFloat64Series

func NewFloat64Series(name string, data []float64) *Series

NewFloat64Series creates a new Series of float64 values.

func NewFloat64SeriesWithValidity

func NewFloat64SeriesWithValidity(name string, data []float64, valid []bool) *Series

NewFloat64SeriesWithValidity creates a Float64 Series with explicit null tracking.

func NewInt8Series

func NewInt8Series(name string, data []int8) *Series

NewInt8Series creates a new Series of int8 values.

func NewInt16Series

func NewInt16Series(name string, data []int16) *Series

NewInt16Series creates a new Series of int16 values.

func NewInt32Series

func NewInt32Series(name string, data []int32) *Series

NewInt32Series creates a new Series of int32 values.

func NewInt64Series

func NewInt64Series(name string, data []int64) *Series

NewInt64Series creates a new Series of int64 values.

func NewInt64SeriesWithValidity

func NewInt64SeriesWithValidity(name string, data []int64, valid []bool) *Series

NewInt64SeriesWithValidity creates an Int64 Series with explicit null tracking. Positions where valid[i] is false are marked as null.

func NewStringSeries

func NewStringSeries(name string, data []string) *Series

NewStringSeries creates a new Series of string values.

func NewStringSeriesWithValidity

func NewStringSeriesWithValidity(name string, data []string, valid []bool) *Series

NewStringSeriesWithValidity creates a String Series with explicit null tracking.

func NewTimeSeries

func NewTimeSeries(name string, data []int64) *Series

NewTimeSeries creates a new Series of Time values (nanoseconds since midnight as int64).

func NewUInt8Series

func NewUInt8Series(name string, data []uint8) *Series

NewUInt8Series creates a new Series of uint8 values.

func NewUInt16Series

func NewUInt16Series(name string, data []uint16) *Series

NewUInt16Series creates a new Series of uint16 values.

func NewUInt32Series

func NewUInt32Series(name string, data []uint32) *Series

NewUInt32Series creates a new Series of uint32 values.

func NewUInt64Series

func NewUInt64Series(name string, data []uint64) *Series

NewUInt64Series creates a new Series of uint64 values.

type SortDirection

type SortDirection bool

SortDirection specifies ascending or descending sort order.

type StrNamespace

type StrNamespace = expr.StrNamespace

StrNamespace provides string operations on expressions.

type ThenBuilder

type ThenBuilder = expr.ThenBuilder

ThenBuilder is the intermediate builder after When().Then().

type TimeUnit

type TimeUnit = dtype.TimeUnit

TimeUnit represents the resolution of temporal types.

type WhenBuilder

type WhenBuilder = expr.WhenBuilder

WhenBuilder is the intermediate builder for When/Then/Otherwise chains.

func When

func When(condition Expr) *WhenBuilder

When starts a conditional expression chain.

Example
package main

import (
	"fmt"

	"github.com/msjurset/golars"
)

func main() {
	df, _ := golars.NewDataFrame(
		golars.NewStringSeries("name", []string{"Alice", "Bob", "Charlie"}),
		golars.NewFloat64Series("score", []float64{95.0, 72.0, 88.0}),
	)

	ctx := &golars.ExprContext{DF: df}
	grade, _ := golars.When(golars.Col("score").Gte(golars.Lit(90.0))).
		Then(golars.Lit("A")).
		Otherwise(golars.Lit("B")).
		Evaluate(ctx)

	for i := 0; i < grade.Len(); i++ {
		v, _ := grade.GetString(i)
		fmt.Println(v)
	}
}
Output:
A
B
B

type WriteParquetOption

type WriteParquetOption = parquetio.WriteOption

WriteParquetOption is a functional option for Parquet writing.

Directories

Path Synopsis
internal
array
Package array provides columnar storage arrays for the Golars DataFrame library.
Package array provides columnar storage arrays for the Golars DataFrame library.
bitmap
Package bitmap provides a compact bitset implementation for null tracking in columnar data structures.
Package bitmap provides a compact bitset implementation for null tracking in columnar data structures.
dataframe
Package dataframe provides the DataFrame type, an immutable collection of named, typed columns (Series) that supports relational-style operations.
Package dataframe provides the DataFrame type, an immutable collection of named, typed columns (Series) that supports relational-style operations.
dtype
Package dtype defines the type system for the Golars DataFrame library.
Package dtype defines the type system for the Golars DataFrame library.
expr
Package expr provides a composable expression DSL for evaluating column-level operations against a DataFrame context.
Package expr provides a composable expression DSL for evaluating column-level operations against a DataFrame context.
io/csv
Package csv provides CSV reading and writing for Golars DataFrames.
Package csv provides CSV reading and writing for Golars DataFrames.
io/database
Package database provides DataFrame I/O via Go's database/sql interface.
Package database provides DataFrame I/O via Go's database/sql interface.
io/excel
Package excel provides XLSX reading and writing for Golars DataFrames.
Package excel provides XLSX reading and writing for Golars DataFrames.
io/json
Package json provides JSON and NDJSON reading and writing for Golars DataFrames.
Package json provides JSON and NDJSON reading and writing for Golars DataFrames.
io/parquet
Package parquet provides a minimal Apache Parquet reader and writer for the golars DataFrame library.
Package parquet provides a minimal Apache Parquet reader and writer for the golars DataFrame library.
series
Package series provides the Series type, a named typed column of data.
Package series provides the Series type, a named typed column of data.
sql
Package sql provides a SQL query interface for golars DataFrames.
Package sql provides a SQL query interface for golars DataFrames.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL