PySpark数据框Pandas UDF返回空数据框

时间:2020-05-17 19:21:34

标签: pandas dataframe apache-spark pyspark

我正在尝试使用pandas_udf方法对我的PySpark数据帧应用groupby('Key').apply(UDF)进行一些过滤。要使用pandas_udf,我定义了一个输出schema,并在列Number上设置了条件。例如,这里的简化思想是我只希望返回奇数ID的行中的Number

这现在带来一个问题,即有时组中没有奇数Number,因此UDF仅返回一个空的数据帧,该数据帧与定义的schema冲突以返回{{1 }} int

有没有一种方法可以解决此问题,只输出所有Number奇数行并将其合并为新的数据帧?

Number
schema = StructType([
        StructField("Key", StringType()),
        StructField("Number", IntegerType())
    ])

1 个答案:

答案 0 :(得分:1)

在某些组中,我遇到了带有空DataFrame的问题。我通过检查空的DataFrame并返回定义了架构的DataFrame来解决此问题:

if df_out.empty:
    # change the schema as needed
    return pd.DataFrame({'fullVisitorId': pd.Series([], dtype='str'),
                         'time': pd.Series([], dtype='datetime64[ns]'),
                         'total_transactions': pd.Series([], dtype='int')})
相关问题