Pyspark style guide?

Pyspark code looks gross, especially when chaining multiple operations with dataframes. Anyone have some documented style guide for pyspark code specifically?

Posted Feb 1, 2020, 2:14 AM UTC

35
dutch_gecko•

Nothing official, but I use parentheses so that multiple line chaining looks decent:

df = (
    df
    .filter(F.col("value").isNotNull())
    .select(["name", "value"])
    .repartition(200)
    .cache()
)

You might also be interested in black, a formatting tool for Python that will create these kinds of chains for you (among many other things).

2
MrPowersAAHHH•

I wrote this blog post on chaining PySpark DataFrame transformations.

I also wrote a Spark Style guide, but it's for the Scala API.

Will use your post as motivation to create a PySpark style guide ;)

2
data_analistOP•

Your Scala style guide is great! I found it shortly after posting this actually. Thanks a ton for putting that together! Now I just need to convince my team to switch from Python...

2
MrPowersAAHHH•

Will put together a blog listing the pros / cons of Scala Spark & PySpark. Hopefully that'll help ;)

2
dgkrs•

Quite interested in this for many reasons. I know there's a lot of content out there covering similar pyspark vs scala topics, but the latest versions of Spark have been closing in on the gap between the two languages and a post from 2015 or even 2017 just doesn't do justice. Also they usually cover very common ETL tasks which is understandable, but don't touch on niche problems or niche things you can do.

Also alot of Spark scala vs PySpark articles are very superficial. I can't find topics on flow control in Scala vs PySpark.

I have a script that does a lot of iterative calculations and I wonder if implementing in Scala would speed it up? I reckon this is could be one of the reasons my script is slow. There's a condition set on the iterative calculation before it can move on to the next one. An if statement, and this back and forth between python is costing me. There's a technical debt with starting to write spark in Scala (in my team, as no one uses scala), so I'm struggling to find content that would support spending the time to learn it and refactor this part of the pipeline in Scala. Personally I would like to do it.

For context this script/function processes 1.5billion ish records and takes 40+ minutes, I have similar functions running on the same dataset but without iterative calcs taking 2-3 mins.

2
sirlucif3r•

Not sure if it's the right way, but I use black to format the code , as with any other Python code I have. Haven't had the need to treat it differently.

1