cancel
Showing results for 
Search instead for 
Did you mean: 
Community Platform Discussions
Connect with fellow community members to discuss general topics related to the Databricks platform, industry trends, and best practices. Share experiences, ask questions, and foster collaboration within the community.
cancel
Showing results for 
Search instead for 
Did you mean: 

Why saving pyspark df always converting string field to number?

georgeyjy
New Contributor II

 

 

import pandas as pd

from pyspark.sql.types import StringType, IntegerType

from pyspark.sql.functions import col

 

save_path = os.path.join(base_path, stg_dir, "testCsvEncoding")

d = [{"code": "00034321"}, {"code": "55964445226"}]

df = pd.DataFrame(d)

spark_df = spark.createDataFrame(df)

spark_df.display()

field = "code"

spark_df = spark_df.withColumn(field, col(field).cast(StringType()))

spark_df.display()

spark_df.coalesce(1).write.mode('overwrite').format("csv").option("header", "true").option("encoding", "gbk").save(save_path)

 

 

example codes are as above, i am trying to convert pandas df to pyspark df, and then save data to a csv file, but somehow it always convert a string field to a number field in csv file as attached. Anyone can help?

1 ACCEPTED SOLUTION

Accepted Solutions

daniel_sahal
Esteemed Contributor

@georgeyjy 
Try opening the CSV as text editor. I bet that Excel is automatically trying to detect the schema of CSV thus it thinks that it's an integer.

View solution in original post

2 REPLIES 2

daniel_sahal
Esteemed Contributor

@georgeyjy 
Try opening the CSV as text editor. I bet that Excel is automatically trying to detect the schema of CSV thus it thinks that it's an integer.

Oh, that's it, i tried to open it in text editor and the result is correct.

Many thanks!

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you won’t want to miss the chance to attend and share knowledge.

If there isn’t a group near you, start one and help create a community that brings people together.

Request a New Group