stat

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2023 License: Apache-2.0 Imports: 20 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

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

Add arithmetics 加法

func Align

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

Align Data alignment

a 通常是默认值

func All

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

All 全部为真

func And

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

And 比较 v && x

func Any

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

Any 任意一个为真

func AnyToBool

func AnyToBool(v any) bool

AnyToBool any转换bool

func AnyToFloat32

func AnyToFloat32(v any) float32

func AnyToFloat64

func AnyToFloat64(v any) float64

func AnyToInt32

func AnyToInt32(v any) int32

AnyToInt32 any转换int32

func AnyToInt64

func AnyToInt64(v any) int64

AnyToInt64 any转换int64

func AnyToSlice

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

AnyToSlice any转切片

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

func AnyToString

func AnyToString(v any) string

AnyToString any转string

func Arange

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

Arange Return evenly spaced values within a given interval.

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

func ArgMax

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

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

返回轴上最大值的索引

func ArgMax2

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

func ArgMin

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

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

返回轴上最小值的索引

func ArgMin2

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

func BoolToFloat32

func BoolToFloat32(b bool) float32

BoolToFloat32 bool转float32

func BoolToFloat64

func BoolToFloat64(b bool) float64

BoolToFloat64 bool转float64

func BoolToInt

func BoolToInt(b bool) int8

func BoolToInt32

func BoolToInt32(b bool) int32

func BoolToInt64

func BoolToInt64(b bool) int64

func BoolToString

func BoolToString(b bool) string

BoolToString bool 转 string

func Concat1D

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

Concat1D

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

func ConfidenceIntervalToZscore

func ConfidenceIntervalToZscore(confidenceInterval float64) (zScore float64)

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

func Count

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

Count 统计

func CumSum

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

CumSum 计算累和

func DTypeIsNaN

func DTypeIsNaN(d DType) bool

DTypeIsNaN 判断DType是否NaN

func DefaultFormatter

func DefaultFormatter(v interface{}) string

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

func Diff

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

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

func Div

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

Div arithmetics 除法

func Dot

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

Dot 二维点积

func Dot1D

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

func Dot2D

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

Dot2D 二维矩阵点积

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

func Dot2D1

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

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

func Dot2D1_v2

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

func Dot2D_V1

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

func Dot_v1

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

func Equal

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

Equal 比较相等

func Fill

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

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

FillNa NaN填充默认值

func FindPercent

func FindPercent(zScore float64) (percent float64)

func FindZScore

func FindZScore(percent float64) (zScore float64)

func Float32IsNaN

func Float32IsNaN(f float32) bool

Float32IsNaN 判断float32是否NaN

func Float64IsNaN

func Float64IsNaN(f float64) bool

Float64IsNaN 判断float64是否NaN

func GenericParse

func GenericParse[T BaseType](text string) T

GenericParse 泛型解析

func GetAvx2Enabled

func GetAvx2Enabled() bool

GetAvx2Enabled 获取avx2加速状态

func Gt

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

Gt 比较 v > x

func Gte

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

Gte 比较 v >= x

func Inverse

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

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

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

Lt 比较 v < x

func Lte

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

Lte 比较 v <= x

func Max

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

Max 纵向计算x最大值

func Max2

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

func Maximum

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

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

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

func Mean

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

Mean 求均值

func Mean2

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

func Min

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

Min 纵向计算x最小值

func Min2

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

func Minimum

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

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

func Mul

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

Mul arithmetics 乘法

func NaN

func NaN() float64

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

func Ones

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

Ones v -> shape

func Or

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

Or 比较 v || x

func PanicTrace

func PanicTrace(err interface{}) string

PanicTrace panic 堆栈信息

func ParseBool

func ParseBool(s string, v any) bool

ParseBool 字符串转bool

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

func ParseFloat32

func ParseFloat32(s string, v any) float32

ParseFloat32 字符串转float32

func ParseFloat64

func ParseFloat64(s string, v any) float64

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

func ParseInt32

func ParseInt32(s string, v any) int32

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

func ParseInt64

func ParseInt64(s string, v any) int64

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

func Pow

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

func PrintString

func PrintString(v any) string

func Range

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

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

func Repeat

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

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

func RepeatInto

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

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

func Reverse

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

Reverse 反转切片

func Rolling

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 SetAvx2Enabled

func SetAvx2Enabled(enabled bool)

SetAvx2Enabled 设定AVX2加速开关

func Shape

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

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

func Shift

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

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

param 支持前后移动

func ShiftN

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

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

func SliceToFloat32

func SliceToFloat32(v any) []float32

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

func SliceToFloat64

func SliceToFloat64(v any) []float64

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

func SliceToString

func SliceToString(v any) []string

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

func Slope

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

Slope 计算斜率

func Sqrt

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

Sqrt 求平方根

func Std

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

Std 计算标准差

func Std_TODO

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

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

func StringIsEmpty added in v1.0.1

func StringIsEmpty(s string) bool

StringIsEmpty 判断字符串是否空字符串

func StringIsFalse

func StringIsFalse(s string) bool

func StringIsNaN

func StringIsNaN(s string) bool

