stat

package
v0.9.33 Latest Latest
Warning

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

Go to latest
Published: May 13, 2023 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SERIES_TYPE_INVAILD = reflect.Invalid // 无效类型
	SERIES_TYPE_BOOL    = reflect.Bool    // 布尔类型
	SERIES_TYPE_INT32   = reflect.Int32   // int64
	SERIES_TYPE_INT64   = reflect.Int64   // int64
	SERIES_TYPE_FLOAT32 = reflect.Float32 // float32
	SERIES_TYPE_FLOAT64 = reflect.Float64 // float64
	SERIES_TYPE_DTYPE   = SERIES_TYPE_FLOAT64
	SERIES_TYPE_STRING  = reflect.String // string
)

Supported Series Types

View Source
const (
	Nil2Bool              = false      // 空指针转bool
	BoolNaN               = false      // bool 无效值
	True2Bool             = true       // true转bool
	False2Bool            = false      // false 转bool
	True2Float32  float32 = float32(1) // true转float32
	False2Float32 float32 = float32(0) // false转float32

	StringBad2Bool   = false // 字符串解析bool异常
	StringTrue2Bool  = true  // 字符串true转bool
	StringFalse2Bool = false // 字符串false转bool
)
View Source
const (
	MaxFloat32                  = float32(math.MaxFloat32)             // float32最大值
	MinFloat32                  = float32(math.SmallestNonzeroFloat32) // float32最小值
	StringTrue2Float32  float32 = float32(1)                           // 字符串true转float32
	StringFalse2Float32 float32 = float32(0)                           // 字符串false转float32
)
View Source
const (
	MaxFloat64          float64 = float64(math.MaxFloat64)             // float64最大值
	MinFloat64          float64 = float64(math.SmallestNonzeroFloat64) // float64最小值
	True2Float64        float64 = float64(1)                           // true转float64
	False2Float64       float64 = float64(0)                           // false转float64
	StringNil2Float     float64 = float64(0)                           // deprecated: 字符串空指针转float64
	StringBad2Float     float64 = float64(0)                           // deprecated: 字符串解析float64异常
	StringTrue2Float64  float64 = float64(1)                           // 字符串true转float64
	StringFalse2Float64 float64 = float64(0)                           // 字符串false转float64
)
View Source
const (
	MaxInt32          = int32(math.MaxInt32)
	MinInt32          = int32(math.MinInt32)
	Nil2Int32         = int32(0) // 空指针转int32
	Int32NaN          = int32(0) // int32 无效值
	True2Int32        = int32(1) // true转int32
	False2Int32       = int32(0) // false 转int32
	StringBad2Int32   = int32(0) // 字符串解析int32异常
	StringTrue2Int32  = int32(1) // 字符串true转int32
	StringFalse2Int32 = int32(0) // 字符串false转int32
)
View Source
const (
	MaxInt64          = int64(math.MaxInt64)
	MinInt64          = int64(math.MinInt64)
	Nil2Int64         = int64(0) // 空指针转int64
	Int64NaN          = int64(0) // int64 无效值
	True2Int64        = int64(1) // true转int64
	False2Int64       = int64(0) // false 转int64
	StringBad2Int64   = int64(0) // 字符串解析int64异常
	StringTrue2Int64  = int64(1) // 字符串true转int64
	StringFalse2Int64 = int64(0) // 字符串false转int64
)
View Source
const (
	StringNaN    = "NaN"   // 字符串NaN
	Nil2String   = "NaN"   // nil指针转string
	True2String  = "true"  // true转string
	False2String = "false" // false转string
)

Variables

View Source
var (
	// Nil2Float64 nil指针转换float64
	Nil2Float64 = float64(0)
	// Nil2Float32 nil指针转换float32
	Nil2Float32 = float32(0)
	DTypeNaN    = DType(0)
)
View Source
var (
	// IgnoreParseExceptions 忽略解析异常
	IgnoreParseExceptions bool = true
	Avx2Enabled                = false // AVX2加速开关
)
View Source
var (
	// ErrUnsupportedType 不支持的类型
	ErrUnsupportedType = exception.New(errorTypeBase+0, "Unsupported type")
	ErrRange           = exception.New(errorTypeBase+1, "range error")
)
View Source
var (
	TypeBool = reflect.TypeOf([]bool{})

	TypeInt64 = reflect.TypeOf([]int64{})

	TypeFloat32 = reflect.TypeOf([]float32{})

	TypeFloat64 = reflect.TypeOf([]float64{})
	TypeString  = reflect.TypeOf([]string{})
)

初始化全局的私有变量

View Source
var (
	// PossibleNaOfString 有可能出现的NaN字符串的全部选项
	PossibleNaOfString = []string{"NA", "NaN", "nan", "<nil>"}
)

Functions

func Abs

func Abs[T BaseType](x []T) []T

Abs 泛型绝对值

func Add added in v0.6.6

func Add[T Number](x []T, y any) []T

Add arithmetics 加法

func Align added in v0.6.3

func Align[T BaseType](x []T, a T, dLen int) []T

Align Data alignment

a 通常是默认值

func All added in v0.6.6

func All[T Number | ~bool](x []T) bool

All 全部为真

func And added in v0.6.6

func And[S ~[]E, E any](v S, x any) []bool

And 比较 v && v

func Any added in v0.6.6

func Any[T Number | ~bool](x []T) bool

Any 任意一个为真

func AnyToBool added in v0.6.5

func AnyToBool(v any) bool

AnyToBool any转换bool

