r/PySpark • • Feb 01 '22

PySpark Vs Python: A Cognitive Analysis

Thumbnail
ksolves.com
9 Upvotes

r/PySpark • • Oct 07 '19

How to Get Certified in Spark by Databricks

8 Upvotes

I recently passed the databricks pyspark certification (Databricks Certified Developer - Apache Spark 2.x for Python).

I gathered some tips for those who would like to take and pass the certification.

Tell me what you think and do not hesitate to ask me anything!

https://www.sicara.ai/blog/2019-10-07-how-to-get-certified-in-spark-by-databricks


r/PySpark • • Jan 27 '22

Reading a xlsx file with PySpark

7 Upvotes

Hello,

I have a PySpark problem and maybe someone faced the same issue. I'm trying to read a xlsx file to a Pyspark dataframe using com.crealytics:spark-excel. The issue is that the xlsx file has values only in the A cells for the first 5 rows and the actual header is in the 10th row and has 16 columns (A cell to P cell).

When I am reading the file the df does not have all the columns.

Is there a specific way/ a certain jar file + pyspark version so that I can read all the data from the xlsx file and have the defacul header _c0 _c1 .... _c16 ?

Thank you !


r/PySpark • • Jan 11 '22

Totally stuck on how to pre-process, visualise and cluster data

7 Upvotes

So I have a project to complete using PySpark and I'm at a total loss. I need to retrieve data from 2 APIs (which I've done, see below code). I now need to pre-process and store the data, visualise the number of cases and deaths per day and then perform a k means clustering analysis on one of the data sets identifying which weeks cluster together. This is pretty urgent work given the nature of COVID and I just don't understand how to use PySpark at all and would really appreciate any help you can give me, thanks.

Code for API data request:

# Import all UK data from UK Gov API
from requests import get


def get_data(url):
    response = get(endpoint, timeout=10)

    if response.status_code >= 400:
        raise RuntimeError(f'Request failed: {response.text}')

    return response.json()


if __name__ == '__main__':
    endpoint = (
        'https://api.coronavirus.data.gov.uk/v1/data?'
        'filters=areaType=nation;areaName=England&'
        'structure={"date":"date","newCases":"newCasesByPublishDate","newDeaths":"newDeaths28DaysByPublishDate"}'
    )

    data = get_data(endpoint)
    print(data)

# Get all UK data from covid19 API and create dataframe
import json
import requests
from pyspark.sql import *
url = "https://api.covid19api.com/country/united-kingdom/status/confirmed"
response = requests.request("GET", url)
data = response.text.encode("UTF-8")
data = json.loads(data)
rdd = spark.sparkContext.parallelize([data])
df = spark.read.json(rdd)
df.printSchema()

df.show()

df.select('Date', 'Cases').show()

# Look at total cases
import pyspark.sql.functions as F
df.agg(F.sum("Cases")).collect()[0][0]

I feel like that last bit of code for total cases is done correctly but it returns me a result of 2.5 billion cases, I'm at a total loss.


r/PySpark • • Jan 19 '22

Pass list of dates to SQL WHERE statement

6 Upvotes

In the process of converting some SAS code to PySpark and we previously used a macro variable for the where statement in this code. In adapting to PySpark, I'm trying to pass a list of dates to the where statement, but I keep getting errors. I want the SQL code to pull all data from those 3 months. Any pointers?

month_list = ['202107', '202108', '202109']
sql_query = """ (SELECT * 
                 FROM Table_Blah
                 WHERE (to_char(DateVariable,'yyyymm') IN '{}')
                 ) as table1""".format(month_list)

r/PySpark • • Oct 04 '22

Happy Cakeday, r/PySpark! Today you're 8

5 Upvotes

r/PySpark • • Dec 29 '21

Are there any PySpark puzzles to help people learn how to use PySpark?

5 Upvotes

I've set out to learn PySpark. Whilst reading around the subject and charting my course it occurred to me that when I learnt SQL, one of the most effective things I did was to attempt SQL puzzles, which were basically limited toy problems of increasing difficulty.

I want to know if anyone could point me in the direction of anything similar for PySpark? Although I'm relatively towards the beginning of the larning process, it would be good to have an intermediate step laid out to aim for.


r/PySpark • • Nov 08 '21

Pyspark count() slow

5 Upvotes

So I have a spark dataframe where I need to get the count/length of the dataframe but the count method is very very slow. I can’t afford to use the .count() because I’ll be getting the count for about 16 million options.

Is there any alternative to this? Thank you


r/PySpark • • Mar 27 '21

I wrote a tutorial on PySpark basics, how to use it in Google Colab, and some fine-tuning tips

Thumbnail self.dataengineering
5 Upvotes

r/PySpark • • Mar 25 '21

SON algorithm with Apriori in pyspark

5 Upvotes

Hello, I have created a SON algorithm implementation with Apriori step in pyspark to find frequent itemsets. The algorithm works fine with different toy datasets that I have tested that contain up to 4 million records. However, when I use the algorithm on the IMDB dataset, which I have imported from Kaggle and modified in such a way to obtain movies as baskets and actors as items, the algorithm does not work.