StringIsNaN 判断字符串是否NaN

func StringIsTrue

func StringIsTrue(s string) bool

func Sub

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

Sub arithmetics 减法

func Sum

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

Sum 求和

func Throw

func Throw(tv any) *exception.Exception

func ToBool

func ToBool(s Series) []bool

func ToFloat32

func ToFloat32(s Series) []float32

ToFloat32 转换Float32

func ToFloat64

func ToFloat64(s Series) []float64

func Transpose2D

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

Transpose2D 矩阵转置

func TriangleBevel

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

TriangleBevel 三角形斜边

func V1And

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

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

func ZscoreToConfidenceInterval(zScore float64) (confidenceInterval float64)

ZscoreToConfidenceInterval 通过分值查找置信区间

Types

type AlphaType

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

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

BaseType 基础类型

type BigFloat

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

type Complex

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

type DType = float64

func Any2DType

func Any2DType(v any) DType

Any2DType any转DType

func Median

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

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

func PolyFit

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

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

func Slice2DType(v any) []DType

Slice2DType 切片转DType

type EW

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

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

type Float

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

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

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

type Int

type Int = int32

func DType2Int

func DType2Int(d []DType) []Int

DType切片转int32切片

type Integer

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

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

LeafNode struct

type MoveType deprecated

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

Deprecated: 已弃用

type NDArray

type NDArray[T BaseType] []T

func (NDArray[T]) Add

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

func (NDArray[T]) And

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

func (NDArray[T]) Append

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

func (NDArray[T]) Apply

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

func (NDArray[T]) Apply2

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

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

func (NDArray[T]) ArgMax

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

func (NDArray[T]) ArgMin

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

func (NDArray[T]) Bools

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

func (NDArray[T]) Concat

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

func (NDArray[T]) Copy

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

func (NDArray[T]) DTypes

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

func (NDArray[T]) Diff

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

func (NDArray[T]) Div

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

func (NDArray[T]) EWM

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

func (NDArray[T]) Empty

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

func (NDArray[T]) Eq

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

func (NDArray[T]) FillNa

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

func (NDArray[T]) Floats

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

func (NDArray[T]) Gt

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

func (NDArray[T]) Gte

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

func (NDArray[T]) IndexOf

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

func (NDArray[T]) Ints

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

func (NDArray[T]) Len

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

func (NDArray[T]) Less

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

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

func (NDArray[T]) Logic

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

func (NDArray[T]) Lt

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

func (NDArray[T]) Lte

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

func (NDArray[T]) Max

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

func (NDArray[T]) Mean

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

func (NDArray[T]) Min

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

func (NDArray[T]) Mul

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

func (NDArray[T]) NaN

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

func (NDArray[T]) Name

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

func (NDArray[T]) Or

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

func (NDArray[T]) Records

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

func (NDArray[T]) Ref

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

func (NDArray[T]) Rename

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

func (NDArray[T]) Repeat

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

func (NDArray[T]) Reverse

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

func (NDArray[T]) Rolling

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

func (NDArray[T]) Select

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

func (NDArray[T]) Shift

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

func (NDArray[T]) Std

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

func (NDArray[T]) StdDev

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

func (NDArray[T]) Strings

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

func (NDArray[T]) Sub

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

func (NDArray[T]) Subset

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

func (NDArray[T]) Sum

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

func (NDArray[T]) Swap

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

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

func (NDArray[T]) Type

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

func (NDArray[T]) V1And

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

func (NDArray[T]) V1Gt

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

func (NDArray[T]) Values

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

type Node

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

Node struct

type Number

type Number interface {
	Integer | Float
}

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

type Number16 deprecated

type Number16 interface {
	~int16 | ~uint16
}

Deprecated: 不推荐使用

type Number32 deprecated

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

Deprecated: 不推荐使用

type Number64 deprecated

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

Deprecated: 不推荐使用

type Number8 deprecated

type Number8 interface {
	~int8 | ~uint8
}

Deprecated: 不推荐使用

type NumberOfCPUBitsRelated

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

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

type Options

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

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

type RollingAndExpandingMixin struct {
	Window []DType
	Series Series
}

RollingAndExpandingMixin 滚动和扩展静态横切

func (RollingAndExpandingMixin) Apply

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

Apply 接受一个回调

func (RollingAndExpandingMixin) Count

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

func (RollingAndExpandingMixin) GetBlocks

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

func (RollingAndExpandingMixin) Max

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

func (RollingAndExpandingMixin) Mean

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

Mean returns the rolling mean.

func (RollingAndExpandingMixin) Min

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

func (RollingAndExpandingMixin) Std

func (RollingAndExpandingMixin) Sum

type Series

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 api.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, fillEmpty 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
	Or(x any) Series
}

Series

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

func Align2Series

func Align2Series(x any, N int) Series

Align2Series any转换成series

func NewSeries

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

NewSeries 构建一个新的Series

type Signed

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

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

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

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

DetectTypeBySlice 检测类型

type Unsigned

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

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

ZTable is the core z-score table component

func NewZTable

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

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

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

func (*ZTable) FindZScore

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