MysterySpark
MysterySpark

Reputation: 35

Aggregate one column, but show all columns in select

I try to show maximum value from column while I group rows by date column.

So i tried this code

maxVal = dfSelect.select('*')\
            .groupBy('DATE')\
            .agg(max('CLOSE'))

But output looks like that:

+----------+----------+
|      DATE|max(CLOSE)|
+----------+----------+
|1987-05-08|     43.51|
|1987-05-29|    39.061|
+----------+----------+

I wanna have output like below

+------+---+----------+------+------+------+------+------+---+----------+
|TICKER|PER|      DATE|  TIME|  OPEN|  HIGH|   LOW| CLOSE|VOL|max(CLOSE)|
+------+---+----------+------+------+------+------+------+---+----------+
|   CDG|  D|1987-01-02|000000|50.666|51.441|49.896|50.666|  0|    50.666|
|   ABC|  D|1987-01-05|000000|51.441| 52.02|51.441|51.441|  0|    51.441|
+------+---+----------+------+------+------+------+------+---+----------+

So my question is how to change the code to have output with all columns and aggregated 'CLOSE' column?



Scheme of my data looks like below:

root
 |-- TICKER: string (nullable = true)
 |-- PER: string (nullable = true)
 |-- DATE: date (nullable = true)
 |-- TIME: string (nullable = true)
 |-- OPEN: float (nullable = true)
 |-- HIGH: float (nullable = true)
 |-- LOW: float (nullable = true)
 |-- CLOSE: float (nullable = true)
 |-- VOL: integer (nullable = true)
 |-- OPENINT: string (nullable = true)

Upvotes: 2

Views: 739

Answers (1)

Raghu
Raghu

Reputation: 1712

If you want the same aggregation all your columns in the original dataframe, then you can do something like,

import pyspark.sql.functions as F
expr = [F.max(coln).alias(coln) for coln in df.columns if 'date' not in coln] # df is your datafram
df_res = df.groupby('date').agg(*expr)

If you want multiple aggregations, then you can do like,

sub_col1 = # define
sub_col2=# define
expr1 = [F.max(coln).alias(coln) for coln in sub_col1 if 'date' not in coln]
expr2 = [F.first(coln).alias(coln) for coln in sub_col2 if 'date' not in coln]
expr=expr1+expr2
df_res = df.groupby('date').agg(*expr)

If you want only one of the columns aggregated and added to your original dataframe, then you can do a selfjoin after aggregating

df_agg = df.groupby('date').agg(F.max('close').alias('close_agg')).withColumn("dummy",F.lit("dummmy")) # dummy column is needed as a workaround in spark issues of self join
df_join = df.join(df_agg,on='date',how='left')

or you can use a windowing function

from pyspark.sql import Window
w= Window.partitionBy('date')
df_res = df.withColumn("max_close",F.max('close').over(w))

Upvotes: 2

Related Questions