cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results for 
Search instead for 
Did you mean: 

I want to split a dataframe with date range 1 week, with each week data in different column.

kkarthik
New Contributor

DF

Q Date(yyyy-mm-dd)

q1 2017-10-01

q2 2017-10-03

q1 2017-10-09

q3 2017-10-06

q2 2017-10-01

q1 2017-10-13

Q1 2017-10-02

Q3 2017-10-21

Q4 2017-10-17

Q5 2017-10-20

Q4 2017-10-31

Q2 2017-10-27

Q5 2017-10-01

Dataframe:

Q Count(week 1) Count(week 2) Count(week 3) Count(week 4) Avg(counts) Standard deviation of the counts

Q1 2 2 0 0 As applicable As applicable

Q2 2 0 0 1 “ “

Q3 1 0 1 0 “ “

Q4 0 0 1 1

Q5 1 0 1 0 “ “

1 REPLY 1

User16857281974
Contributor

It should just be a matter of applying the correct set of transformations:

At this stage the data will look something like this:

screenshot-10.png 

But the real trick is going to be to flatten it and all that should be required is to group by weekOfYear and then select with that the sum of each column (S,M,T,W,T,F,S) and that last call would look something like this:

df.groupBy("weekOfYear")
  .sum("Sun", "Mon","Tue", "Wed", "Thu", "Fri", "Sat")

--------------- UPDATE ------------

The solution involving sum(..) works if you have numerical data. However, if you have non-numerical data, we need a slightly different technique. In this case, we can still group by weekOfYear but instead of using sum(..) we can use agg(first(...), first(...), ...).

Thanks to Adam for the suggestion of using sum(..) and to @doug for the suggestion of using agg(first(..)).

As we were playing with this, I did put together a sample notebook that demonstrates both solutions .

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you won’t want to miss the chance to attend and share knowledge.

If there isn’t a group near you, start one and help create a community that brings people together.

Request a New Group