Condividi tramite


asTable

Converte il dataframe in un TableArg oggetto , che può essere utilizzato come argomento di tabella in una funzione TVF (Table-Valued Function) incluso UDTF (User-Defined Table Function).

Sintassi

asTable()

Restituzioni

TableArg TableArg: oggetto che rappresenta un argomento di tabella.

Note

Dopo aver ottenuto un oggetto TableArg da un dataframe usando questo metodo, è possibile specificare il partizionamento e l'ordinamento per l'argomento tabella chiamando metodi come partitionBy, orderBye withSinglePartition nell'istanza TableArg di .

Examples

from pyspark.sql.functions import udtf

@udtf(returnType="id: int, doubled: int")
class DoubleUDTF:
    def eval(self, row):
        yield row["id"], row["id"] * 2

df = spark.createDataFrame([(1,), (2,), (3,)], ["id"])

result = DoubleUDTF(df.asTable())
result.show()
# +---+-------+
# | id|doubled|
# +---+-------+
# |  1|      2|
# |  2|      4|
# |  3|      6|
# +---+-------+

df2 = spark.createDataFrame(
    [(1, "a"), (1, "b"), (2, "c"), (2, "d")], ["key", "value"]
)

@udtf(returnType="key: int, value: string")
class ProcessUDTF:
    def eval(self, row):
        yield row["key"], row["value"]

result2 = ProcessUDTF(df2.asTable().partitionBy("key").orderBy("value"))
result2.show()
# +---+-----+
# |key|value|
# +---+-----+
# |  1|    a|
# |  1|    b|
# |  2|    c|
# |  2|    d|
# +---+-----+