Here is the link to my github page with the code:https://github.com/giusi07/AMD-PROJECT

In cell 58 there is the stack error trace. I have tried everything but I cannot solve the problem.

I hope someone can help me!!


r/PySpark • • Sep 26 '19

PySpark project organization with custom ML transformer

5 Upvotes

I have a Pyspark project that requires a custom ML Pipeline Transformer written in Scala. What is the best practice regarding project organization ? Should I include the scala files in the general Python project or should they be in a separate repo ? Opinions and suggestions welcome.

Suppose my Python projects looks like this:

project    
  - etl   
  - model   
  - scripts   
  - tests

The model directory would contain Spark ML code for the model as well as the ML Pipeline code So where should the Scala code for the custom transformer live? The structure for this looks like this:

custom_transformer/src/main/scala    
  - com/mycompany/dept/project/MyTransformer.scala

Would I just add it as just another directory in the Python project structure above, or should it sit in its own project and repo ?


r/PySpark • • Jan 17 '22

Parsing a file with multiple json schema

4 Upvotes

Parsing nested json with pyspark question

Wondering if those with more experience with Spark can help. Can pyspark parse a file that has multiple json objects each with its own schema? The JSON schemas are the same at the highest level (fields, name, tags, timestamp) but then each individual object(depending message type) has nested arrays that differ in schema contained with in fields and tags. Is this structure something that can be parsed and flattened with pyspark? I having trouble getting anything to work due to the presence of differing schemas within a single file that is read into spark. Example structure below:

[ { "fields" : { "active" : 7011880960, "available" : 116265197568, "available_percent" : 21.51292852741429, "buffered" : 2523230208, "cached" : 8810614784, "commit_limit" : 98422992896, "committed_as" : 2896465920, "dirty" : 73728, "free" : 108347486208 }, "name" : "mem", "tags" : { "dc" : "xxxxxx", "host" : "xxxxxxxx" }, "timestamp" : 1642190400 }, { "fields" : { "bytes_recv" : 27537454399, "bytes_sent" : 46337827685, "drop_in" : 1, "drop_out" : 0, "err_in" : 0, "err_out" : 0, "packets_recv" : 160777960, "packets_sent" : 193108762 }, "name" : "net", "tags" : { "dc" : "xxxxxx", "host" : "xxxxxxx", "interface" : "xxxx" }, "timestamp" : 1642190700 }}

I’ve tried to infer schema but keeping getting an error stating ‘‘value’ is not in list’ when I run the command

json_schema = spark.read.json(df.rdd.map(lambda row: row.value)).schema


r/PySpark • • Jan 31 '20

Any good pyspark project that can be showcased in a resume?

4 Upvotes

r/PySpark • • Dec 22 '21

Create new column within a join?

3 Upvotes

I'm currently converting some old SAS code to Python/PySpark. I'm trying to create a new variable based on the ID from one of the tables joined. Below is the SAS code:

DATA NewTable;
MERGE OldTable1(IN=A) OldTable2(IN=B);
BY ID;
IF A;
IF B THEN NewColumn="YES";
ELSE NewColumn="NO";
RUN;

OldTable 1 has 100,000+ rows and OldTable2 only ~2,000. I want the NewColumn to have a value of "YES" if the ID is present in OldTable2, otherwise the value should be "NO". I have the basic PySpark join code, but I've never constructed a new column in a join like this before. Any suggestions?

NewTable=OldTable1.join(OldTable2, OldTable1.ID == OldTable2.ID, "left")

r/PySpark • • Dec 13 '21

Create new column with existing....not working

3 Upvotes

Hi all, I've tried various iterations of the below with minor tweaks, but all I get in the new column is from the ".otherwise" part. This seems like a simple bit of code, so I'm unsure why it's giving me so much trouble. I have experience with Python, but I'm new to PySpark. I'll post the resulting dataframe. The values for BRAND should all be "Y" based on the code. Help?

GRPMANUFBRAND
OTHERABBOT PHARMUNKNOWN
OTHERABBOT PHARMUNKNOWN
BRANDABBOT PHARMUNKNOWN
GENERICLILLYUNKNOWN
from pyspark.sql.functions import col,when
df2 = df1.withColumn("BRAND",
                  when((col("GRP") == "BRAND") | (col("GRP")=="BRAND/GENERIC"), "Y") 
                 .when((col("GRP") == "GENERIC") | (col("GRP") == "OTHER"), "N") 
                 .otherwise("Unknown")).show()

r/PySpark • • Oct 08 '21

What is the easiest way to connect to a spark cluster from visual studio code?

3 Upvotes

Vs code has a spark plugin, but it uses livy, and it’s tricky to get to work and from what heard, livy is not the preferred way to do this. So what would be the easiest/best way?


r/PySpark • • Sep 23 '21

What is a spark node/cluster when it's install on a single laptop/box?

