# Transbigdata Preprocess

> 使用 TransBigData 进行数据预处理与质量评估。适用于数据质量检查、采样间隔分析、边界过滤、ID重编号等任务。

- Skill: `ni1o1/transbigdata-preprocess` (Agent Skill)
- Install (CLI): `npx skillmds@latest add ni1o1/transbigdata-preprocess`
- Raw SKILL.md: https://api.skillmd.com/api/skills/ni1o1/transbigdata-preprocess/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: ni1o1 (https://skillmd.com/u/ni1o1)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/ni1o1/transbigdata-preprocess

---


# TransBigData 数据预处理指南

## 安装

```bash
pip install transbigdata
```

## 数据质量评估

### 1. 数据概览 - `data_summary()`

输出数据集的基本统计信息。

```python
import transbigdata as tbd

tbd.data_summary(
    data,
    col=['VehicleNum', 'Time'],
    show_sample_duration=True,
    roundnum=2
)
```

**输出内容**:
- 数据记录数
- 车辆/设备数
- 时间范围
- 采样间隔分布

### 2. 采样间隔分析 - `sample_duration()`

计算每条记录与前一条的时间间隔。

```python
data_with_duration = tbd.sample_duration(
    data,
    col=['VehicleNum', 'Time']
)
# 返回包含 'duration' 列的 DataFrame（单位：秒）
```

## 数据过滤

### 3. 边界框过滤 - `clean_outofbounds()`

根据矩形边界过滤数据。

```python
# 只保留研究范围内的数据
bounds = [113.75, 22.4, 114.62, 22.86]  # [lon_min, lat_min, lon_max, lat_max]

data_clean = tbd.clean_outofbounds(
    data,
    bounds=bounds,
    col=['Lng', 'Lat']
)
```

### 4. 多边形过滤 - `clean_outofshape()`

根据任意形状的地理边界过滤数据。

```python
import geopandas as gpd

# 加载研究区域边界
area = gpd.read_file('study_area.shp')

data_clean = tbd.clean_outofshape(
    data,
    shape=area,
    col=['Lng', 'Lat'],
    accuracy=500  # 栅格精度，值越小越精确
)
```

## ID 重编号

### 5. 按时间间隔重编号 - `id_reindex()`

当同一ID的记录时间间隔过大时，视为不同个体。

```python
data_reindex = tbd.id_reindex(
    data,
    col='VehicleNum',
    timegap=7200,        # 时间阈值（秒），超过则分配新ID
    timecol='Time',
    new=False,           # False: 保持相同ID索引一致
    suffix='_new'
)
```

### 6. 按距离间隔重编号 - `id_reindex_disgap()`

当同一ID的相邻记录距离过大时，视为不同个体。

```python
data_reindex = tbd.id_reindex_disgap(
    data,
    col='VehicleNum',
    disgap=1000,         # 距离阈值（米）
    suffix='_new'
)
```

## 完整示例：数据预处理流程

```python
import pandas as pd
import geopandas as gpd
import transbigdata as tbd

# 1. 加载数据
data = pd.read_csv('gps_data.csv')
data['Time'] = pd.to_datetime(data['Time'])

# 2. 数据质量检查
print("=== 数据概览 ===")
tbd.data_summary(data, col=['VehicleNum', 'Time'])

# 3. 添加采样间隔列
data = tbd.sample_duration(data, col=['VehicleNum', 'Time'])
print(f"采样间隔统计: 均值={data['duration'].mean():.1f}秒, 中位数={data['duration'].median():.1f}秒")

# 4. 边界过滤（深圳范围）
bounds = [113.75, 22.4, 114.62, 22.86]
data = tbd.clean_outofbounds(data, bounds=bounds, col=['Lng', 'Lat'])
print(f"边界过滤后: {len(data)} 条记录")

# 5. ID重编号（处理长时间断点）
data = tbd.id_reindex(data, col='VehicleNum', timegap=3600, timecol='Time')
print(f"重编号后车辆数: {data['VehicleNum_new'].nunique()}")

# 6. 保存处理后的数据
data.to_csv('gps_data_cleaned.csv', index=False)
```

## 使用建议

1. **先检查后处理**: 使用 `data_summary()` 了解数据质量
2. **边界过滤顺序**: 先用边界框快速过滤，再用多边形精确过滤
3. **ID重编号**:
   - 出租车数据通常用时间间隔（2小时）
   - 手机信令数据可能需要用距离间隔
4. **采样间隔**: 了解数据采样频率有助于后续参数设置

## 参考文档

- 数据质量: https://transbigdata.readthedocs.io/en/latest/quality.html
- 数据预处理: https://transbigdata.readthedocs.io/en/latest/preprocess.html