func AnyToFloat32 added in v0.6.4

func AnyToFloat32(v any) float32

func AnyToFloat64 added in v0.6.4

func AnyToFloat64(v any) float64

func AnyToInt32 added in v0.6.6

func AnyToInt32(v any) int32

AnyToInt32 any转换int32

func AnyToInt64 added in v0.6.4

func AnyToInt64(v any) int64

AnyToInt64 any转换int64

func AnyToSlice added in v0.6.4

func AnyToSlice[T BaseType](A any, n int) []T

AnyToSlice any转切片

如果a是基础类型, 就是repeat
如果a是切片, 就做对齐处理

func AnyToString added in v0.6.4

func AnyToString(v any) string

AnyToString any转string

func Arange added in v0.7.0

func Arange[T Number](start T, end T, argv ...T) []T

Arange Return evenly spaced values within a given interval.

返回给定间隔内的等间距值

func ArgMax added in v0.6.4

func ArgMax[T Number](x []T) int

ArgMax Returns the indices of the maximum values along an axis.

返回轴上最大值的索引

func ArgMax2 added in v0.6.6

func ArgMax2[T BaseType](x []T) int

func ArgMin added in v0.6.4

func ArgMin[T Number](x []T) int

ArgMin Returns the indices of the minimum values along an axis.

返回轴上最小值的索引

func ArgMin2 added in v0.6.6

func ArgMin2[T BaseType](x []T) int

func BoolToFloat32 added in v0.6.6

func BoolToFloat32(b bool) float32

BoolToFloat32 bool转float32

func BoolToFloat64 added in v0.6.6

func BoolToFloat64(b bool) float64

BoolToFloat64 bool转float64

func BoolToInt added in v0.6.6

func BoolToInt(b bool) int8

func BoolToInt32 added in v0.6.6

func BoolToInt32(b bool) int32

func BoolToInt64 added in v0.6.6

func BoolToInt64(b bool) int64

func BoolToString added in v0.6.13

func BoolToString(b bool) string

BoolToString bool 转 string

func Concat1D added in v0.7.0

func Concat1D[T Number](a, b, c []T) [][]T

Concat1D

Translates slice objects to concatenation along the second axis.
沿第二个轴将切片对象转换为串联

func ConfidenceIntervalToZscore added in v0.7.7

func ConfidenceIntervalToZscore(confidenceInterval float64) (zScore float64)

ConfidenceIntervalToZscore 通过置信区间百分比查找Z分值

func Count added in v0.6.6

func Count[T Number | ~bool](x []T) int

Count 统计

func CumSum added in v0.6.4

func CumSum[T Number](x []T) []T

CumSum 计算累和

func DTypeIsNaN added in v0.6.4

func DTypeIsNaN(d DType) bool

DTypeIsNaN 判断DType是否NaN

func Decimal added in v0.9.12

func Decimal(value float64, prec int) float64

Decimal float64 保留小数点后位数

math.Trunc(value*1e2+0.5) * 1e-2

func DefaultFormatter added in v0.6.5

func DefaultFormatter(v interface{}) string

DefaultFormatter will return a string representation of the data in a particular row.

func Diff added in v0.6.5

func Diff[T Number](s []T, param any) []T

Diff 元素的第一个离散差

First discrete difference of element.
Calculates the difference of a {klass} element compared with another
element in the {klass} (default is element in previous row).

func Diff2 added in v0.6.6

func Diff2[T BaseType](s []T, param any) []T

func Div added in v0.6.6

func Div[T Number](x []T, y any) []T

Div arithmetics 除法

func Dot added in v0.7.0

func Dot[T Number](a, b [][]T) [][]T

Dot 二维点积

func Dot1D added in v0.7.0

func Dot1D[T Number](a, b []T) T

func Dot2D added in v0.7.0

func Dot2D[T Number](a, b [][]T) [][]T

Dot2D 二维矩阵点积

点积(dot)运算及简单应用 https://www.jianshu.com/p/482abac8798c

func Dot2D1 added in v0.7.0

func Dot2D1[T Number](a [][]T, b []T) []T

Dot2D1 二维矩阵和一维矩阵计算点积

func Dot2D1_v2 added in v0.7.0

func Dot2D1_v2[T Number](a [][]T, b []T) []T

func Dot2D_V1 added in v0.7.0

func Dot2D_V1[T Number](a, b [][]T) [][]T

func Dot_v1 added in v0.7.0

func Dot_v1[T Number](a, b [][]T) [][]T

func Equal added in v0.6.7

func Equal[T BaseType](x, y []T) []bool

Equal 比较相等

func Fill added in v0.6.4

func Fill[T BaseType](v []T, d T, args ...any) (rows []T)

Fill 填充

Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series, or DataFrame
   Value to use to fill holes (e.g. 0), alternately a
   dict/Series/DataFrame of values specifying which value to use for
   each index (for a Series) or column (for a DataFrame).  Values not
   in the dict/Series/DataFrame will not be filled. This value cannot
   be a list.
method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None
   Method to use for filling holes in reindexed Series
   pad / ffill: propagate last valid observation forward to next valid
   backfill / bfill: use next valid observation to fill gap.
axis : {axes_single_arg}
   Axis along which to fill missing values. For `Series`
   this parameter is unused and defaults to 0.
inplace : bool, default False [√]
   If True, fill in-place. Note: this will modify any
   other views on this object (e.g., a no-copy slice for a column in a
   DataFrame).
