pyspark模式生成器
tinsel的Python项目详细描述
您的数据是您的模式
这个微型图书馆有助于克服手写星火的过度复杂性。 数据帧架构。怎么做?
将数据塑造为NamedTuple或数据类-它们可以自由混合:
from dataclasses import dataclass from tinsel import struct, transform from typing import NamedTuple, Optional, Dict, List @struct @dataclass class UserInfo: hobby: List[str] last_seen: Optional[int] pet_ages: Dict[str, int] @struct class User(NamedTuple): login: str age: int active: bool info: Optional[UserInfo]
将根节点(User在本例中)转换为模式:
schema = transform(User)
如有必要,创建一些数据:
data = [ User( login="Ben", age=18, active=False, info=None ), User( login="Tom", age=32, active=True, info=UserInfo( hobby=["pets", "flowers"], last_seen=16, pet_ages={"Jack": 2, "Sunshine": 6} ) ) ]
还有……喂!:
from pyspark.sql import SparkSession sc = SparkSession.builder.master('local').getOrCreate() df = sc.createDataFrame(data=data, schema=schema) df.printSchema() df.show(truncate=False)
这将输出:
root |-- login: string (nullable = false) |-- age: integer (nullable = false) |-- active: boolean (nullable = false) |-- info: struct (nullable = true) | |-- hobby: array (nullable = false) | | |-- element: string (containsNull = false) | |-- last_seen: integer (nullable = true) | |-- pet_ages: map (nullable = false) | | |-- key: string | | |-- value: integer (valueContainsNull = false) +-----+---+------+----------------------------------------------+ |login|age|active|info | +-----+---+------+----------------------------------------------+ |Ben |18 |false |null | |Tom |32 |true |[[pets, flowers],, [Jack -> 2, Sunshine -> 6]]| +-----+---+------+----------------------------------------------+
功能
- 使用本机python类型;没有额外的dsl,没有神秘的api-只是简单的python;
- 小巧快捷;
- 为python中缺少的某些类型提供类型垫片,例如long或short;
- 可空字段自然适合模式定义;
0.2.0(2018-08-28)
- 添加了数据类支持
0.1.0(2018-08-28)
- pypi上的第一个版本。