# basic information
sdf.printSchema()
# default 20
sdf.show(truncate = False, n = 1000)
# basic statistics
# count distinct
sdf.select(countDistinct("col1", "col2")).show()
# count rows
sdf.count()
# min or max
sdf.select(min(col('colname'))).show()
# data frame
sdf=spark.createDataFrame(df)
sdf.createTempView("sql_table")
sdf.createOrReplaceTempView("query_table")
sdf=sdf.cache() # efficient
sdf.toPandas().to_csv('sdf.csv', index = False) # without the number -indexing column
# distinct
sdf.select("col1", "col2", substring("col3", 1, 7)).distinct().show(10000)
# drop duplicates
wk_list = sdf.dropDuplicates(["WK"]).select("WK")
# drop a column
sdf = sdf.drop('sdf') # to avoid mistakes
# rename columns
sdf = sdf.withColumnRenamed("old_col", "new_col").withColumnRenamed("o_c", "n_c")
# add new coulumns
sdd = sdf.withColumn("col", lit(212))
# concat and substring
sdf= sdf.withColumn("mmyy", concat(substring(col('WK'), 5,2), substring(col('WK'), 3, 2)))
# filter
# isin, must be in list
sdf.filter(sdf.prod_name.isin(list(prod_list))).select("prod_type", "prod_name").distinct().show(10000)
# is Null
sdf.filter(col('prod_nbr').isNull()).agg(sum('num')).show()
# multiple conditions
product.filter((col('prod_nbr').isNull()) & (col('type') != 'I')).show(50)
# equal and not equal
sdf.filter(col('id')=='').count() #0
sdf.filter(col('id') == '000000').show()
sdf.filter(col('from_dt') != col('to_dt')).count()
# multiple conditions
# group by
sdf.filter(col('id').isNull()).agg(sum('num')).show()
agg = sdf.groupBy('col1', 'col2').agg(sum(col('num')).alias('num1'))
sdf.filter(col('id').isNull()).count()
# order by
agg = sdf.filter(col('id') !='').groupby('month_id').agg(countDistinct(col('col')).alias('num')).orderBy('month_id')
# join
# 2 equal signs
a = b.join(c, a.col_1 == b.col_2,'inner')
a = b.join(c,'col_name','inner') # common column name
# after join -> select all
a = b.join(c, b.WK == c.wk_1, "left").select(b["*"], c["Cycle_week"])
# union
a = b.union(c)
# reassign the data
a = b.withColumn("col_1",\
when(b["col_2"] == 'val', lit(None)).otherwise(b["col_3"]))
# date time
a = b.withColumn('Date',from_unixtime(unix_timestamp(col('from_dt')), "yyyy-MM-dd"))
a = b.withColumn("dayofweek", dayofweek('from_dt'))
# get the Friday, sunday as the first day for a single week
# switch other columns
# add date
a = a.withColumn('cyc_dt',when(col('dayofweek')==1,date_add(col('Date'),5)).\
otherwise(date_add(col('Date'),6)))
# unix timestamp
a = a.withColumn('Date',from_unixtime(unix_timestamp(col('from_dt')), "yyyy-MM-dd"))
# day of week
a = a.withColumn("dayofweek", dayofweek('from_dt'))
# to_date
a = a.withColumn('cyc_dt', to_date('Cycle_week'))
# write the data
a.write.mode("overwrite").saveAsTable("database.table")
sdf.toPandas().to_csv('file_name.csv', index = False)
sdf.repartition(1).write.mode('overwrite').csv('{}/SOME.D{}'.format('/user/u/a/', var_defined_earlier))
# read the data
sdf=spark.read.parquet('{}/file_name.parquet'.format(schema_defined_earlier))
# query
sdf = spark.sql("""select * from table """)
# pandas
# read in the data
df = pd.read_excel('file.xls', sheet_name = 'sheet', header = None)
df = pd.read_excel('file.xls', header = 0, converters = {'col':str}) #with header # zero leading, read as str
# unique values
wk_list_df['mmyy'].unique()
# sort values
wk = wk_list_df.sort_values(by = 'WK')
# aggregate
agg = df.groupBy('N', 'D').count()
# apply and lambda
a['cyc_dt'] = a['CYCLE_DATE'].apply(lambda x: datetime.strptime(x, "%d%b%Y")) # all upper
# fillna
b = a.fillna("NULL")
# zero leading
f_name_2022 = [str(i).zfill(3) for i in f_name_2022] # add zero leading
f_name_2022 = [*range(2, 360, 7)] # why * ?
chema = StructType([\
StructField("C", StringType(), True),\
StructField("cyc_dt", StringType(), True)\
])
# comment
# in the querey
# with /* */
# setting
from utilities.spark_init import spark_session
from utilities.date_func import date_func
from utilities.FTP_trans import logon,read_file
from pyspark.sql.functions import *
from pyspark.sql.window import *
from datetime import datetime, timedelta
from time import time
import numpy as np
import pandas as pd
import openpyxl
import xlrd #(!pip3 install xlrd)
import subprocess
from shlex import quote
from urllib import request # to request content through ftp protocol
import socket
import ftplib
import os
import shutil
import ctypes
from ftplib import FTP
from openpyxl.styles import Font, Color, Alignment, Border, Side
from dateutil.relativedelta import relativedelta, FR
from math import ceil
import pyodbc
import jaydebeapi
import openpyxl #(!pip3 install openpyxl)
from pyspark.sql.types import *
from pyspark import SQLContext
#Initialize Spark Session
spark_conf = {"spark.executor.memory": "12g",
"spark.executor.memoryOverhead": "3g",
"spark.dynamicAllocation.initialExecutors": 2,
"spark.driver.memory": "16g",
"spark.kryoserializer.buffer.max": "1g",
"spark.driver.cores": 32,
"spark.executor.cores": 8,
"spark.yarn.queue": "adhoc",
"spark.app.name": "CombModel",
"spark.dynamicAllocation.maxExecutors": 32}
spark = spark_session(spark_conf)
spark.sparkContext.setLogLevel('FATAL')
pyspark learning
最新推荐文章于 2024-07-19 12:37:36 发布