limit : int, default None
   If method is specified, this is the maximum number of consecutive
   NaN values to forward/backward fill. In other words, if there is
   a gap with more than this number of consecutive NaNs, it will only
   be partially filled. If method is not specified, this is the
   maximum number of entries along the entire axis where NaNs will be
   filled. Must be greater than 0 if not None.
downcast : dict, default is None
   A dict of item->dtype of what to downcast if possible,
   or the string 'infer' which will try to downcast to an appropriate
   equal type (e.g. float64 to int64 if possible).

Returns
-------
[]T or None

func FillNa added in v0.6.4

func FillNa[T BaseType](x []T, v any, args ...any) []T

FillNa NaN填充默认值

func FindPercent added in v0.7.7

func FindPercent(zScore float64) (percent float64)

func FindZScore added in v0.7.7

func FindZScore(percent float64) (zScore float64)

func Float32IsNaN added in v0.6.4

func Float32IsNaN(f float32) bool

Float32IsNaN 判断float32是否NaN

func Float64IsNaN added in v0.6.4

func Float64IsNaN(f float64) bool

Float64IsNaN 判断float64是否NaN

func GetAvx2Enabled added in v0.6.6

func GetAvx2Enabled() bool

GetAvx2Enabled 获取avx2加速状态

func Gt added in v0.7.9

func Gt[S ~[]E, E any](v S, x any) []bool

Gt 比较 v > x

func Gte added in v0.7.9

func Gte[S ~[]E, E any](v S, x any) []bool

Gte 比较 v >= x

func Inverse added in v0.7.0

func Inverse(a [][]float64) [][]float64

Inverse 计算矩阵的(乘法)逆

Compute the (multiplicative) inverse of a matrix.

Given a square matrix `a`, return the matrix `ainv` satisfying
``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.

func IsEmpty added in v0.6.4

func IsEmpty(s string) bool

IsEmpty Code to test if string is empty

func LinearRegression

func LinearRegression(x, y, weights []float64, origin bool) (alpha, beta float64)

LinearRegression 线性回归

func Lt added in v0.7.9

func Lt[S ~[]E, E any](v S, x any) []bool

Lt 比较 v < x

func Lte added in v0.7.9

func Lte[S ~[]E, E any](v S, x any) []bool

Lte 比较 v <= x

func Max added in v0.6.3

func Max[T Number](x []T) T

Max 纵向计算x最大值

func Max2 added in v0.6.6

func Max2[T BaseType](x []T) T

func Maximum added in v0.6.4

func Maximum[T Number](f1, f2 []T) []T

Maximum AVX2版本, 两个序列横向比较最大值

TODO:print(np.maximum(1.4, np.nan)) 输出nan

func Mean added in v0.6.4

func Mean[T Number](x []T) T

Mean 求均值

func Mean2 added in v0.6.6

func Mean2[T BaseType](x []T) T

func Min added in v0.6.4

func Min[T Number](x []T) T

Min 纵向计算x最小值

func Min2 added in v0.6.6

func Min2[T BaseType](x []T) T

func Minimum added in v0.6.4

func Minimum[T Number](f1, f2 []T) []T

Minimum AVX2版本, 两个序列横向比较最大值

func Mul added in v0.6.6

func Mul[T Number](x []T, y any) []T

Mul arithmetics 乘法

func NaN added in v0.6.5

func NaN() float64

NaN returns an IEEE 754 “not-a-number” value.

func Ones added in v0.7.0

func Ones[T Number](v []T) []T

Ones v -> shape

func PanicTrace added in v0.6.5

func PanicTrace(err interface{}) string

PanicTrace panic 堆栈信息

func ParseBool added in v0.6.5

func ParseBool(s string, v any) bool

ParseBool 字符串转bool

任意组合的nan字符串都会被解析成NaN

func ParseFloat32 added in v0.6.4

func ParseFloat32(s string, v any) float32

ParseFloat32 字符串转float32

func ParseFloat64 added in v0.6.4

func ParseFloat64(s string, v any) float64

ParseFloat64 字符串转float64 任意组合的nan字符串都会被解析成NaN

func ParseInt32 added in v0.6.6

func ParseInt32(s string, v any) int32

ParseInt32 解析int字符串, 尝试解析10进制和16进制

func ParseInt64 added in v0.6.4

func ParseInt64(s string, v any) int64

ParseInt64 解析int字符串, 尝试解析10进制和16进制

func Pow added in v0.7.0

func Pow[T Number](v []T, n int) []T

func PrintString added in v0.9.20

func PrintString(v any) string

func Range added in v0.6.5

func Range[T Number](n int) []T

Range 产生从0到n-1的数组

func Repeat added in v0.6.3

func Repeat[T BaseType](f T, n int) []T

Repeat 构造n长度的f的泛型切片

func RepeatInto added in v0.6.6

func RepeatInto[T BaseType](s []T, f T, n int) []T

RepeatInto 替换n长度的f的泛型切片

func Reverse added in v0.6.4

func Reverse[S ~[]E, E any](s S) S

Reverse 反转切片

func Rolling added in v0.6.5

func Rolling[T BaseType](S []T, N any) [][]T

Rolling returns an array with elements that roll beyond the last position are re-introduced at the first. 滑动窗口, 数据不足是用空数组占位

func Round added in v0.9.13

func Round(value float64, prec int) float64

Round float64 保留小数点后位数

value float64 浮点数
prec int 需保留小数点后的位数

func SetAvx2Enabled added in v0.6.6

func SetAvx2Enabled(enabled bool)

SetAvx2Enabled 设定AVX2加速开关

func Shape added in v0.7.0