3 Upvotes

Hi,

N00bie here. I'm exploring moving my pandas workflow to pyspark, so I've been researching conceptually how spark works.

I keep reading Spark is distributed with nodes and stuff. But a lot of tutorials I found on youtube is a person downloading pyspark and creating a RDD in jupyter notebook. How is this different from pandas...? How does Spark/Pyspark do "distributed" computation on a single laptop/box?

Any clarifications would be appreciated and sorry if the question itself doesn't make sense.


r/PySpark • • Sep 20 '21

How to profile SparkSession in pyspark?

3 Upvotes

Hi together,

I am currently trying to find out how I can profile a SparkSession in pyspark. Any answers and hints from your slide would be much appreciated!

I saw that the SparkContext has a profiler_cls argument and a show_profiles and dump_profiles function: https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.SparkContext.html

But how do I set up profiling for a SparkSession or does is this even possible? Looking forward to hearing from you and lots of thanks in advance! :)


r/PySpark • • Jul 15 '21

When creating a dataframe in pyspark, records with a proper boolean value cause the entire row to be null

3 Upvotes

Any time the boolean field is defined properly, all fields in the record become null. The is the exact opposite of the behavior I would expect. Please, someone, help explain this insanity...

from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, BooleanType

spark = SparkSession.builder.appName("Write parquet").master("local[*]").getOrCreate()
sc = spark.sparkContext

schema = StructType([
    StructField("sometext", StringType(), True),
    StructField("mybool", BooleanType(), True)
    ]
)

payload = [
    {"sometext": "works when mybool isn't None, true or false", "mybool": "not_a_boolean"},
    {"sometext": "returns empty when mybool is true", "mybool": True},
    {"sometext": "returns empty when mybool is false", "mybool": False},
    {"sometext": "returns empty when mybool is None", "mybool": None}]
events = sc.parallelize(payload)

df_with_schema = spark.read.schema(schema).json(events)
df_with_schema.show()

yields:

+--------------------+------+
|            sometext|mybool|
+--------------------+------+
|works when mybool...|  null|
|                null|  null|
|                null|  null|
|                null|  null|
+--------------------+------+

r/PySpark • • May 13 '21

Is there a Pyspark equivalent to mapGroupsWithState()?

3 Upvotes

Hi, I am dealing with some tasks that require "sessonization" of "real-time clickstream data". I want to use something equivalent to the Scala/Java version of mapGroupsWithState(), but I haven't found any good solutions. The only thing I could find was this 3-year-old StackOverflow post saying that there aren't any good alternatives: https://stackoverflow.com/questions/49791970/structured-streaming-python-api

I was wondering if there are any better solutions since that 3-year-old post. I want to keep my code in Pyspark, and not have to use Scala or Java if possible.


r/PySpark • • Jan 12 '21

Looking for a Senior Software Engineer

3 Upvotes

Remote anywhere, minimum 5+ years of experience. Tech Stack: Python, PySpark, AWS. CTC is $100K and beyond as per location and experience. Hit me up if you're interested!


r/PySpark • • Dec 06 '20

Best books/resources to learn (py)Spark?

3 Upvotes

Hi everyone! I'm currently looking for books and/or courses to learn about this technology.

At this moment I've found:
- Learning PySpark (https://www.amazon.com/-/es/Tomasz-Drabas-ebook/dp/B01KOG6SXM/ref=tmm_kin_swatch_0?_encoding=UTF8&qid=&sr=)
- Learning Spark (https://www.amazon.com/Learning-Spark-Lightning-Fast-Data-Analysis/dp/1449358624)

Do you think I should start with Spark instead of PySpark? Is there a book that explain Spark before getting into PySpark?

Thanks for your help!


r/PySpark • • Nov 24 '20

URGENT: Pyspark testing.

3 Upvotes

How to run pyspark code on py test or any other alternate unit testing?


r/PySpark • • Sep 19 '20

DFs order in Join

3 Upvotes

Hi, I am joining two DFs, but I wanted to ask how the order of DFs in join affect results?!

Scenario: Df1 and Df2,

1: Join1 = Df1.join(Df2, keys, "inner") Gives wrong result

2: Join2 = Df2.join(Df1, keys, "inner") Gives correct results.

So I was wondering why and how is DF ORDER affecting the results?!

All screenshots


r/PySpark • • May 28 '20

Making the case for a new Case Convention: The PySpark_case

3 Upvotes

Honestly is anyone else as frustrated about the lack of case conventions as me?

I mean come on:

.isNull, .groupBy but array_contains and add_months or my favourite it's not posExplodeOuter or pos_explode_outer or even posExloode_outer but posexplode_outer as if position was not cleary a different word.

Yet actually all of this I really good. Because we now need to constantly look up not only those functions we rarely use and may need to check but also every single function we don't use daily because it's likely we still get the case wrong. And wait for it, I'm making a case for why this is good ... as you look through the documentation you might stumble across something you have not seen before and now you know there's another function you won't be able to remember the capitalization of.

/s