python - Pyspark - 为数据框定义自定义模式
问题描述
我正在尝试读取 csv 文件,并尝试将其存储在数据框中,但是当我尝试创建ID
type 的列时StringType
,它并没有以预期的方式发生。
table_schema = StructType([StructField('ID', StringType(), True),
StructField('Name', StringType(), True),
StructField('Tax_Percentage(%)', IntegerType(), False),
StructField('Effective_From', TimestampType(), False),
StructField('Effective_Upto', TimestampType(), True)])
# CSV options
infer_schema = "true"
first_row_is_header = "true"
delimiter = ","
df = spark.read.format(file_type) \
.option("inferSchema", infer_schema) \
.option("header", first_row_is_header) \
.option("sep", delimiter) \
.option("schema", table_schema) \
.load(file_location)
display(df)
以下是运行上述代码后生成的架构:
df:pyspark.sql.dataframe.DataFrame
ID:integer
Name:string
Tax_Percentage(%):integer
Effective_From:string
Effective_Upto :string
尽管提供了自定义架构,但仍将其ID
键入到integer
我期望它为字符串的位置。与列Effective_From
和相同Effective_Upto
。
解决方案
它应该是
.schema(table_schema) \
代替
.option("schema", table_schema) \
.option("inferSchema", "true") \
此外,如果您提供架构定义,则不需要:)
推荐阅读
- android - 添加 android:required="false" 不会从 Google Play 控制台中删除
- python - 遍历目录时出现找不到文件错误
- php - 如何在 mysql 中使用 firebase 令牌?
- c# - ASP.NET MVC 删除函数不返回列表
- python - Elasticbeanstalk 上的 Flask-socketIO
- json - 从数组初始化的可解码
- python - Multiprocessing with Pool by lowering memory usage in worker
- python - How to convert a byte string into a list of tuples?
- google-apps-script - 我每天/每月可以调用多少次 url.fetch?(Какие есть ограничения по количеству url.fetch в день/месяц для google 应用程序脚本?)
- c++ - 带有 std::cout 的多线程控制台文本动画