跳转到主要内容

T-Digest数据结构

项目描述

# tdigest
### 流式或分布式数据的高效百分位数估计
[![PyPI版本](https://badge.fury.io/py/tdigest.svg)](https://badge.fury.io/py/tdigest)
[![构建状态](https://travis-ci.org/CamDavidsonPilon/tdigest.svg?branch=master)](https://travis-ci.org/CamDavidsonPilon/tdigest)


这是Ted Dunning的[t-digest](https://github.com/tdunning/t-digest)数据结构的Python实现。t-digest数据结构旨在从流式数据或分布式数据中计算准确的估计。这些估计是百分位数、分位数、修剪均值等。两个t-digest可以相加,使得数据结构非常适合map-reduce设置,并且可以序列化为小于10KB(而不是存储整个数据列表)。

有关更多信息,请参阅此博客文章:[大数据的百分位数和分位数估计:t-Digest](http://dataorigami.net/blogs/napkin-folding/19055451-percentile-and-quantile-estimation-of-big-data-the-t-digest)


### 安装
*tdigest*与Python 2和Python 3都兼容。

```
pip安装tdigest
```

### 使用

#### 顺序更新摘要

```
from tdigest import TDigest
from numpy.random import random

digest = TDigest()
for x in range(5000)
digest.update(random())

print(digest.percentile(15)) # 约为0.15,因为0.15是均匀分布(0,1)的第15百分位数
```

#### 批量更新摘要

```
another_digest = TDigest()
another_digest.batch_update(random(5000))
print(another_digest.percentile(15))
```

#### 将两个摘要相加以创建一个新的摘要

```
sum_digest = digest + another_digest
sum_digest.percentile(30) # 约为0.3
```

#### 将摘要转换为字典或使用JSON序列化摘要

您可以使用to_dict()方法将TDigest对象转换为标准的Python字典。
```
digest = TDigest()
digest.update(1)
digest.update(2)
digest.update(3)
print(digest.to_dict())
```
或者,您可以使用`centroids_to_list()`获取仅包含质心的列表。
```
digest.centroids_to_list()
```

类似地,您可以使用`update_from_dict()`从字典中恢复摘要值。质心将与摘要中现有的任何质心合并。
例如,创建一个新的摘要并从Python字典中恢复值。
```
digest = TDigest()
digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]})
```

K和delta值是可选的,或者您可以使用`update_centroids_from_list()`仅提供一个质心列表。
```
digest = TDigest()
digest.update_centroids([{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}])
```

如果您想使用其他工具(如JSON)进行序列化,可以先转换为to_dict()。
```
json.dumps(digest.to_dict())
```

或者,创建一个自定义编码函数,将其作为默认参数提供给标准json模块。
```
def encoder(digest_obj)
return digest_obj.to_dict()
```
然后,将编码函数作为默认参数传递。
```
json.dumps(digest, default=encoder)
```


### API

`TDigest.`

- `update(x, w=1)`: 使用值`x`和权重`w`更新tdigest。
- `batch_update(x, w=1)`: 使用数组`x`中的值和权重`w`更新tdigest。
- `compress()`: 对底层数据结构执行压缩,这将缩小其内存占用,而不会损害准确性。在添加许多值之后执行此操作很有用。
- `percentile(p)`: 返回第`p`百分位数。例如:`p=50`是中位数。
- `cdf(x)`: 返回值`x`处的CDF。
- `trimmed_mean(p1, p2)`: 返回不包含低于`p1`和高于`p2`百分位数的值的数据集的均值。
- `to_dict()`: 返回TDigest及其内部质心值的Python字典。
- `update_from_dict(dict_values)`: 从序列化字典值更新TDigest对象。
- `centroids_to_list()`: 返回TDigest对象内部质心值的Python列表。
- `update_centroids_from_list(list_values)`: 从Python列表更新质心。







项目详情


下载文件

下载适合您平台的应用程序。如果您不确定选择哪一个,请了解有关安装包的更多信息。

源代码分布

tdigest-0.5.2.2.tar.gz (6.5 kB 查看哈希值)

上传时间 源代码

构建分布

tdigest-0.5.2.2-py3-none-any.whl (9.4 kB 查看哈希值)

上传时间 Python 3

tdigest-0.5.2.2-py2.py3-none-any.whl (9.4 kB 查看哈希值)

上传时间: Python 2 Python 3

由以下支持