Documentation
¶
Overview ¶
Example ¶
package main
import (
"fmt"
"github.com/go-dataframe/dataframe"
)
func main() {
df := dataframe.Must(dataframe.New(
dataframe.Col("city", []string{"Lyon", "Paris", "Nice", "Paris", "Lyon"}),
dataframe.Col("year", []int{2023, 2023, 2024, 2024, 2024}),
dataframe.Col("rain", []float64{830.5, 640.2, 760.1, 598.7, 810.0}),
))
fmt.Println(df.Head(3))
// df.groupby("city").mean(numeric_only=True)
g := dataframe.Must(df.GroupBy("city"))
fmt.Println(dataframe.Must(g.Mean()).ResetIndex(false))
// df.query("rain > 700 and year == 2024")
fmt.Println(dataframe.Must(df.Query("rain > 700 and year == 2024")))
}
Output: city year rain 0 Lyon 2023 830.5 1 Paris 2023 640.2 2 Nice 2024 760.1 city year rain 0 Lyon 2023.5 820.25 1 Nice 2024.0 760.10 2 Paris 2023.5 619.45 city year rain 2 Nice 2024 760.1 4 Lyon 2024 810.0
Index ¶
- Variables
- func Must[T any](v T, err error) T
- func Timestamp(s string, layout ...string) (time.Time, error)
- type AggSpec
- type CSVOption
- func CSVComment(c byte) CSVOption
- func CSVDTypes(dtypes map[string]DType) CSVOption
- func CSVDateFormat(layout string) CSVOption
- func CSVFalseValues(tokens ...string) CSVOption
- func CSVHeader(present bool) CSVOption
- func CSVIndexCol(name string) CSVOption
- func CSVIndexColumn(i int) CSVOption
- func CSVKeepDefaultNA(keep bool) CSVOption
- func CSVNAValues(tokens ...string) CSVOption
- func CSVNRows(n int) CSVOption
- func CSVNames(names ...string) CSVOption
- func CSVParseDates(names ...string) CSVOption
- func CSVQuote(c byte) CSVOption
- func CSVSeparator(c byte) CSVOption
- func CSVSkipBlankLines(skip bool) CSVOption
- func CSVSkipRows(n int) CSVOption
- func CSVTrueValues(tokens ...string) CSVOption
- func CSVUseCols(names ...string) CSVOption
- type CSVWriteOption
- type Column
- type ConcatOptions
- type DType
- type DataFrame
- func Concat(frames ...*DataFrame) (*DataFrame, error)
- func ConcatWith(opts ConcatOptions, frames ...*DataFrame) (*DataFrame, error)
- func FromArray(a *ndarray.Array, names ...string) (*DataFrame, error)
- func FromSeries(series ...*Series) (*DataFrame, error)
- func Merge(left, right *DataFrame, opts MergeOptions) (*DataFrame, error)
- func New(cols ...Column) (*DataFrame, error)
- func ReadCSV(r io.Reader, opts ...CSVOption) (*DataFrame, error)
- func ReadCSVFile(path string, opts ...CSVOption) (*DataFrame, error)
- func (df *DataFrame) Add(other any) (*DataFrame, error)
- func (df *DataFrame) Apply(name string, f func(Row) any) (*Series, error)
- func (df *DataFrame) ApplyColumns(f func(*Series) (*Series, error)) (*DataFrame, error)
- func (df *DataFrame) AsType(dtypes map[string]DType) (*DataFrame, error)
- func (df *DataFrame) AsTypeAll(dt DType) (*DataFrame, error)
- func (df *DataFrame) At(label any, column string) (any, error)
- func (df *DataFrame) BFill() *DataFrame
- func (df *DataFrame) Column(name string) (*Series, error)
- func (df *DataFrame) ColumnAt(i int) (*Series, error)
- func (df *DataFrame) Columns() []string
- func (df *DataFrame) Copy() *DataFrame
- func (df *DataFrame) Count() *Series
- func (df *DataFrame) DTypes() []DType
- func (df *DataFrame) DTypesSeries() *Series
- func (df *DataFrame) Describe() *DataFrame
- func (df *DataFrame) Display() map[string][]byte
- func (df *DataFrame) Div(other any) (*DataFrame, error)
- func (df *DataFrame) Drop(names ...string) (*DataFrame, error)
- func (df *DataFrame) DropNA(subset ...string) (*DataFrame, error)
- func (df *DataFrame) DropNAAll(subset ...string) (*DataFrame, error)
- func (df *DataFrame) DropNAColumns() *DataFrame
- func (df *DataFrame) DropNAThresh(thresh int, subset ...string) (*DataFrame, error)
- func (df *DataFrame) Eval(expr string, vars ...map[string]any) (*Series, error)
- func (df *DataFrame) FFill() *DataFrame
- func (df *DataFrame) FillNA(v any) *DataFrame
- func (df *DataFrame) FillNAColumns(values map[string]any) (*DataFrame, error)
- func (df *DataFrame) Filter(mask any) (*DataFrame, error)
- func (df *DataFrame) GroupBy(keys ...string) (*GroupBy, error)
- func (df *DataFrame) HTML() string
- func (df *DataFrame) Head(n int) *DataFrame
- func (df *DataFrame) IAt(i, j int) (any, error)
- func (df *DataFrame) Iloc(rows Selector, cols ...Selector) (*DataFrame, error)
- func (df *DataFrame) Index() *Index
- func (df *DataFrame) IsNA() *DataFrame
- func (df *DataFrame) Join(other *DataFrame, how, lsuffix, rsuffix string) (*DataFrame, error)
- func (df *DataFrame) Len() int
- func (df *DataFrame) Loc(rows Selector, cols ...string) (*DataFrame, error)
- func (df *DataFrame) Max() *Series
- func (df *DataFrame) Mean() *Series
- func (df *DataFrame) Median() *Series
- func (df *DataFrame) Melt(idVars, valueVars []string) (*DataFrame, error)
- func (df *DataFrame) Merge(right *DataFrame, opts MergeOptions) (*DataFrame, error)
- func (df *DataFrame) Min() *Series
- func (df *DataFrame) Mul(other any) (*DataFrame, error)
- func (df *DataFrame) NotNA() *DataFrame
- func (df *DataFrame) Pivot(index, columns, values string) (*DataFrame, error)
- func (df *DataFrame) PivotTable(index, columns, values, aggfunc string) (*DataFrame, error)
- func (df *DataFrame) Query(expr string, vars ...map[string]any) (*DataFrame, error)
- func (df *DataFrame) Reindex(labels any) (*DataFrame, error)
- func (df *DataFrame) ReindexColumns(names ...string) *DataFrame
- func (df *DataFrame) Rename(names map[string]string) *DataFrame
- func (df *DataFrame) Resample(rule string) (*Resampler, error)
- func (df *DataFrame) ResampleOn(column, rule string) (*Resampler, error)
- func (df *DataFrame) ResetIndex(drop bool) *DataFrame
- func (df *DataFrame) Round(decimals int) *DataFrame
- func (df *DataFrame) Select(names ...string) (*DataFrame, error)
- func (df *DataFrame) Series() []*Series
- func (df *DataFrame) SetColumns(names ...string) (*DataFrame, error)
- func (df *DataFrame) SetIndex(columns ...string) (*DataFrame, error)
- func (df *DataFrame) Shape() (rows, cols int)
- func (df *DataFrame) Shift(n int) *DataFrame
- func (df *DataFrame) SortIndex(ascending bool) *DataFrame
- func (df *DataFrame) SortValues(by []string, ascending ...bool) (*DataFrame, error)
- func (df *DataFrame) Stack() (*Series, error)
- func (df *DataFrame) Std() *Series
- func (df *DataFrame) String() string
- func (df *DataFrame) Sub(other any) (*DataFrame, error)
- func (df *DataFrame) Sum() *Series
- func (df *DataFrame) T() *DataFrame
- func (df *DataFrame) Tail(n int) *DataFrame
- func (df *DataFrame) ToPeriod(freq string) (*DataFrame, error)
- func (df *DataFrame) Unstack() (*DataFrame, error)
- func (df *DataFrame) Values() (*ndarray.Array, error)
- func (df *DataFrame) Var() *Series
- func (df *DataFrame) WithColumn(name string, data any) (*DataFrame, error)
- func (df *DataFrame) WithIndex(ix *Index) (*DataFrame, error)
- func (df *DataFrame) WriteCSV(w io.Writer, opts ...CSVWriteOption) error
- func (df *DataFrame) WriteCSVFile(path string, opts ...CSVWriteOption) error
- type DatetimeFields
- func (d DatetimeFields) Day() *Series
- func (d DatetimeFields) DayOfWeek() *Series
- func (d DatetimeFields) DayOfYear() *Series
- func (d DatetimeFields) Hour() *Series
- func (d DatetimeFields) Minute() *Series
- func (d DatetimeFields) Month() *Series
- func (d DatetimeFields) Normalize() *Series
- func (d DatetimeFields) Second() *Series
- func (d DatetimeFields) Strftime(layout string) *Series
- func (d DatetimeFields) Year() *Series
- type GroupBy
- func (g *GroupBy) Agg(specs ...AggSpec) (*DataFrame, error)
- func (g *GroupBy) Apply(f func(key any, group *DataFrame) (*DataFrame, error)) (*DataFrame, error)
- func (g *GroupBy) Count() (*DataFrame, error)
- func (g *GroupBy) First() (*DataFrame, error)
- func (g *GroupBy) Groups() ([]any, []*DataFrame)
- func (g *GroupBy) Last() (*DataFrame, error)
- func (g *GroupBy) Max() (*DataFrame, error)
- func (g *GroupBy) Mean() (*DataFrame, error)
- func (g *GroupBy) Median() (*DataFrame, error)
- func (g *GroupBy) Min() (*DataFrame, error)
- func (g *GroupBy) NGroups() int
- func (g *GroupBy) NUnique() (*DataFrame, error)
- func (g *GroupBy) Select(columns ...string) (*GroupBy, error)
- func (g *GroupBy) Size() *Series
- func (g *GroupBy) Std() (*DataFrame, error)
- func (g *GroupBy) String() string
- func (g *GroupBy) Sum() (*DataFrame, error)
- func (g *GroupBy) Transform(column, fn string) (*Series, error)
- func (g *GroupBy) Var() (*DataFrame, error)
- type Index
- func (ix *Index) DType() DType
- func (ix *Index) Display() map[string][]byte
- func (ix *Index) Get(label any) ([]int, error)
- func (ix *Index) IsRange() bool
- func (ix *Index) Label(i int) any
- func (ix *Index) Labels() []any
- func (ix *Index) Len() int
- func (ix *Index) Level(k int) (*Series, error)
- func (ix *Index) NLevels() int
- func (ix *Index) Name() string
- func (ix *Index) Names() []string
- func (ix *Index) Rename(names ...string) (*Index, error)
- func (ix *Index) String() string
- func (ix *Index) Values() (*ndarray.Array, error)
- type MergeOptions
- type Resampler
- func (r *Resampler) Agg(specs ...AggSpec) (*DataFrame, error)
- func (r *Resampler) Count() (*DataFrame, error)
- func (r *Resampler) First() (*DataFrame, error)
- func (r *Resampler) Last() (*DataFrame, error)
- func (r *Resampler) Max() (*DataFrame, error)
- func (r *Resampler) Mean() (*DataFrame, error)
- func (r *Resampler) Median() (*DataFrame, error)
- func (r *Resampler) Min() (*DataFrame, error)
- func (r *Resampler) Size() *Series
- func (r *Resampler) Std() (*DataFrame, error)
- func (r *Resampler) Sum() (*DataFrame, error)
- type Rolling
- type Row
- type Selector
- type Series
- func ConcatSeries(series ...*Series) (*Series, error)
- func NewCategorical(name string, codes []int32, categories []string) (*Series, error)
- func NewSeries(name string, data any) (*Series, error)
- func NewSeriesBitmap(name string, data any, validity []uint64) (*Series, error)
- func NewSeriesIndexed(name string, data any, index *Index) (*Series, error)
- func NewSeriesMasked(name string, data any, valid []bool) (*Series, error)
- func ToDatetime(s *Series, layout ...string) (*Series, error)
- func (s *Series) Abs() (*Series, error)
- func (s *Series) Add(other any) (*Series, error)
- func (s *Series) Agg(name string) (any, error)
- func (s *Series) And(o *Series) (*Series, error)
- func (s *Series) AsType(dt DType) (*Series, error)
- func (s *Series) At(i int) (any, error)
- func (s *Series) BFill() *Series
- func (s *Series) Between(lo, hi any) (*Series, error)
- func (s *Series) Categorical() (codes []int32, categories []string, err error)
- func (s *Series) Copy() *Series
- func (s *Series) Count() int
- func (s *Series) CumMax() (*Series, error)
- func (s *Series) CumMin() (*Series, error)
- func (s *Series) CumProd() (*Series, error)
- func (s *Series) CumSum() (*Series, error)
- func (s *Series) DType() DType
- func (s *Series) Diff(n int) (*Series, error)
- func (s *Series) Display() map[string][]byte
- func (s *Series) Div(other any) (*Series, error)
- func (s *Series) DropNA() *Series
- func (s *Series) Dt() (DatetimeFields, error)
- func (s *Series) Eq(other any) (*Series, error)
- func (s *Series) FFill() *Series
- func (s *Series) FillNA(v any) (*Series, error)
- func (s *Series) Filter(mask any) (*Series, error)
- func (s *Series) Floats() ([]float64, error)
- func (s *Series) FloorDiv(other any) (*Series, error)
- func (s *Series) Ge(other any) (*Series, error)
- func (s *Series) Get(label any) (any, error)
- func (s *Series) Gt(other any) (*Series, error)
- func (s *Series) HTML() string
- func (s *Series) Head(n int) *Series
- func (s *Series) Iloc(sel Selector) (*Series, error)
- func (s *Series) Index() *Index
- func (s *Series) IsIn(values ...any) (*Series, error)
- func (s *Series) IsNA() *Series
- func (s *Series) Items() []any
- func (s *Series) Le(other any) (*Series, error)
- func (s *Series) Len() int
- func (s *Series) Loc(sel Selector) (*Series, error)
- func (s *Series) Lt(other any) (*Series, error)
- func (s *Series) Map(f func(any) any) (*Series, error)
- func (s *Series) MapFloat(f func(float64) float64) (*Series, error)
- func (s *Series) Max() any
- func (s *Series) Mean() float64
- func (s *Series) Median() float64
- func (s *Series) Min() any
- func (s *Series) Mod(other any) (*Series, error)
- func (s *Series) Mul(other any) (*Series, error)
- func (s *Series) NUnique() int
- func (s *Series) Name() string
- func (s *Series) Ne(other any) (*Series, error)
- func (s *Series) Neg() (*Series, error)
- func (s *Series) Not() (*Series, error)
- func (s *Series) NotNA() *Series
- func (s *Series) Or(o *Series) (*Series, error)
- func (s *Series) PctChange(n int) (*Series, error)
- func (s *Series) Pow(other any) (*Series, error)
- func (s *Series) Prod() float64
- func (s *Series) Quantile(q float64) float64
- func (s *Series) Reindex(labels any) (*Series, error)
- func (s *Series) Rename(name string) *Series
- func (s *Series) ResetIndex() *Series
- func (s *Series) Rolling(window int) (*Rolling, error)
- func (s *Series) RollingMin(window, minPeriods int) (*Rolling, error)
- func (s *Series) Round(decimals int) *Series
- func (s *Series) SetIndex(ix *Index) (*Series, error)
- func (s *Series) Shift(n int) *Series
- func (s *Series) SortIndex(ascending bool) *Series
- func (s *Series) SortValues(ascending bool) *Series
- func (s *Series) Std() float64
- func (s *Series) String() string
- func (s *Series) Strings() []string
- func (s *Series) Sub(other any) (*Series, error)
- func (s *Series) Sum() float64
- func (s *Series) SumValue() any
- func (s *Series) Tail(n int) *Series
- func (s *Series) ToFrame() *DataFrame
- func (s *Series) ToPeriod(freq string) (*Series, error)
- func (s *Series) ToTimestamp() (*Series, error)
- func (s *Series) Unique() *Series
- func (s *Series) Unstack() (*DataFrame, error)
- func (s *Series) Valid() []bool
- func (s *Series) ValidityBitmap() []uint64
- func (s *Series) ValueCounts() *Series
- func (s *Series) Values() (*ndarray.Array, error)
- func (s *Series) Var() float64
- func (s *Series) VarDDOF(ddof int) float64
- func (s *Series) Xor(o *Series) (*Series, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( MaxRows = 60 MinRows = 10 MaxColumns = 20 )
Display limits, pandas' defaults: past MaxRows rows only the first and last MinRows/2 are shown; past MaxColumns columns only the first and last MaxColumns/2.
var ( // ErrDType reports an operation the column's dtype does not support. ErrDType = errors.New("dataframe: unsupported dtype") // ErrColumn reports a column name that is not in the frame. ErrColumn = errors.New("dataframe: no such column") // ErrLabel reports an index label that is not in the index. ErrLabel = errors.New("dataframe: label not in index") // ErrLength reports data whose length does not match the frame or index. ErrLength = errors.New("dataframe: length mismatch") // ErrIndex reports a position out of range. ErrIndex = errors.New("dataframe: position out of range") // ErrArgument reports an invalid argument. ErrArgument = errors.New("dataframe: invalid argument") // ErrQuery reports a query expression that does not parse or evaluate. ErrQuery = errors.New("dataframe: bad query") // ErrParse reports input (CSV, dates, ...) that does not parse. ErrParse = errors.New("dataframe: parse error") )
Errors returned by the package. They are wrapped with detail; test with errors.Is.
Functions ¶
Types ¶
type CSVOption ¶
type CSVOption func(*csvConfig)
CSVOption configures ReadCSV. The options mirror the read_csv parameters of pandas that notebooks use; each one names the pandas parameter it stands for.
func CSVComment ¶
CSVComment sets a comment character: the rest of a line from it is ignored, and a line starting with it is skipped (pandas' comment).
func CSVDTypes ¶
CSVDTypes sets the dtype of the named columns (pandas' dtype with a dict); a value that does not convert is an error. Names not in the file are ignored, as in pandas.
func CSVDateFormat ¶
CSVDateFormat sets the layout of the CSVParseDates columns: a Go layout or a strftime pattern such as "%d/%m/%Y" (pandas' date_format). By default ISO 8601 and a list of common layouts are accepted.
func CSVFalseValues ¶
CSVFalseValues adds tokens read as false, besides False, FALSE and false (pandas' false_values).
func CSVHeader ¶
CSVHeader says whether the first row (after the skipped rows) holds the column names. By default it does, unless CSVNames is given (pandas' header="infer"); CSVHeader(true) with CSVNames replaces the names the file has (header=0 with names), CSVHeader(false) reads every row as data (header=None), naming the columns "0", "1", ... when CSVNames is absent.
func CSVIndexCol ¶
CSVIndexCol makes the named column the index (pandas' index_col with a name).
func CSVIndexColumn ¶
CSVIndexColumn makes the column at position i (among the columns read) the index (pandas' index_col with an integer). An unnamed column gives an unnamed index, so a file written by WriteCSV with its index reads back with CSVIndexColumn(0).
func CSVKeepDefaultNA ¶
CSVKeepDefaultNA says whether pandas' default missing-value tokens ("", "NA", "NaN", "null", "None", "#N/A", ...) count as missing, true by default (pandas' keep_default_na).
func CSVNAValues ¶
CSVNAValues adds tokens read as missing values (pandas' na_values).
func CSVNames ¶
CSVNames sets the column names (pandas' names). A row with more fields than names gives its leading fields to the index, as in pandas.
func CSVParseDates ¶
CSVParseDates reads the named columns as Datetime (pandas' parse_dates with a list of names). A column holding a value that is not a date stays a String column, as pandas leaves it.
func CSVQuote ¶
CSVQuote sets the quote character, '"' by default (pandas' quotechar); 0 disables quoting (quoting=QUOTE_NONE).
func CSVSeparator ¶
CSVSeparator sets the field separator, ',' by default (pandas' sep).
func CSVSkipBlankLines ¶
CSVSkipBlankLines says whether empty and whitespace-only lines are skipped, true by default; otherwise they are rows of missing values (pandas' skip_blank_lines).
func CSVSkipRows ¶
CSVSkipRows skips the first n lines of the file, blank ones included, before the header (pandas' skiprows with an integer).
func CSVTrueValues ¶
CSVTrueValues adds tokens read as true, besides True, TRUE and true (pandas' true_values).
func CSVUseCols ¶
CSVUseCols keeps only the named columns, in file order (pandas' usecols).
type CSVWriteOption ¶
type CSVWriteOption func(*csvWriteConfig)
CSVWriteOption configures WriteCSV, mirroring pandas' to_csv parameters.
func CSVWriteHeader ¶
func CSVWriteHeader(write bool) CSVWriteOption
CSVWriteHeader says whether the column names are written, true by default (pandas' header).
func CSVWriteIndex ¶
func CSVWriteIndex(write bool) CSVWriteOption
CSVWriteIndex says whether the index is written as the first columns, true by default (pandas' index).
func CSVWriteLineTerminator ¶
func CSVWriteLineTerminator(s string) CSVWriteOption
CSVWriteLineTerminator sets the line end, "\n" by default (pandas' lineterminator, whose default is the platform's).
func CSVWriteNARep ¶
func CSVWriteNARep(s string) CSVWriteOption
CSVWriteNARep sets what a missing value is written as, "" by default (pandas' na_rep).
func CSVWriteSeparator ¶
func CSVWriteSeparator(c byte) CSVWriteOption
CSVWriteSeparator sets the field separator, ',' by default (pandas' sep).
type ConcatOptions ¶
type ConcatOptions struct {
// Axis 0 stacks frames vertically (rows after rows); 1 places them side
// by side, aligned on the index.
Axis int
// IgnoreIndex gives the result a range index (axis 0).
IgnoreIndex bool
// Inner keeps only the columns (axis 0) or labels (axis 1) every frame
// has, instead of their union.
Inner bool
}
ConcatOptions tunes Concat.
type DType ¶
type DType uint8
DType is the element type of a column. The first thirteen values are the go-ndarray dtypes, in go-ndarray's order, so a numeric column converts to and from an ndarray dtype by a plain conversion. The others are the column kinds an array cannot hold: text, instants, categories and periods.
const ( Float64 DType = DType(ndarray.Float64) Bool DType = DType(ndarray.Bool) Int8 DType = DType(ndarray.Int8) Int16 DType = DType(ndarray.Int16) Int32 DType = DType(ndarray.Int32) Int64 DType = DType(ndarray.Int64) Uint8 DType = DType(ndarray.Uint8) Uint16 DType = DType(ndarray.Uint16) Uint32 DType = DType(ndarray.Uint32) Uint64 DType = DType(ndarray.Uint64) Float32 DType = DType(ndarray.Float32) // Complex64 and Complex128 columns hold and show complex numbers; they // take part in arithmetic and sums but have no order. Complex64 DType = DType(ndarray.Complex64) Complex128 DType = DType(ndarray.Complex128) // String is a column of Go strings. String DType = 13 // Datetime is a column of instants, stored as int64 nanoseconds since the // Unix epoch, UTC. Datetime DType = 14 // Category is a column of int32 codes into a list of string categories. Category DType = 15 // Period is a column of calendar periods (a month, a quarter, ...), stored // as int64 ordinals counted from the period holding the Unix epoch. Period DType = 16 )
The column dtypes.
func ParseDType ¶
ParseDType returns the dtype with the given name. Besides the names String returns it accepts "int" (int64), "float" (float64), "str" and "object" (string), and "datetime64[ns]" (datetime).
type DataFrame ¶
type DataFrame struct {
// contains filtered or unexported fields
}
DataFrame is a table of named columns of equal length sharing one Index of row labels. Each column has its own dtype; numeric columns are go-ndarray arrays. A DataFrame is immutable: operations return new frames, sharing the columns they do not change.
func Concat ¶
Concat stacks frames vertically: the columns are the union of the frames' columns in order of appearance (a frame lacking one contributes missing values), and the indexes are concatenated (pandas' concat).
func ConcatWith ¶
func ConcatWith(opts ConcatOptions, frames ...*DataFrame) (*DataFrame, error)
ConcatWith is Concat with options.
func FromArray ¶
FromArray returns a frame of the columns of a two-dimensional array, named by names (or "0", "1", ... when names is empty).
func FromSeries ¶
FromSeries returns a frame of the series as columns, aligned on their indexes: when they differ, the rows are the union of the labels (in sorted order, as pandas builds a frame from a dict of series), and a series lacking a label gets a missing value there.
func Merge ¶
func Merge(left, right *DataFrame, opts MergeOptions) (*DataFrame, error)
Merge joins two frames on key columns, as pandas' merge. Rows come in pandas' order: inner and left joins follow the left frame, a right join the right frame, an outer join the sorted keys. Missing keys match each other, as in pandas. The result has a range index.
Example ¶
package main
import (
"fmt"
"github.com/go-dataframe/dataframe"
)
func main() {
left := dataframe.Must(dataframe.New(
dataframe.Col("id", []int{1, 2, 3}),
dataframe.Col("name", []string{"ada", "bob", "cy"}),
))
right := dataframe.Must(dataframe.New(
dataframe.Col("id", []int{3, 1, 1}),
dataframe.Col("score", []float64{7.5, 9, 8}),
))
// pd.merge(left, right, on="id", how="left")
fmt.Println(dataframe.Must(dataframe.Merge(left, right, dataframe.MergeOptions{On: []string{"id"}, How: "left"})))
}
Output: id name score 0 1 ada 9.0 1 1 ada 8.0 2 2 bob NaN 3 3 cy 7.5
func New ¶
New returns a frame of the given columns, in order, with a range index.
df, err := dataframe.New(
dataframe.Col("city", []string{"Lyon", "Paris"}),
dataframe.Col("pop", []int{522_000, 2_103_000}),
)
func ReadCSV ¶
ReadCSV reads a CSV table, as pandas' read_csv does: the first row names the columns, each column's dtype is inferred from all its values (int64, uint64, float64, bool or string; see CSVParseDates and CSVDTypes for the others), pandas' default missing-value tokens are missing, and the index is a range unless CSVIndexCol says otherwise.
Fields follow RFC 4180: quoted fields may hold separators, doubled quotes and line breaks; lines end with LF, CRLF or CR; a UTF-8 byte order mark is skipped. A row with fewer fields than the header gets missing values; a row with more is an error naming its line, except the first data row, whose extra leading fields become the index (as in pandas).
An integer or bool column with missing values keeps its dtype, the missing rows marked in its validity, where pandas would make it float64 or object. String values share one buffer holding the input: a string kept keeps the whole input alive (see docs/design.md).
func ReadCSVFile ¶
ReadCSVFile reads a CSV file as ReadCSV reads one.
func (*DataFrame) Add ¶
Add returns df + other, other a scalar or a frame (aligned on labels and column names).
func (*DataFrame) Apply ¶
Apply calls f on every row and returns a series of the results, indexed like the frame, with an inferred dtype (pandas' df.apply(f, axis=1)).
func (*DataFrame) ApplyColumns ¶
ApplyColumns calls f on every column and returns the frame of the results, which must keep the frame's length.
func (*DataFrame) AsType ¶
AsType returns the frame with the named columns converted, as Series.AsType converts.
func (*DataFrame) DTypesSeries ¶
DTypesSeries returns the dtypes as a string series indexed by column name, the way pandas shows df.dtypes.
func (*DataFrame) Describe ¶
Describe returns summary statistics of the numeric columns, as pandas' describe(): count, mean, std, min, 25%, 50%, 75%, max. A frame without numeric columns is described as text: count, unique, top, freq.
func (*DataFrame) Display ¶
Display returns the frame for a notebook: text/plain as String, text/html as HTML.
func (*DataFrame) DropNA ¶
DropNA returns the rows with no missing value in the subset columns (all columns when none are named): pandas' dropna().
func (*DataFrame) DropNAAll ¶
DropNAAll returns the rows that have at least one value present in the subset columns: pandas' dropna(how="all").
func (*DataFrame) DropNAColumns ¶
DropNAColumns returns the frame without the columns that have a missing value: pandas' dropna(axis=1).
func (*DataFrame) DropNAThresh ¶
DropNAThresh keeps the rows with at least thresh values present in the subset columns: pandas' dropna(thresh=thresh).
func (*DataFrame) Eval ¶
Eval evaluates an expression of the Query language to a series, one value per row (pandas' eval).
func (*DataFrame) FillNA ¶
FillNA returns the frame with missing values replaced by v in every column whose dtype v converts to; the other columns are left as they are.
func (*DataFrame) FillNAColumns ¶
FillNAColumns fills missing values column by column, from a map of column name to value.
func (*DataFrame) Filter ¶
Filter returns the rows where mask is true (pandas' df[mask]). The mask is a bool series (aligned by label) or a []bool.
func (*DataFrame) IAt ¶
IAt returns the value at row position i and column position j (pandas' df.iat); negative positions count from the end.
func (*DataFrame) Iloc ¶
Iloc selects rows by position, and optionally columns by position:
df.Iloc(dataframe.Slice(0, 5)) // df.iloc[0:5] df.Iloc(dataframe.Pos(0, 2), dataframe.Slice(1, 3)) // df.iloc[[0, 2], 1:3] df.Iloc(dataframe.Mask(m)) // df.iloc[m]
func (*DataFrame) Join ¶
Join joins another frame on the index labels (pandas' join): how is "left" (the default when empty), "right", "inner" or "outer"; column names both frames have take the suffixes.
func (*DataFrame) Loc ¶
Loc selects rows by label (or mask), and optionally columns by name:
df.Loc(dataframe.Labels("a", "c")) // df.loc[["a", "c"]]
df.Loc(dataframe.LabelRange("2020-01", "2020-03")) // df.loc["2020-01":"2020-03"]
df.Loc(dataframe.Mask(m), "x", "y") // df.loc[m, ["x", "y"]]
func (*DataFrame) Melt ¶
Melt reshapes wide data to long (pandas' melt): the id columns repeat, and each value column becomes rows of ("variable", "value") pairs. With no value columns named, every non-id column is one.
func (*DataFrame) Merge ¶
func (df *DataFrame) Merge(right *DataFrame, opts MergeOptions) (*DataFrame, error)
Merge joins the frame with another, as the Merge function.
func (*DataFrame) Pivot ¶
Pivot reshapes long data to wide: rows from the index column, columns from the columns column, cells from the values column (pandas' pivot). A repeated (index, columns) pair is an error; use PivotTable to aggregate.
func (*DataFrame) PivotTable ¶
PivotTable is Pivot with repeated pairs aggregated by aggfunc ("mean", pandas' default, "sum", "count", ...).
func (*DataFrame) Query ¶
Query returns the rows for which a boolean expression holds (pandas' query). The expression language is small and is parsed, never executed as code:
- column names, bare (price) or in backquotes (`unit price`); "index" names the index when no column is called that;
- @name, a variable from vars;
- numbers, 'strings' or "strings", true/false (or True/False), lists [1, 2, 3];
- arithmetic + - * / // % ** and unary minus;
- comparisons == != < <= > >=, chained as in 1 < x < 5;
- x in [...] and x not in [...];
- and, or, not (also &, |, ~), and parentheses;
- the functions isna(x), notna(x) and abs(x), and the methods x.isna() and x.notna().
Comparisons against a missing value are false (!= is true), as for NaN in pandas.
func (*DataFrame) Reindex ¶
Reindex returns the frame with rows for the given labels (an *Index or anything NewIndex accepts), in that order; a label the frame lacks gives a row of missing values.
func (*DataFrame) ReindexColumns ¶
ReindexColumns returns the frame with the given columns in that order; a name the frame lacks gives an all-missing float64 column.
func (*DataFrame) Rename ¶
Rename returns the frame with columns renamed by the map; names it does not mention are kept, and an unknown key is ignored, as in pandas.
func (*DataFrame) Resample ¶
Resample bins the rows of a frame with a datetime index by time (pandas' resample): fixed bins (e.g. "15min", "h", "D", "7D") start at midnight of the first day and are labelled by their start; calendar bins ("W", "ME", "QE", "YE", "MS", "QS", "YS") hold whole weeks, months, quarters or years. Every bin from the first to the last is in the result, empty ones included (their sum is 0, their mean missing).
Example ¶
package main
import (
"fmt"
"github.com/go-dataframe/dataframe"
)
func main() {
ts := dataframe.Must(dataframe.ToDatetime(dataframe.Must(dataframe.NewSeries("when",
[]string{"2024-01-01 09:00", "2024-01-01 17:30", "2024-01-03 08:00"}))))
df := dataframe.Must(dataframe.New(dataframe.Col("when", ts), dataframe.Col("kwh", []float64{1.5, 2, 4})))
df = dataframe.Must(df.SetIndex("when"))
// df.resample("D").sum()
fmt.Println(dataframe.Must(dataframe.Must(df.Resample("D")).Sum()).ResetIndex(false))
}
Output: when kwh 0 2024-01-01 3.5 1 2024-01-02 0.0 2 2024-01-03 4.0
func (*DataFrame) ResampleOn ¶
ResampleOn bins by a datetime column instead of the index.
func (*DataFrame) ResetIndex ¶
ResetIndex returns the frame with a range index. Unless drop is set, the old index levels become the first columns, named after the levels ("index" for an unnamed one-level index, "level_0", "level_1", ... for unnamed levels of a multi-level one).
func (*DataFrame) SetColumns ¶
SetColumns returns the frame with all column names replaced.
func (*DataFrame) SetIndex ¶
SetIndex returns the frame indexed by the named columns (several make a multi-level index), which leave the columns, as pandas' set_index does by default.
func (*DataFrame) SortIndex ¶
SortIndex returns the frame sorted by its index labels (every level, the first the most significant).
func (*DataFrame) SortValues ¶
SortValues returns the frame sorted by the given columns, the first the most significant. ascending gives the direction: none means all ascending, one value applies to every key, otherwise one per key. The sort is stable and puts missing values last, like pandas' sort_values(kind="stable").
func (*DataFrame) Stack ¶
Stack returns the frame as a series with one value per (row, column) pair, the column name becoming the last index level; missing values are dropped (pandas' stack).
func (*DataFrame) String ¶
String formats the frame as pandas prints it: every value cell gets a leading space (a negative number's sign takes its place), cells are right-aligned under right-aligned column names, columns are joined by one space, and the index is left-aligned.
func (*DataFrame) T ¶
T returns the transpose: one column per row, named after the row's label, and one row per column, labelled by its name. The values take the columns' common dtype, or become strings when they have none (pandas makes an object column there).
func (*DataFrame) ToPeriod ¶
ToPeriod converts the frame's datetime index to periods (pandas' to_period).
func (*DataFrame) Unstack ¶
Unstack pivots the last index level into columns. With one value column the new columns are named by the labels; with several, column_label.
func (*DataFrame) Values ¶
Values returns the frame as a two-dimensional array, rows by columns. All columns must be numeric or bool; the dtype is the one NumPy would pick for them all (an int column with missing values counts as float64), and missing values are NaN.
func (*DataFrame) WithColumn ¶
WithColumn returns the frame with a column set: replaced in place if the name exists, appended otherwise. data is a *Series (aligned on the frame's index by label, as pandas assigns one), a slice or array of the frame's length, or a scalar repeated on every row.
func (*DataFrame) WriteCSV ¶
func (df *DataFrame) WriteCSV(w io.Writer, opts ...CSVWriteOption) error
WriteCSV writes the frame as CSV, as pandas' to_csv does by default: a header row, the index as the first column(s) (headed by its name, empty when unnamed), missing values as empty fields, floats as Python prints them ("1.0", "0.1", "1e-05", "1e+16"), bools as True and False, instants as dates when all are at midnight and otherwise with the fraction of a second the column needs, and quotes only around fields holding the separator, a quote or a line break (RFC 4180).
func (*DataFrame) WriteCSVFile ¶
func (df *DataFrame) WriteCSVFile(path string, opts ...CSVWriteOption) error
WriteCSVFile writes the frame to a file as WriteCSV writes it.
type DatetimeFields ¶
type DatetimeFields struct {
// contains filtered or unexported fields
}
DatetimeFields reads parts of a datetime series, as pandas' .dt accessor.
func (DatetimeFields) DayOfWeek ¶
func (d DatetimeFields) DayOfWeek() *Series
DayOfWeek returns the day of the week, Monday 0 to Sunday 6, as pandas.
func (DatetimeFields) DayOfYear ¶
func (d DatetimeFields) DayOfYear() *Series
DayOfYear returns the day of the year, from 1.
func (DatetimeFields) Month ¶
func (d DatetimeFields) Month() *Series
Month returns the month, 1 to 12.
func (DatetimeFields) Normalize ¶
func (d DatetimeFields) Normalize() *Series
Normalize returns each instant at midnight of its day.
func (DatetimeFields) Strftime ¶
func (d DatetimeFields) Strftime(layout string) *Series
Strftime formats each instant with a Go layout or a strftime pattern.
func (DatetimeFields) Year ¶
func (d DatetimeFields) Year() *Series
Year returns the year of each instant.
type GroupBy ¶
type GroupBy struct {
// contains filtered or unexported fields
}
GroupBy is a frame split into groups of rows by the values of key columns, ready to aggregate. Groups come out sorted by key, and rows whose key is missing are left out, as pandas' groupby does by default (sort=True, dropna=True). Grouping is hash based: one pass to code the keys, then one pass per aggregation.
func (*GroupBy) Agg ¶
Agg applies several aggregations. A column with one function keeps its name; with several, each result is named column_func (pandas makes a two-level column index there; this package keeps column names flat).
func (*GroupBy) Apply ¶
Apply calls f on each group's rows and concatenates the frames it returns, in group order.
func (*GroupBy) Groups ¶
Groups returns each group's key (a Go value, or a []any tuple for several keys) and its rows as a frame, in group order.
func (*GroupBy) Select ¶
Select restricts the aggregated columns to the named ones (pandas' df.groupby(k)[cols]).
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index holds the row labels of a Series or DataFrame. It is a range (0, 1, 2, ... as a frame gets by default; nothing is stored), one column of labels of any dtype (numbers, strings, instants: a datetime index), or several such columns, one per level, for a multi-level index such as a group-by over several keys produces. An Index is immutable.
func NewRangeIndex ¶
NewRangeIndex returns the index 0, 1, ..., n-1.
func (*Index) Get ¶
Get returns the positions of a label (a []any tuple, or a prefix of one, for a multi-level index). A missing label is an ErrLabel.
func (*Index) Label ¶
Label returns the label at position i: a Go value for a one-level index (nil when missing), a []any tuple for a multi-level one.
type MergeOptions ¶
type MergeOptions struct {
// How is "inner" (the default), "left", "right", "outer" or "cross".
How string
// On names key columns both frames have. When On, LeftOn and RightOn
// are all empty, the keys are the columns the frames have in common.
On []string
// LeftOn and RightOn name key columns that differ between the frames,
// pairwise.
LeftOn, RightOn []string
// Suffixes are appended to non-key columns both frames have; the
// default is "_x" and "_y".
Suffixes [2]string
// Indicator adds a column "_merge" saying where each row came from:
// "both", "left_only" or "right_only".
Indicator bool
}
MergeOptions describes a database-style join of two frames.
type Resampler ¶
type Resampler struct {
// contains filtered or unexported fields
}
Resampler is a frame's rows binned by time, ready to aggregate.
type Rolling ¶
type Rolling struct {
// contains filtered or unexported fields
}
Rolling is a moving window over a series, ready to aggregate.
type Row ¶
type Row struct {
// contains filtered or unexported fields
}
Row is one row of a frame, as Apply hands it to a function.
func (Row) Float ¶
Float returns the value in the named column as a float64 (NaN when it is missing or not a number).
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
Selector picks rows (or, for Iloc, columns): all of them, a range or list of positions, a list or inclusive range of labels, or a boolean mask. Build one with All, Slice, Pos, Labels, LabelRange or Mask.
func LabelRange ¶
LabelRange selects from label from to label to, both included, as pandas' loc[from:to]. A nil bound is open. A label that is absent is placed by binary search, which needs a sorted index.
func Labels ¶
Labels selects the rows with the given labels, in that order (a []any tuple, or a prefix of one, for a multi-level index).
func Mask ¶
Mask selects the rows where a mask is true: a []bool of the right length, or a bool *Series, which is aligned on the index by label when its index differs (it must then hold every label; missing values count as false).
type Series ¶
type Series struct {
// contains filtered or unexported fields
}
Series is one named, labelled column: values of one dtype, with missing values marked in a validity bitmap, and an Index of row labels. A Series is immutable: every operation returns a new one, sharing storage where it can.
func ConcatSeries ¶
ConcatSeries stacks series end to end.
func NewCategorical ¶
NewCategorical returns a category series from codes into categories: code k stands for categories[k], and a negative code marks a missing value. A code past the last category is an error.
func NewSeries ¶
NewSeries returns a series over a copy of data, with a range index. data is a slice of any Go number type, []bool, []string, []time.Time, []any (nil is missing; the dtype is inferred), or a one-dimensional *ndarray.Array, which is shared rather than copied when it is contiguous.
func NewSeriesBitmap ¶
NewSeriesBitmap is NewSeries with a packed validity bitmap: bit i%64 of word i/64 set means value i is present; a clear bit marks it missing (its slot in data is kept but ignored). This is the Arrow validity bit order read as little-endian 64-bit words. A nil bitmap means every value is present; otherwise it must hold at least one bit per value, and the bits past the last value are ignored. The bitmap is copied.
func NewSeriesIndexed ¶
NewSeriesIndexed is NewSeries with the given row labels.
func NewSeriesMasked ¶
NewSeriesMasked is NewSeries with a validity mask: valid[i] false marks value i missing (its slot in data is kept but ignored). valid must be as long as data.
func ToDatetime ¶
ToDatetime converts a series to datetime. A string series is parsed (ISO 8601 and common layouts, or the given layout: a Go layout or a strftime pattern such as "%d/%m/%Y"); a string that does not parse is an error. An integer series is read as nanoseconds since the epoch; a datetime series is returned as is.
func (*Series) Add ¶
Add returns s + other: other is a scalar or a series (aligned by label). Types promote as NumPy promotes them; strings concatenate.
func (*Series) Agg ¶
Agg reduces the series by name: "sum", "mean", "std", "var", "min", "max", "count", "median", "prod", "nunique", "first", "last" or "size".
func (*Series) At ¶
At returns the value at position i (negative counts from the end), nil when missing.
func (*Series) Categorical ¶
Categorical returns a category series' codes (-1 where a value is missing) and its categories. Any other dtype is an ErrDType.
func (*Series) Dt ¶
func (s *Series) Dt() (DatetimeFields, error)
Dt returns the datetime accessor; it fails on a series of another dtype.
func (*Series) FFill ¶
FFill returns the series with each missing value replaced by the last present one before it (pandas' ffill); leading missing values stay.
func (*Series) FillNA ¶
FillNA returns the series with missing values replaced by v, which must convert to the series' dtype (an int fills a float series; a float fills an int series only when it is integral).
func (*Series) Floats ¶
Floats returns the values as float64s, missing values as NaN. It accepts every real number dtype and bool.
func (*Series) Get ¶
Get returns the value with row label label. A label held by several rows gives the first.
func (*Series) Head ¶
Head returns the first n values (all of them if there are fewer; with a negative n, all but the last -n).
func (*Series) IsIn ¶
IsIn returns whether each value is one of values (pandas' isin). A missing value is never in.
func (*Series) IsNA ¶
IsNA returns a bool series, true where a value is missing (NaN counts as missing in a float series, as in pandas).
func (*Series) Map ¶
Map applies f to every value (nil for a missing one) and builds a series of the results, whose dtype is inferred as for NewSeries([]any); a nil result is missing.
func (*Series) MapFloat ¶
MapFloat applies f to every present value of a real series, giving a float64 series; missing values stay missing.
func (*Series) Mean ¶
Mean returns the mean of the present values (NaN if there are none or the dtype is not real).
func (*Series) Min ¶
Min returns the smallest present value (a Go value of the series' kind; time.Time for datetimes), nil when there is none.
func (*Series) PctChange ¶
PctChange returns the relative change from n rows before (pandas' pct_change, without filling missing values).
func (*Series) Reindex ¶
Reindex returns the series with values for the given labels, as DataFrame.Reindex.
func (*Series) ResetIndex ¶
ResetIndex returns the series with a range index.
func (*Series) Rolling ¶
Rolling returns a window of the given number of rows ending at each row; a row gets a value once the window holds window present values (pandas' default min_periods).
func (*Series) RollingMin ¶
RollingMin is Rolling with min_periods: the least number of present values a window needs to give a value.
func (*Series) Round ¶
Round returns the series rounded to the given number of decimals (half to even, as NumPy rounds). Integer and non-numeric series are unchanged.
func (*Series) Shift ¶
Shift returns the series moved down by n rows (up for a negative n), the vacated rows missing (pandas' shift).
func (*Series) SortValues ¶
SortValues returns the series sorted by value, stably, missing values last.
func (*Series) Sum ¶
Sum returns the sum of the present values as a float64 (NaN for a dtype without a sum). SumValue keeps the exact type.
func (*Series) SumValue ¶
SumValue returns the sum in the dtype pandas gives it: int64 for signed integers and bools, uint64 for unsigned ones, float64, or complex128; nil for a dtype without a sum.
func (*Series) ToPeriod ¶
ToPeriod converts a datetime series to periods of a frequency: "Y", "Q", "M", "W", "D", "h", "min" or "s" (pandas' dt.to_period).
func (*Series) ToTimestamp ¶
ToTimestamp converts a period series to the instants its periods start.
func (*Series) Unstack ¶
Unstack pivots the last index level of a multi-level series into columns, one per distinct label (sorted), rows being the distinct remaining labels (sorted); a missing combination is a missing value (pandas' unstack).
func (*Series) Valid ¶
Valid returns, for each value, whether it is present (the negation of IsNA, as a plain slice).
func (*Series) ValidityBitmap ¶
ValidityBitmap returns a copy of the series' validity bitmap, in the layout NewSeriesBitmap takes, or nil when no value is masked. NaN in a float series is an in-band missing value, not a cleared bit: test floats for NaN as well.
func (*Series) ValueCounts ¶
ValueCounts returns how often each distinct value occurs, most frequent first (ties in order of first appearance), indexed by the values and named "count", as pandas' value_counts.
func (*Series) Values ¶
Values returns the values as a go-ndarray array of the series' dtype; a datetime or period series gives its int64 storage. A series that owns its storage hands it out without copying. Missing values are left as they are stored (NaN for floats, zero otherwise); IsNA tells them apart. A string or category series has no array form.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package arrowio reads and writes frames as Apache Arrow data: the Arrow IPC file format (Feather v2) and the Arrow IPC streaming format, and converts frames to and from Arrow record batches and tables; package parquetio builds Parquet on these conversions.
|
Package arrowio reads and writes frames as Apache Arrow data: the Arrow IPC file format (Feather v2) and the Arrow IPC streaming format, and converts frames to and from Arrow record batches and tables; package parquetio builds Parquet on these conversions. |
|
Package dfplot draws DataFrames and Series, in the manner of the plot helpers of pandas (df.plot.line, df.plot.bar, ...) that notebooks lean on.
|
Package dfplot draws DataFrames and Series, in the manner of the plot helpers of pandas (df.plot.line, df.plot.bar, ...) that notebooks lean on. |
|
Package parquetio reads and writes frames as Parquet files, through github.com/apache/arrow-go's pure-Go Parquet implementation (no cgo).
|
Package parquetio reads and writes frames as Parquet files, through github.com/apache/arrow-go's pure-Go Parquet implementation (no cgo). |