para_csv
Converte uma coluna contendo StructType em strings CSV . Lança uma exceção no caso de um tipo não suportado.
Sintaxe
Python
from pyspark.sql import functions as sf
sf.to_csv(col, options=None)
Parâmetros
Parâmetro | Tipo | Descrição |
|---|---|---|
|
| Nome da coluna que contém uma estrutura. |
| dicionário, opcional | Opções para controlar a conversão. Aceita as mesmas opções que a fonte de dados CSV. |
Devoluções
pyspark.sql.Column: Uma string CSV convertida a partir de StructType fornecido.
Exemplos
Exemplo 1 : Convertendo um StructType simples em strings CSV
Python
from pyspark.sql import Row, functions as sf
data = [(1, Row(age=2, name='Alice'))]
df = spark.createDataFrame(data, ("key", "value"))
df.select(sf.to_csv(df.value)).show()
Output
+-------------+
|to_csv(value)|
+-------------+
| 2,Alice|
+-------------+
Exemplo 2 : Convertendo um StructType complexo em strings CSV
Python
from pyspark.sql import Row, functions as sf
data = [(1, Row(age=2, name='Alice', scores=[100, 200, 300]))]
df = spark.createDataFrame(data, ("key", "value"))
df.select(sf.to_csv(df.value)).show(truncate=False)
Output
+-------------------------+
|to_csv(value) |
+-------------------------+
|2,Alice,"[100, 200, 300]"|
+-------------------------+
Exemplo 3 : Convertendo um StructType com valores nulos em strings CSV
Python
from pyspark.sql import Row, functions as sf
from pyspark.sql.types import StructType, StructField, IntegerType, StringType
data = [(1, Row(age=None, name='Alice'))]
schema = StructType([
StructField("key", IntegerType(), True),
StructField("value", StructType([
StructField("age", IntegerType(), True),
StructField("name", StringType(), True)
]), True)
])
df = spark.createDataFrame(data, schema)
df.select(sf.to_csv(df.value)).show()
Output
+-------------+
|to_csv(value)|
+-------------+
| ,Alice|
+-------------+
Exemplo 4 : Convertendo um StructType com diferentes tipos de dados em strings CSV
Python
from pyspark.sql import Row, functions as sf
data = [(1, Row(age=2, name='Alice', isStudent=True))]
df = spark.createDataFrame(data, ("key", "value"))
df.select(sf.to_csv(df.value)).show()
Output
+-------------+
|to_csv(value)|
+-------------+
| 2,Alice,true|
+-------------+