func Shape[T Number](x any) (r, c int)

Shape 返回一维或2维数组的行数和列数

func Shift added in v0.6.5

func Shift[T BaseType](S []T, N any) []T

Shift 使用可选的时间频率按所需的周期数移动索引

param 支持前后移动

func ShiftN added in v0.6.7

func ShiftN[T BaseType](S []T, periods int) []T

ShiftN series切片, 使用可选的时间频率按所需的周期数移动索引 Deprecated: 不推荐使用

func SliceToFloat32 added in v0.6.4

func SliceToFloat32(v any) []float32

SliceToFloat32 any输入只能是一维slice或者数组

func SliceToFloat64 added in v0.6.4

func SliceToFloat64(v any) []float64

SliceToFloat64 any输入只能是一维slice或者数组

func SliceToString added in v0.6.22

func SliceToString(v any) []string

SliceToString any输入只能是一维slice或者数组

func Slope added in v0.9.23

func Slope(x1 int, y1 float64, x2 int, y2 float64) float64

Slope 计算斜率

func Sqrt added in v0.6.4

func Sqrt[T Number](v []T) []T

Sqrt 求平方根

func Std added in v0.6.4

func Std[T BaseType](f []T) T

Std 计算标准差

func Std_TODO added in v0.6.4

func Std_TODO[T Float](f []T) T

Std_TODO StdDev 这个版本有bug, gonum计算的std不对 TODO: 于总来解决

func StringIsFalse added in v0.6.6

func StringIsFalse(s string) bool

func StringIsNaN added in v0.6.4

func StringIsNaN(s string) bool

StringIsNaN 判断字符串是否NaN

func StringIsTrue added in v0.6.6

func StringIsTrue(s string) bool

func Sub added in v0.6.4

func Sub[T Number](x []T, y any) []T

Sub arithmetics 减法

func Sum added in v0.6.4

func Sum[T Number](f []T) T

Sum 求和

func Throw added in v0.6.6

func Throw(tv any) *exception.Exception

func ToBool added in v0.6.6

func ToBool(s Series) []bool

func ToFloat32 added in v0.6.6

func ToFloat32(s Series) []float32

ToFloat32 转换Float32

func ToFloat64 added in v0.6.6

func ToFloat64(s Series) []float64

func Transpose2D added in v0.7.0

func Transpose2D[T Number](x [][]T) [][]T

Transpose2D 矩阵转置

func TriangleBevel added in v0.9.23

func TriangleBevel(slope float64, x1 int, y1 float64, xn int) float64

TriangleBevel 三角形斜边

func V1And added in v0.7.10

func V1And[T Number | ~bool](x, y []T) []bool

And 两者为真

func Where

func Where[T StatType](condition []T, x, y []T) []T

Where 返回根据“条件”从“x”或“y”中选择的元素 这里先实现一个简单的, 留给于总重构 params只支持两个默认值x和y, 如果condition为true返回x, 否则返回y condition和param都可能是基础数据类型,也可能是一个slice, 并且长度可能不一致 直接写成序列版本, 可能更简单

func Zeros added in v0.6.4

func Zeros[T BaseType](shape int) []T

Zeros Return a new array of given shape and type, filled with zeros.

args[0] dtype 基础数据类型

func ZscoreToConfidenceInterval added in v0.7.7

func ZscoreToConfidenceInterval(zScore float64) (confidenceInterval float64)

ZscoreToConfidenceInterval 通过分值查找置信区间

Types

type AlphaType added in v0.6.6

type AlphaType int
const (
	// AlphaAlpha Specify smoothing factor α directly, 0<α≤1.
	AlphaAlpha AlphaType = iota
	// AlphaCom Specify decay in terms of center of mass, α=1/(1+com), for com ≥ 0.
	AlphaCom
	// AlphaSpan Specify decay in terms of span, α=2/(span+1), for span ≥ 1.
	AlphaSpan
	// AlphaHalfLife Specify decay in terms of half-life, α=1−exp(−ln(2)/halflife), for halflife > 0.
	AlphaHalfLife
)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html

type BaseType added in v0.6.5

type BaseType interface {
	Integer | Float | ~string | ~bool
}

BaseType 基础类型

type BigFloat added in v0.6.4

type BigFloat = big.Float // 预留将来可能扩展float

type Complex added in v0.6.5

type Complex interface {
	~complex64 | ~complex128
}

Complex is a constraint that permits any complex numeric type. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.

type DType added in v0.6.4

type DType = float64

func Any2DType added in v0.6.4

func Any2DType(v any) DType

Any2DType any转DType

func Median added in v0.6.4

func Median[T Number](values []T) DType

Median returns median value of series. Linear interpolation is used for odd length. TODO:未加验证, 未加速

func PolyFit added in v0.6.4

func PolyFit(x, y []DType, deg int, args ...any) []DType

PolyFit

Least squares polynomial fit.

