pyspark lag function with inconsistent time series
import pyspark.sql.functions as F
from pyspark.sql.window import Window
I would like to use a window function to find the value from a column 4 periods ago.
Suppose my data (df) looks like this (in reality i have many different IDs):
ID | value | period
a | 100 | 1
a | 200 | 2
a | 300 | 3
a | 400 | 5
a | 500 | 6
a | 600 | 7
If the time series was consistent (e.g. period 1-6) I could just use F.lag(df['value'], count=4).over(Window.partitionBy('id').orderBy('period'))
However, because the time series has a discontinuity, the values would be displaced.
My desired output would be this:
ID | value | period | 4_lag_value
a | 100 | 1 | nan
a | 200 | 2 | nan
a | 300 | 3 | nan
a | 400 | 5 | 100
a | 500 | 6 | 200
a | 600 | 7 | 300
How can I do this in pyspark?
python pyspark pyspark-sql
add a comment |
import pyspark.sql.functions as F
from pyspark.sql.window import Window
I would like to use a window function to find the value from a column 4 periods ago.
Suppose my data (df) looks like this (in reality i have many different IDs):
ID | value | period
a | 100 | 1
a | 200 | 2
a | 300 | 3
a | 400 | 5
a | 500 | 6
a | 600 | 7
If the time series was consistent (e.g. period 1-6) I could just use F.lag(df['value'], count=4).over(Window.partitionBy('id').orderBy('period'))
However, because the time series has a discontinuity, the values would be displaced.
My desired output would be this:
ID | value | period | 4_lag_value
a | 100 | 1 | nan
a | 200 | 2 | nan
a | 300 | 3 | nan
a | 400 | 5 | 100
a | 500 | 6 | 200
a | 600 | 7 | 300
How can I do this in pyspark?
python pyspark pyspark-sql
add a comment |
import pyspark.sql.functions as F
from pyspark.sql.window import Window
I would like to use a window function to find the value from a column 4 periods ago.
Suppose my data (df) looks like this (in reality i have many different IDs):
ID | value | period
a | 100 | 1
a | 200 | 2
a | 300 | 3
a | 400 | 5
a | 500 | 6
a | 600 | 7
If the time series was consistent (e.g. period 1-6) I could just use F.lag(df['value'], count=4).over(Window.partitionBy('id').orderBy('period'))
However, because the time series has a discontinuity, the values would be displaced.
My desired output would be this:
ID | value | period | 4_lag_value
a | 100 | 1 | nan
a | 200 | 2 | nan
a | 300 | 3 | nan
a | 400 | 5 | 100
a | 500 | 6 | 200
a | 600 | 7 | 300
How can I do this in pyspark?
python pyspark pyspark-sql
import pyspark.sql.functions as F
from pyspark.sql.window import Window
I would like to use a window function to find the value from a column 4 periods ago.
Suppose my data (df) looks like this (in reality i have many different IDs):
ID | value | period
a | 100 | 1
a | 200 | 2
a | 300 | 3
a | 400 | 5
a | 500 | 6
a | 600 | 7
If the time series was consistent (e.g. period 1-6) I could just use F.lag(df['value'], count=4).over(Window.partitionBy('id').orderBy('period'))
However, because the time series has a discontinuity, the values would be displaced.
My desired output would be this:
ID | value | period | 4_lag_value
a | 100 | 1 | nan
a | 200 | 2 | nan
a | 300 | 3 | nan
a | 400 | 5 | 100
a | 500 | 6 | 200
a | 600 | 7 | 300
How can I do this in pyspark?
python pyspark pyspark-sql
python pyspark pyspark-sql
edited Nov 20 '18 at 13:51
Dan
asked Nov 20 '18 at 13:45
DanDan
858
858
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
I've come up with a solution, but it seems unnecessarily ugly, would welcome anything better!
data = spark.sparkContext.parallelize([
('a',100,1),
('a',200,2),
('a',300,3),
('a',400,5),
('a',500,6),
('a',600,7)])
df = spark.createDataFrame(data, ['id','value','period'])
window = Window.partitionBy('id').orderBy('period')
# look 1, 2, 3 and 4 rows behind:
for diff in [1,2,3,4]:
df = df.withColumn('{}_diff'.format(diff),
df['period'] - F.lag(df['period'], count=diff).over(window))
# if any of these are 4, that's the lag we need
# if not, there is no 4 period lagged return, so return None
#initialise col
df = df.withColumn('4_lag_value', F.lit(None))
# loop:
for diff in [1,2,3,4]:
df = df.withColumn('4_lag_value',
F.when(df['{}_diff'.format(diff)] == 4,
F.lag(df['value'], count=diff).over(window))
.otherwise(df['4_lag_value']))
# drop working cols
df = df.drop(*['{}_diff'.format(diff) for diff in [1,2,3,4]])
This returns the desired output.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394414%2fpyspark-lag-function-with-inconsistent-time-series%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I've come up with a solution, but it seems unnecessarily ugly, would welcome anything better!
data = spark.sparkContext.parallelize([
('a',100,1),
('a',200,2),
('a',300,3),
('a',400,5),
('a',500,6),
('a',600,7)])
df = spark.createDataFrame(data, ['id','value','period'])
window = Window.partitionBy('id').orderBy('period')
# look 1, 2, 3 and 4 rows behind:
for diff in [1,2,3,4]:
df = df.withColumn('{}_diff'.format(diff),
df['period'] - F.lag(df['period'], count=diff).over(window))
# if any of these are 4, that's the lag we need
# if not, there is no 4 period lagged return, so return None
#initialise col
df = df.withColumn('4_lag_value', F.lit(None))
# loop:
for diff in [1,2,3,4]:
df = df.withColumn('4_lag_value',
F.when(df['{}_diff'.format(diff)] == 4,
F.lag(df['value'], count=diff).over(window))
.otherwise(df['4_lag_value']))
# drop working cols
df = df.drop(*['{}_diff'.format(diff) for diff in [1,2,3,4]])
This returns the desired output.
add a comment |
I've come up with a solution, but it seems unnecessarily ugly, would welcome anything better!
data = spark.sparkContext.parallelize([
('a',100,1),
('a',200,2),
('a',300,3),
('a',400,5),
('a',500,6),
('a',600,7)])
df = spark.createDataFrame(data, ['id','value','period'])
window = Window.partitionBy('id').orderBy('period')
# look 1, 2, 3 and 4 rows behind:
for diff in [1,2,3,4]:
df = df.withColumn('{}_diff'.format(diff),
df['period'] - F.lag(df['period'], count=diff).over(window))
# if any of these are 4, that's the lag we need
# if not, there is no 4 period lagged return, so return None
#initialise col
df = df.withColumn('4_lag_value', F.lit(None))
# loop:
for diff in [1,2,3,4]:
df = df.withColumn('4_lag_value',
F.when(df['{}_diff'.format(diff)] == 4,
F.lag(df['value'], count=diff).over(window))
.otherwise(df['4_lag_value']))
# drop working cols
df = df.drop(*['{}_diff'.format(diff) for diff in [1,2,3,4]])
This returns the desired output.
add a comment |
I've come up with a solution, but it seems unnecessarily ugly, would welcome anything better!
data = spark.sparkContext.parallelize([
('a',100,1),
('a',200,2),
('a',300,3),
('a',400,5),
('a',500,6),
('a',600,7)])
df = spark.createDataFrame(data, ['id','value','period'])
window = Window.partitionBy('id').orderBy('period')
# look 1, 2, 3 and 4 rows behind:
for diff in [1,2,3,4]:
df = df.withColumn('{}_diff'.format(diff),
df['period'] - F.lag(df['period'], count=diff).over(window))
# if any of these are 4, that's the lag we need
# if not, there is no 4 period lagged return, so return None
#initialise col
df = df.withColumn('4_lag_value', F.lit(None))
# loop:
for diff in [1,2,3,4]:
df = df.withColumn('4_lag_value',
F.when(df['{}_diff'.format(diff)] == 4,
F.lag(df['value'], count=diff).over(window))
.otherwise(df['4_lag_value']))
# drop working cols
df = df.drop(*['{}_diff'.format(diff) for diff in [1,2,3,4]])
This returns the desired output.
I've come up with a solution, but it seems unnecessarily ugly, would welcome anything better!
data = spark.sparkContext.parallelize([
('a',100,1),
('a',200,2),
('a',300,3),
('a',400,5),
('a',500,6),
('a',600,7)])
df = spark.createDataFrame(data, ['id','value','period'])
window = Window.partitionBy('id').orderBy('period')
# look 1, 2, 3 and 4 rows behind:
for diff in [1,2,3,4]:
df = df.withColumn('{}_diff'.format(diff),
df['period'] - F.lag(df['period'], count=diff).over(window))
# if any of these are 4, that's the lag we need
# if not, there is no 4 period lagged return, so return None
#initialise col
df = df.withColumn('4_lag_value', F.lit(None))
# loop:
for diff in [1,2,3,4]:
df = df.withColumn('4_lag_value',
F.when(df['{}_diff'.format(diff)] == 4,
F.lag(df['value'], count=diff).over(window))
.otherwise(df['4_lag_value']))
# drop working cols
df = df.drop(*['{}_diff'.format(diff) for diff in [1,2,3,4]])
This returns the desired output.
answered Nov 20 '18 at 15:51
DanDan
858
858
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394414%2fpyspark-lag-function-with-inconsistent-time-series%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
