Skip to main content
 首页 » 编程设计

python之如何根据数据类型识别列并在 pyspark 中转换它们

2024年09月03日31rubylouvre

我有一个如下所示的数据框

df = pd.DataFrame({ 
'date':['11/12/2001','11/12/2002','11/12/2003','11/12/2004','11/12/2005','11/12/2006'], 
'readings' : ['READ_1','READ_2','READ_1','READ_3','READ_4','READ_5'], 
 'val_date' :['21/12/2001','22/12/2002','23/12/2003','24/12/2004','25/12/2005','26/12/2006'], 
 }) 
spark_df = spark.createDataFrame(df) 
spark_df = spark_df.withColumn("date", spark_df["date"].cast(TimestampType())) 
spark_df = spark_df.withColumn("val_date", spark_df["val_date"].cast(TimestampType())) 

我有一个包含列数据类型的数据框,如上所示

我想做的是识别

a) 名称中包含术语date、time 并将其数据类型从Timestamp/Datetime 转换为string 的列

和

b) 根据Timestamp 或Datetime 数据类型识别列并将它们转换为string 类型

虽然下面的方法有效,但这并不优雅和高效。我有超过 3k 列,无法逐行执行此操作

spark_df = spark_df.withColumn("date", spark_df["date"].cast(StringType())) 
spark_df = spark_df.withColumn("val_date", spark_df["val_date"].cast(StringType())) 

我也试过下面但没有帮助

selected = [c.cast(StringType()) for c in spark_df.columns if ('date') in c]+['time'] 
spark_df.select(selected) 

有没有根据上面给出的条件 a 和 b 识别列并一次转换它们的方法?

您使用至少一种方法解决此问题的意见将很有帮助

请您参考如下方法:

您可以执行以下操作:

from pyspark.sql.functions import col 
 
schema = {col: col_type for col, col_type in df.dtypes} 
time_cols = [col for col, col_type in schema.items() if col_type in "timestamp date".split() or "date" in col or "time" in col] 
 
for column in time_cols: 
    df = df.withColumn(column, col(column).cast("string"))