.. note::
	This forms part of the old polynomial API. Since version 1.4, the
	new polynomial API defined in `numpy.polynomial` is preferred.
	A summary of the differences can be found in the
	:doc:`transition guide </reference/routines.polynomials>`.

Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`
to points `(x, y)`. Returns a vector of coefficients `p` that minimises
the squared error in the order `deg`, `deg-1`, ... `0`.

The `Polynomial.fit <numpy.polynomial.polynomial.Polynomial.fit>` class
method is recommended for new code as it is more stable numerically. See
the documentation of the method for more information.

Parameters
----------
x : array_like, shape (M,)
	x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_like, shape (M,) or (M, K)
	y-coordinates of the sample points. Several data sets of sample
	points sharing the same x-coordinates can be fitted at once by
	passing in a 2D-array that contains one dataset per column.
deg : int
	Degree of the fitting polynomial

Returns
-------
p : ndarray, shape (deg + 1,) or (deg + 1, K)
	Polynomial coefficients, highest power first.  If `y` was 2-D, the
	coefficients for `k`-th data set are in ``p[:,k]``.

residuals, rank, singular_values, rcond
	These values are only returned if ``full == True``

	- residuals -- sum of squared residuals of the least squares fit
	- rank -- the effective rank of the scaled Vandermonde
		coefficient matrix
	- singular_values -- singular values of the scaled Vandermonde
		coefficient matrix
	- rcond -- value of `rcond`.

	For more details, see `numpy.linalg.lstsq`.

Warns
-----
RankWarning
	The rank of the coefficient matrix in the least-squares fit is
	deficient. The warning is only raised if ``full == False``.

	The warnings can be turned off by

	>>> import warnings
	>>> warnings.simplefilter('ignore', np.RankWarning)

See Also
--------
polyval : Compute polynomial values.
linalg.lstsq : Computes a least-squares fit.
scipy.interpolate.UnivariateSpline : Computes spline fits.

Notes
-----
The solution minimizes the squared error

.. math::
	E = \\sum_{j=0}^k |p(x_j) - y_j|^2

in the equations::

	x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
	x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]
	...
	x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]

The coefficient matrix of the coefficients `p` is a Vandermonde matrix.

`polyfit` issues a `RankWarning` when the least-squares fit is badly
conditioned. This implies that the best fit is not well-defined due
to numerical error. The results may be improved by lowering the polynomial
degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter
can also be set to a value smaller than its default, but the resulting
fit may be spurious: including contributions from the small singular
values can add numerical noise to the result.

Note that fitting polynomial coefficients is inherently badly conditioned
when the degree of the polynomial is large or the interval of sample points
is badly centered. The quality of the fit should always be checked in these
cases. When polynomial fits are not satisfactory, splines may be a good
alternative.

References
----------
.. [1] Wikipedia, "Curve fitting",
		https://en.wikipedia.org/wiki/Curve_fitting
.. [2] Wikipedia, "Polynomial interpolation",
		https://en.wikipedia.org/wiki/Polynomial_interpolation
.. [3] numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)
		https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html

Examples
--------
>>> import warnings
>>> x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
>>> z = np.polyfit(x, y, 3)
>>> z
array([ 0.08703704, -0.81349206,  1.69312169, -0.03968254]) # may vary

func PolyVal added in v0.6.4

func PolyVal(p, x []DType) []DType

PolyVal

Evaluate a polynomial at specific values.

.. note::
This forms part of the old polynomial API. Since version 1.4, the
new polynomial API defined in `numpy.polynomial` is preferred.
A summary of the differences can be found in the
:doc:`transition guide </reference/routines.polynomials>`.

If `p` is of length N, this function returns the value:

``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]``

If `x` is a sequence, then ``p(x)`` is returned for each element of ``x``.
If `x` is another polynomial then the composite polynomial ``p(x(t))``
is returned.

Parameters

----------

p : array_like or poly1d object
	1D array of polynomial coefficients (including coefficients equal
	to zero) from highest degree to the constant term, or an
	instance of poly1d.
x : array_like or poly1d object
	A number, an array of numbers, or an instance of poly1d, at
	which to evaluate `p`.

Returns

-------

values : ndarray or poly1d
	If `x` is a poly1d instance, the result is the composition of the two
	polynomials, i.e., `x` is "substituted" in `p` and the simplified
	result is returned. In addition, the type of `x` - array_like or
	poly1d - governs the type of the output: `x` array_like => `values`
	array_like, `x` a poly1d object => `values` is also.

See Also
--------
poly1d: A polynomial class.

Notes
-----
Horner's scheme [1]_ is used to evaluate the polynomial. Even so,
for polynomials of high degree the values may be inaccurate due to
rounding errors. Use carefully.

If `x` is a subtype of `ndarray` the return value will be of the same type.

References
----------
.. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng.
trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand
Reinhold Co., 1985, pg. 720.

Examples
--------
>>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
76
>>> np.polyval([3,0,1], np.poly1d(5))
poly1d([76])
>>> np.polyval(np.poly1d([3,0,1]), 5)
76
>>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
poly1d([76])

func Slice2DType added in v0.6.4

func Slice2DType(v any) []DType

Slice2DType 切片转DType

type EW added in v0.6.6

type EW struct {
	Com      DType // 根据质心指定衰减
	Span     DType // 根据跨度指定衰减
	HalfLife DType // 根据半衰期指定衰减
	Alpha    DType // 直接指定的平滑因子α
	Adjust   bool  // 除以期初的衰减调整系数以核算 相对权重的不平衡(将 EWMA 视为移动平均线)
	IgnoreNA bool  // 计算权重时忽略缺失值
	Callback func(idx int) DType
}

EW (Factor) 指数加权(EW)计算Alpha 结构属性非0即为有效启动同名算法

type ExponentialMovingWindow added in v0.6.6

type ExponentialMovingWindow struct {
	Data     Series    // 序列
	AType    AlphaType // 计算方式: com/span/halflefe/alpha
	Param    DType     // 参数类型为浮点
	Adjust   bool      // 默认为真, 是否调整, 默认真时, 计算序列的EW移动平均线, 为假时, 计算指数加权递归
	IgnoreNA bool      // 默认为假, 计算权重时是否忽略缺失值NaN

	Cb func(idx int) DType
	// contains filtered or unexported fields
}

ExponentialMovingWindow 加权移动窗口

func (ExponentialMovingWindow) Mean added in v0.6.6

type Float added in v0.6.3

type Float interface {
	~float32 | ~float64
}

Float is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.

type GenericType added in v0.6.4

type GenericType interface {
	~bool | ~int32 | ~int64 | ~int | ~float32 | ~float64 | ~string
}

GenericType Series支持的所有类型 Deprecated: 不推荐使用

type Int added in v0.6.4

type Int = int32

func DType2Int added in v0.6.4

func DType2Int(d []DType) []Int

DType切片转int32切片

type Integer added in v0.6.4

type Integer interface {
	Signed | Unsigned
}

Integer is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.

type LeafNode added in v0.7.7

type LeafNode struct {
	// contains filtered or unexported fields
}

LeafNode struct

type MoveType deprecated added in v0.6.3

type MoveType interface {
	StatType | ~bool | ~string
}

Deprecated: 已弃用

type NDArray added in v0.6.4

type NDArray[T BaseType] []T

func (NDArray[T]) Add added in v0.6.6

func (self NDArray[T]) Add(x any) Series

func (NDArray[T]) And added in v0.6.7

func (self NDArray[T]) And(x any) Series

func (NDArray[T]) Append added in v0.6.6

func (self NDArray[T]) Append(values ...any) Series

func (NDArray[T]) Apply added in v0.6.6

func (self NDArray[T]) Apply(f func(idx int, v any))

func (NDArray[T]) Apply2 added in v0.6.15

func (self NDArray[T]) Apply2(f func(idx int, v any) any, args ...bool) Series

Apply2 提供可替换功能的apply方法, 默认不替换

func (NDArray[T]) ArgMax added in v0.6.6

func (self NDArray[T]) ArgMax() int

func (NDArray[T]) ArgMin added in v0.6.6

func (self NDArray[T]) ArgMin() int

func (NDArray[T]) Bools added in v0.7.9

func (self NDArray[T]) Bools() []bool

func (NDArray[T]) Concat added in v0.6.16

func (self NDArray[T]) Concat(x Series) Series

func (NDArray[T]) Copy added in v0.6.6

func (self NDArray[T]) Copy() Series

func (NDArray[T]) DTypes added in v0.6.6

func (self NDArray[T]) DTypes() []DType

func (NDArray[T]) Diff added in v0.6.6

func (self NDArray[T]) Diff(n any) Series

func (NDArray[T]) Div added in v0.6.6

func (self NDArray[T]) Div(x any) Series

func (NDArray[T]) EWM added in v0.6.6

func (self NDArray[T]) EWM(alpha EW) ExponentialMovingWindow

func (NDArray[T]) Empty added in v0.6.6

func (self NDArray[T]) Empty(tv ...Type) Series

func (NDArray[T]) Eq added in v0.6.7

func (self NDArray[T]) Eq(x any) Series

func (NDArray[T]) FillNa added in v0.6.6

func (self NDArray[T]) FillNa(v any, inplace bool) Series

func (NDArray[T]) Floats added in v0.6.6

func (self NDArray[T]) Floats() []float32

func (NDArray[T]) Gt added in v0.6.7

func (self NDArray[T]) Gt(x any) Series

func (NDArray[T]) Gte added in v0.6.7

func (self NDArray[T]) Gte(x any) Series

func (NDArray[T]) IndexOf added in v0.6.18

func (self NDArray[T]) IndexOf(index int, opt ...any) any

func (NDArray[T]) Ints added in v0.6.6

func (self NDArray[T]) Ints() []Int

func (NDArray[T]) Len added in v0.6.6

func (arr NDArray[T]) Len() int

func (NDArray[T]) Less added in v0.6.6

func (arr NDArray[T]) Less(i, j int) bool

Less 实现sort.Interface接口的比较元素方法

func (NDArray[T]) Logic added in v0.6.6

func (self NDArray[T]) Logic(f func(idx int, v any) bool) []bool

func (NDArray[T]) Lt added in v0.6.7

func (self NDArray[T]) Lt(x any) Series

func (NDArray[T]) Lte added in v0.6.7

func (self NDArray[T]) Lte(x any) Series

func (NDArray[T]) Max added in v0.6.6

func (self NDArray[T]) Max() any

func (NDArray[T]) Mean added in v0.6.6

func (self NDArray[T]) Mean() DType

func (NDArray[T]) Min added in v0.6.6

func (self NDArray[T]) Min() any

func (NDArray[T]) Mul added in v0.6.6

func (self NDArray[T]) Mul(x any) Series

func (NDArray[T]) NaN added in v0.6.6

func (self NDArray[T]) NaN() any

func (NDArray[T]) Name added in v0.6.6

func (self NDArray[T]) Name() string

func (NDArray[T]) Records added in v0.6.6

func (self NDArray[T]) Records(round ...bool) []string

func (NDArray[T]) Ref added in v0.6.6

func (self NDArray[T]) Ref(n any) Series

func (NDArray[T]) Rename added in v0.6.6

func (self NDArray[T]) Rename(name string)

func (NDArray[T]) Repeat added in v0.6.6

func (self NDArray[T]) Repeat(x any, repeats int) Series

func (NDArray[T]) Reverse added in v0.6.6

func (self NDArray[T]) Reverse() Series

func (NDArray[T]) Rolling added in v0.6.6

func (self NDArray[T]) Rolling(param any) RollingAndExpandingMixin

func (NDArray[T]) Select added in v0.6.6

func (self NDArray[T]) Select(r ScopeLimit) Series

func (NDArray[T]) Shift added in v0.6.6

func (self NDArray[T]) Shift(periods int) Series

func (NDArray[T]) Std added in v0.6.6

func (self NDArray[T]) Std() DType

func (NDArray[T]) StdDev added in v0.6.6

func (self NDArray[T]) StdDev() DType

func (NDArray[T]) Strings added in v0.6.22

func (self NDArray[T]) Strings() []string

func (NDArray[T]) Sub added in v0.6.6

func (self NDArray[T]) Sub(x any) Series

func (NDArray[T]) Subset added in v0.6.6

func (self NDArray[T]) Subset(start, end int, opt ...any) Series

func (NDArray[T]) Sum added in v0.6.6

func (self NDArray[T]) Sum() DType

func (NDArray[T]) Swap added in v0.6.6

func (arr NDArray[T]) Swap(i, j int)

Swap 实现sort.Interface接口的交换元素方法

func (NDArray[T]) Type added in v0.6.6

func (self NDArray[T]) Type() Type

func (NDArray[T]) V1And added in v0.8.1

func (self NDArray[T]) V1And(x any) Series

func (NDArray[T]) V1Gt added in v0.7.9

func (self NDArray[T]) V1Gt(x any) Series

func (NDArray[T]) Values added in v0.6.6

func (self NDArray[T]) Values() any

type Node added in v0.7.7

type Node struct {
	// contains filtered or unexported fields
}

Node struct

type Number added in v0.6.4

type Number interface {
	Integer | Float
}

Number int和uint的长度取决于CPU是多少位

type Number16 deprecated added in v0.6.4

type Number16 interface {
	~int16 | ~uint16
}

Deprecated: 不推荐使用

type Number32 deprecated added in v0.6.4

type Number32 interface {
	~int32 | ~uint32 | float32
}

Deprecated: 不推荐使用

type Number64 deprecated added in v0.6.4

type Number64 interface {
	~int64 | ~uint64 | float64 | int | uint
}

Deprecated: 不推荐使用

type Number8 deprecated added in v0.6.4

type Number8 interface {
	~int8 | ~uint8
}

Deprecated: 不推荐使用

type NumberOfCPUBitsRelated added in v0.6.6

type NumberOfCPUBitsRelated interface {
	~int | ~uint | ~uintptr
}

NumberOfCPUBitsRelated The number of CPU bits is related Deprecated: 不推荐使用

type Options added in v0.7.7

type Options struct {
	BucketSize int // number of table values to group together in tree leaf-node
}

Options is a config for the NewZTable function which allows bucket size customization. Default bucket size is 30

type Ordered added in v0.6.5

type Ordered interface {
	Integer | Float | ~string
}

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

type RollingAndExpandingMixin added in v0.6.6

type RollingAndExpandingMixin struct {
	Window []DType
	Series Series
}

RollingAndExpandingMixin 滚动和扩展静态横切

func (RollingAndExpandingMixin) Apply added in v0.6.6

func (r RollingAndExpandingMixin) Apply(f func(S Series, N DType) DType) (s Series)

Apply 接受一个回调

func (RollingAndExpandingMixin) Count added in v0.6.6

func (r RollingAndExpandingMixin) Count() (s Series)

func (RollingAndExpandingMixin) GetBlocks added in v0.6.6

func (r RollingAndExpandingMixin) GetBlocks() (blocks []Series)

func (RollingAndExpandingMixin) Max added in v0.6.6

func (r RollingAndExpandingMixin) Max() (s Series)

func (RollingAndExpandingMixin) Mean added in v0.6.6

func (r RollingAndExpandingMixin) Mean() (s Series)

Mean returns the rolling mean.

func (RollingAndExpandingMixin) Min added in v0.6.6

func (r RollingAndExpandingMixin) Min() (s Series)

func (RollingAndExpandingMixin) Std added in v0.6.6

func (RollingAndExpandingMixin) Sum added in v0.6.6

type ScopeLimit added in v0.6.6

type ScopeLimit struct {
	Start *int
	End   *int
}

ScopeLimit is used to specify a range. Both Start and End are inclusive. A nil value means no limit, so a Start of nil means 0 and an End of nil means no limit. The End value must always be equal to or larger than Start. Negative values are acceptable. A value of -2 means the second last row.

func IntsToRanges added in v0.6.6

func IntsToRanges(ints []int) []ScopeLimit

IntsToRanges will convert an already (ascending) ordered list of ints to a slice of Ranges.

Example:

import "sort"
ints := []int{2,4,5,6,8,10,11,45,46}
sort.Ints(ints)

fmt.Println(IntsToRanges(ints))
// Output: R{2,2}, R{4,6}, R{8,8}, R{10,11}, R{45,46}

func RangeFinite added in v0.6.6

func RangeFinite(start int, end ...int) ScopeLimit

RangeFinite returns a ScopeLimit that has a finite span.

func (*ScopeLimit) Limits added in v0.6.6

func (r *ScopeLimit) Limits(length int) (s int, e int, _ error)

Limits is used to return the start and end limits of a ScopeLimit object for a given Dataframe or Series with length number of rows.

func (*ScopeLimit) NRows added in v0.6.6

func (r *ScopeLimit) NRows(length ...int) (int, error)

NRows returns the number of rows contained by ScopeLimit. If End is nil, then length must be provided.

func (ScopeLimit) String added in v0.6.6

func (r ScopeLimit) String() string

String implements Stringer interface.

type Series added in v0.6.5

type Series interface {
	// Name 取得series名称
	Name() string
	// Rename renames the series.
	Rename(name string)
	// Type returns the type of Data the series holds.
	// 返回series的数据类型
	Type() Type
	// Values 获得全部数据集
	Values() any
	// NaN 输出默认的NaN
	NaN() any

	// Floats 强制转成[]float32
	Floats() []float32
	// DTypes 强制转[]stat.DType
	DTypes() []DType
	// Ints 强制转换成整型
	Ints() []Int
	// Strings 强制转换string切片
	Strings() []string
	// Bools 强制转换成bool切片
	Bools() []bool

	// Len 获得行数, 实现sort.Interface接口的获取元素数量方法
	Len() int
	// Less 实现sort.Interface接口的比较元素方法
	Less(i, j int) bool
	// Swap 实现sort.Interface接口的交换元素方法
	Swap(i, j int)

	// Empty returns an empty Series of the same type
	Empty(t ...Type) Series
	// Copy 复制
	Copy() Series
	// Reverse 序列反转
	Reverse() Series
	// Select 选取一段记录
	Select(r ScopeLimit) Series
	// Append 增加一批记录
	Append(values ...any) Series
	// Concat concatenates two series together. It will return a new Series with the
	// combined elements of both Series.
	Concat(x Series) Series

	// Records returns the elements of a Series as a []string
	Records(round ...bool) []string
	// IndexOf 取一条记录, index<0时, 从后往前取值
	IndexOf(index int, opt ...any) any
	// Subset 获取子集
	Subset(start, end int, opt ...any) Series
	// Repeat elements of an array.
	Repeat(x any, repeats int) Series
	// FillNa Fill NA/NaN values using the specified method.
	FillNa(v any, inplace bool) Series

	// Ref 引用其它周期的数据
	Ref(periods any) (s Series)
	// Shift index by desired number of periods with an optional time freq.
	//	使用可选的时间频率按所需的周期数移动索引.
	Shift(periods int) Series
	// Rolling 序列化版本
	Rolling(param any) RollingAndExpandingMixin
	// Apply 接受一个回调函数
	Apply(f func(idx int, v any))
	// Apply2 增加替换功能, 默认不替换
	Apply2(f func(idx int, v any) any, args ...bool) Series
	// Logic 逻辑处理
	Logic(f func(idx int, v any) bool) []bool
	// EWM Provide exponentially weighted (EW) calculations.
	//
	//	Exactly one of “com“, “span“, “halflife“, or “alpha“ must be
	//	provided if “times“ is not provided. If “times“ is provided,
	//	“halflife“ and one of “com“, “span“ or “alpha“ may be provided.
	EWM(alpha EW) ExponentialMovingWindow

	// Mean calculates the average value of a series
	Mean() DType
	// StdDev calculates the standard deviation of a series
	StdDev() DType
	// Max 找出最大值
	Max() any
	// ArgMax Returns the indices of the maximum values along an axis
	ArgMax() int
	// Min 找出最小值
	Min() any
	// ArgMin Returns the indices of the minimum values along an axis
	ArgMin() int
	// Diff 元素的第一个离散差
	Diff(param any) (s Series)
	// Std 计算标准差
	Std() DType
	// Sum 计算累和
	Sum() DType
	Add(x any) Series
	Sub(x any) Series
	Mul(x any) Series
	Div(x any) Series
	Eq(x any) Series
	Gt(x any) Series
	Gte(x any) Series
	Lt(x any) Series
	Lte(x any) Series
	And(x any) Series
}

Series

Data structure for 1-dimensional cross-sectional and time series data
一维横截面和时间序列数据的数据结构

func Align2Series added in v0.9.10

func Align2Series(x any, N int) Series

Align2Series any转换成series

func NewSeries added in v0.6.6

func NewSeries[T BaseType](data ...T) Series

NewSeries 构建一个新的Series

type Signed added in v0.6.5

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.

type StatType

type StatType interface {
	~int32 | ~int64 | ~float32 | ~float64
}

StatType 可以统计的类型 Deprecated: 不推荐使用

type StringFormatter added in v0.6.5

type StringFormatter func(val interface{}) string

StringFormatter is used to convert a value into a string. Val can be nil or the concrete type stored by the series.

type Type added in v0.6.5

type Type = reflect.Kind

Type is a convenience alias that can be used for a more type safe way of reason and use Series types.

func DetectTypeBySlice added in v0.6.6

func DetectTypeBySlice(arr ...any) (Type, error)

DetectTypeBySlice 检测类型

type Unsigned added in v0.6.5

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Unsigned is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.

type ZTable added in v0.7.7

type ZTable struct {
	// contains filtered or unexported fields
}

ZTable is the core z-score table component

func NewZTable added in v0.7.7

func NewZTable(options *Options) *ZTable

NewZTable creates and returns a new ZTable object. 'options' allows you to set the bucket size of the leaf nodes. Tuning bucket size will allow you to trade off memory for speed and vice-versa in the z-score lookup,

func (*ZTable) FindPercentage added in v0.7.7

func (zt *ZTable) FindPercentage(zScore float64) float64

FindPercentage returns the percentage of a given z-score from the table

func (*ZTable) FindZScore added in v0.7.7

func (zt *ZTable) FindZScore(percentage float64) (float64, error)

FindZScore returns the closest z-score given a percentage value

Jump to

Keyboard shortcuts

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