Úvod do PySpark DataFrames

Introduction to PySpark

Benjamin Schmidt

Data Engineer

O DataFrames

  • DataFrames: Tabulkový formát (řádky/sloupce)
  • Podporuje operace podobné SQL
  • Srovnatelný s Pandas DataFrame nebo SQL tabulkou
  • Strukturovaná data

DataFrames

Introduction to PySpark

Vytváření DataFrames ze souborů

# Create a DataFrame from CSV
census_df = spark.read.csv('path/to/census.csv', header=True, inferSchema=True)
Introduction to PySpark

Zobrazení DataFrame

# Show the first 5 rows of the DataFrame
census_df.show()


   age  education.num marital.status         occupation income
0   90              9        Widowed                  ?  <=50K
1   82              9        Widowed    Exec-managerial  <=50K
2   66             10        Widowed                  ?  <=50K
3   54              4       Divorced  Machine-op-inspct  <=50K
4   41             10      Separated     Prof-specialty  <=50K
Introduction to PySpark

Zobrazení schématu DataFrame

# Show the schema
census_df.printSchema()

Output: root |-- age: integer (nullable = true) |-- education.num: integer (nullable = true) |-- marital.status: string (nullable = true) |-- occupation: string (nullable = true) |-- income: string (nullable = true)
Introduction to PySpark

Základní analytika s PySpark DataFrames

# .count() will return the total row numbers in the DataFrame
row_count = census_df.count()
print(f'Number of rows: {row_count}')
# groupby() allows the use of sql-like aggregations
census_df.groupBy('gender').agg({'salary_usd': 'avg'}).show()

Další agregační funkce:

  • sum()
  • min()
  • max()
Introduction to PySpark

Klíčové funkce pro analytiku v PySparku

  • .select(): Vybere konkrétní sloupce z DataFrame
  • .filter(): Filtruje řádky podle podmínek
  • .groupBy(): Seskupí řádky podle jednoho či více sloupců
  • .agg(): Aplikuje agregační funkce na seskupená data
Introduction to PySpark

Příklad použití klíčových funkcí

# Using filter and select, we can narrow down our DataFrame
filtered_census_df = census_df.filter(df['age'] > 50).select('age', 'occupation')
filtered_census_df.show()

Output +---+------------------+ |age| occupation | +---+------------------+ | 90| ?| | 82| Exec-managerial| | 66| ?| | 54| Machine-op-inspct| +---+------------------+
Introduction to PySpark

Lass uns üben!

Introduction to PySpark

Preparing Video For Download...