apache-spark - Pyspark 数据帧写入和读取更改架构
问题描述
我有一个包含 string 和 int 列的 spark 数据框。
但是当我将数据框写入 csv 文件然后稍后加载时,所有列都作为字符串加载。
from pyspark.sql import SparkSession
spark = SparkSession.builder.enableHiveSupport().getOrCreate()
df = spark.createDataFrame([("Alberto", 2), ("Dakota", 2)],
["Name", "count"])
前:
df.printSchema()
输出:
root
|-- Name: string (nullable = true)
|-- count: long (nullable = true)
df.write.mode('overwrite').option('header', True).csv(filepath)
new_df = spark.read.option('header', True).csv(filepath)
后:
new_df.printSchema()
输出:
root
|-- Name: string (nullable = true)
|-- count: string (nullable = true)
如何在编写时指定存储模式?
解决方案
我们don't have to specify schema
在写的时候,但我们可以指定schema
读的时候。
Example:
from pyspark.sql.types import *
from pyspark.sql.functions import *
schema = StructType(
[
StructField('Name', StringType(), True),
StructField('count', LongType(), True)
]
)
#specify schema while reading
new_df = spark.read.schema(schema).option('header', True).csv(filepath)
new_df.printSchema()
#or else use inferschema option as true but specifying schema will be more robust
new_df = spark.read.option('header', True).option("inferSchema",True).csv(filepath)
推荐阅读
- java - 如何在不必先暂停的情况下重置 CountDownTimer
- java - 是否可以手动缓存整个网页?
- android - 位置侦听器始终返回 googpleplex 纬度和经度
- python - 为什么我的记分牌没有在 pygame 中更新?
- stm32 - 在QT中,当连接到STM32时,如何检测USB端口何时从串行模式切换到DFU
- json - 在另一个 json 中替换和添加 json
- netsuite - SuiteScript2.0 从保存的搜索公式列中获取值
- c++ - 如何用静态声明的不同大小的数组实例化一个类?
- ios - 键盘正在破坏 UICollectionView 的单元格
- python-3.x - TypeError: 'builtin_function_or_method' 和 'int' 的实例之间不支持'>='