我有一个具有特定模式的Spark数据框(Df1),我有另一个具有相同列但不同模式的数据帧.我知道如何一列接一列地做,但由于我有一大组专栏,所以它会相当长.为了保持数据帧之间模式的一致性,我想知道是否可以将一个模式应用到数据框中,或者创建一个函数来完成这项工作. 下面是一个例子

df1
root
|-- A: date (nullable = true)
 |-- B: integer (nullable = true)
 |-- C: string (nullable = true)

df2
root
 |-- A: string (nullable = true)
 |-- B: string (nullable = true)
 |-- C: string (nullable = true)`

我想将df1的模式复制到df2.如有任何意见和指示,我将不胜感激.

我在一篇专栏文章中try 了这种方法.考虑到我有大量的专栏,这将是一个相当长的方法.

df2 = df2.withColumn("B", df2["B"].cast('int'))

推荐答案

是的,100可以动态实现

df2.select(*[(col(x.name).cast(x.dataType)) for x in df1.schema.fields])

100

from pyspark.sql.functions import *
df1 = spark.createDataFrame([('2022-02-02',2,'a')],['A','B','C']).withColumn("A",to_date(col("A")))
print("df1 Schema")
df1.printSchema()
#df1 Schema
#root
# |-- A: date (nullable = true)
# |-- B: long (nullable = true)
# |-- C: string (nullable = true)

df2 = spark.createDataFrame([('2022-02-02','2','a')],['A','B','C'])
print("df2 Schema")
df2.printSchema()
#df2 Schema
#root
# |-- A: string (nullable = true)
# |-- B: string (nullable = true)
# |-- C: string (nullable = true)
#

#casting the df2 columns by getting df1 schema using select clause
df3 = df2.select(*[(col(x.name).cast(x.dataType)) for x in df1.schema.fields])
df3.show(10,False)
print("df3 Schema")
df3.printSchema()

#+----------+---+---+
#|A         |B  |C  |
#+----------+---+---+
#|2022-02-02|2  |a  |
#+----------+---+---+

#df3 Schema
#root
# |-- A: date (nullable = true)
# |-- B: long (nullable = true)
# |-- C: string (nullable = true)

在本例中,我用Integer,date,long types定义了df1.

100定义为string类型.

100是通过使用df2作为源数据并附加df1 schema来定义的.

Python相关问答推荐

如何将自动创建的代码转换为类而不是字符串?

如何在Pygame中绘制右对齐的文本?

如何在Power Query中按名称和时间总和进行分组

Docker-compose:为不同项目创建相同的容器

Python panda拆分列保持连续多行

强制venv在bin而不是收件箱文件夹中创建虚拟环境

Google Drive API获取文件计量数据

剧作家Python没有得到回应

如何使用Google Gemini API为单个提示生成多个响应?

为什么我的Python代码在if-else声明中的行之前执行if-else声明中的行?

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

创建可序列化数据模型的最佳方法

删除marplotlib条形图上的底边

实现神经网络代码时的TypeError

Tkinter菜单自发添加额外项目

如何在Python中使用另一个数据框更改列值(列表)

如何找出Pandas 图中的连续空值(NaN)?

关于两个表达式的区别

如何使用正则表达式修改toml文件中指定字段中的参数值