Pandas: Outer join with a specified range of difference between the keys












0















I want to perform outer join on two data frames where the keys are id: int and date: pd.Timestamp objects. On top of that, I want the keys to be considered as equal if the ids are the same (the normal behaviour) and the dates are either equal (the normal behaviour) or the difference between the dates is maximum 30 days. Then, when the outer join is performed, the date from the right data frame should be taken. An example is included below:



left = pd.DataFrame({"id": [1, 2, 3], "date": [pd.Timestamp(2002, 3, 25), pd.Timestamp(2003, 4, 4), pd.Timestamp(2004, 6, 6)], "val_3": [77, 88, 11]})

right = pd.DataFrame({"id": [1, 2, 3], "date": [pd.Timestamp(2002, 3, 10), pd.Timestamp(2003, 4, 27), pd.Timestamp(2004, 5, 5)], "val_1": [99, 66, 33], "val_2": [101, 102, 103]})


And the result after the join should be:



result = pd.DataFrame({"id": [1, 2, 3, 3], "date": [pd.Timestamp(2002, 3, 10), pd.Timestamp(2003, 4, 27), pd.Timestamp(2004, 6, 6), pd.Timestamp(2004, 5, 5)], "val_3": [77, 88, 11, np.nan], "val_1": [99, 66, np.nan, 33], "val_2": [101, 102, np.nan, 103]})


Looking forward to your answers!










share|improve this question























  • What should happen if 2 dates in the right frame fall within 30 days of one date in the left frame for the same id? Should we get 2 rows for the date in the left frame, or do we take only the first or last date within that 30 day window?

    – ALollz
    Jan 3 at 19:41


















0















I want to perform outer join on two data frames where the keys are id: int and date: pd.Timestamp objects. On top of that, I want the keys to be considered as equal if the ids are the same (the normal behaviour) and the dates are either equal (the normal behaviour) or the difference between the dates is maximum 30 days. Then, when the outer join is performed, the date from the right data frame should be taken. An example is included below:



left = pd.DataFrame({"id": [1, 2, 3], "date": [pd.Timestamp(2002, 3, 25), pd.Timestamp(2003, 4, 4), pd.Timestamp(2004, 6, 6)], "val_3": [77, 88, 11]})

right = pd.DataFrame({"id": [1, 2, 3], "date": [pd.Timestamp(2002, 3, 10), pd.Timestamp(2003, 4, 27), pd.Timestamp(2004, 5, 5)], "val_1": [99, 66, 33], "val_2": [101, 102, 103]})


And the result after the join should be:



result = pd.DataFrame({"id": [1, 2, 3, 3], "date": [pd.Timestamp(2002, 3, 10), pd.Timestamp(2003, 4, 27), pd.Timestamp(2004, 6, 6), pd.Timestamp(2004, 5, 5)], "val_3": [77, 88, 11, np.nan], "val_1": [99, 66, np.nan, 33], "val_2": [101, 102, np.nan, 103]})


Looking forward to your answers!










share|improve this question























  • What should happen if 2 dates in the right frame fall within 30 days of one date in the left frame for the same id? Should we get 2 rows for the date in the left frame, or do we take only the first or last date within that 30 day window?

    – ALollz
    Jan 3 at 19:41
















0












0








0








I want to perform outer join on two data frames where the keys are id: int and date: pd.Timestamp objects. On top of that, I want the keys to be considered as equal if the ids are the same (the normal behaviour) and the dates are either equal (the normal behaviour) or the difference between the dates is maximum 30 days. Then, when the outer join is performed, the date from the right data frame should be taken. An example is included below:



left = pd.DataFrame({"id": [1, 2, 3], "date": [pd.Timestamp(2002, 3, 25), pd.Timestamp(2003, 4, 4), pd.Timestamp(2004, 6, 6)], "val_3": [77, 88, 11]})

right = pd.DataFrame({"id": [1, 2, 3], "date": [pd.Timestamp(2002, 3, 10), pd.Timestamp(2003, 4, 27), pd.Timestamp(2004, 5, 5)], "val_1": [99, 66, 33], "val_2": [101, 102, 103]})


And the result after the join should be:



result = pd.DataFrame({"id": [1, 2, 3, 3], "date": [pd.Timestamp(2002, 3, 10), pd.Timestamp(2003, 4, 27), pd.Timestamp(2004, 6, 6), pd.Timestamp(2004, 5, 5)], "val_3": [77, 88, 11, np.nan], "val_1": [99, 66, np.nan, 33], "val_2": [101, 102, np.nan, 103]})


Looking forward to your answers!










share|improve this question














I want to perform outer join on two data frames where the keys are id: int and date: pd.Timestamp objects. On top of that, I want the keys to be considered as equal if the ids are the same (the normal behaviour) and the dates are either equal (the normal behaviour) or the difference between the dates is maximum 30 days. Then, when the outer join is performed, the date from the right data frame should be taken. An example is included below:



left = pd.DataFrame({"id": [1, 2, 3], "date": [pd.Timestamp(2002, 3, 25), pd.Timestamp(2003, 4, 4), pd.Timestamp(2004, 6, 6)], "val_3": [77, 88, 11]})

right = pd.DataFrame({"id": [1, 2, 3], "date": [pd.Timestamp(2002, 3, 10), pd.Timestamp(2003, 4, 27), pd.Timestamp(2004, 5, 5)], "val_1": [99, 66, 33], "val_2": [101, 102, 103]})


And the result after the join should be:



result = pd.DataFrame({"id": [1, 2, 3, 3], "date": [pd.Timestamp(2002, 3, 10), pd.Timestamp(2003, 4, 27), pd.Timestamp(2004, 6, 6), pd.Timestamp(2004, 5, 5)], "val_3": [77, 88, 11, np.nan], "val_1": [99, 66, np.nan, 33], "val_2": [101, 102, np.nan, 103]})


Looking forward to your answers!







python pandas outer-join






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 3 at 19:30









gorjangorjan

1,450615




1,450615













  • What should happen if 2 dates in the right frame fall within 30 days of one date in the left frame for the same id? Should we get 2 rows for the date in the left frame, or do we take only the first or last date within that 30 day window?

    – ALollz
    Jan 3 at 19:41





















  • What should happen if 2 dates in the right frame fall within 30 days of one date in the left frame for the same id? Should we get 2 rows for the date in the left frame, or do we take only the first or last date within that 30 day window?

    – ALollz
    Jan 3 at 19:41



















What should happen if 2 dates in the right frame fall within 30 days of one date in the left frame for the same id? Should we get 2 rows for the date in the left frame, or do we take only the first or last date within that 30 day window?

– ALollz
Jan 3 at 19:41







What should happen if 2 dates in the right frame fall within 30 days of one date in the left frame for the same id? Should we get 2 rows for the date in the left frame, or do we take only the first or last date within that 30 day window?

– ALollz
Jan 3 at 19:41














1 Answer
1






active

oldest

votes


















0














I think merge on 'id' and then split the DataFrame as needed if the date doesn't fall within 30 days



import pandas as pd

# Rename so it's easier to split columns later
left = left.rename(columns={'date': 'date_l'})

m = left.merge(right, on='id', how='outer')
mask = m.date >= m.date_l - pd.Timedelta(days=30)

pd.concat([
m[mask].drop(columns='date_l'),
m.loc[~mask, left.columns].rename(columns={'date_l': 'date'}),
m.loc[~mask, right.columns]],
ignore_index=True, sort=False)


Output:



   id  val_3       date  val_1  val_2
0 1 77.0 2002-03-10 99.0 101.0
1 2 88.0 2003-04-27 66.0 102.0
2 3 11.0 2004-06-06 NaN NaN
3 3 NaN 2004-05-05 33.0 103.0





share|improve this answer


























  • Although I concluded that my use-case is a lot more complex, this answer achieves what I said i want so I will mark it as correct.

    – gorjan
    Jan 5 at 2:18












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
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54028648%2fpandas-outer-join-with-a-specified-range-of-difference-between-the-keys%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









0














I think merge on 'id' and then split the DataFrame as needed if the date doesn't fall within 30 days



import pandas as pd

# Rename so it's easier to split columns later
left = left.rename(columns={'date': 'date_l'})

m = left.merge(right, on='id', how='outer')
mask = m.date >= m.date_l - pd.Timedelta(days=30)

pd.concat([
m[mask].drop(columns='date_l'),
m.loc[~mask, left.columns].rename(columns={'date_l': 'date'}),
m.loc[~mask, right.columns]],
ignore_index=True, sort=False)


Output:



   id  val_3       date  val_1  val_2
0 1 77.0 2002-03-10 99.0 101.0
1 2 88.0 2003-04-27 66.0 102.0
2 3 11.0 2004-06-06 NaN NaN
3 3 NaN 2004-05-05 33.0 103.0





share|improve this answer


























  • Although I concluded that my use-case is a lot more complex, this answer achieves what I said i want so I will mark it as correct.

    – gorjan
    Jan 5 at 2:18
















0














I think merge on 'id' and then split the DataFrame as needed if the date doesn't fall within 30 days



import pandas as pd

# Rename so it's easier to split columns later
left = left.rename(columns={'date': 'date_l'})

m = left.merge(right, on='id', how='outer')
mask = m.date >= m.date_l - pd.Timedelta(days=30)

pd.concat([
m[mask].drop(columns='date_l'),
m.loc[~mask, left.columns].rename(columns={'date_l': 'date'}),
m.loc[~mask, right.columns]],
ignore_index=True, sort=False)


Output:



   id  val_3       date  val_1  val_2
0 1 77.0 2002-03-10 99.0 101.0
1 2 88.0 2003-04-27 66.0 102.0
2 3 11.0 2004-06-06 NaN NaN
3 3 NaN 2004-05-05 33.0 103.0





share|improve this answer


























  • Although I concluded that my use-case is a lot more complex, this answer achieves what I said i want so I will mark it as correct.

    – gorjan
    Jan 5 at 2:18














0












0








0







I think merge on 'id' and then split the DataFrame as needed if the date doesn't fall within 30 days



import pandas as pd

# Rename so it's easier to split columns later
left = left.rename(columns={'date': 'date_l'})

m = left.merge(right, on='id', how='outer')
mask = m.date >= m.date_l - pd.Timedelta(days=30)

pd.concat([
m[mask].drop(columns='date_l'),
m.loc[~mask, left.columns].rename(columns={'date_l': 'date'}),
m.loc[~mask, right.columns]],
ignore_index=True, sort=False)


Output:



   id  val_3       date  val_1  val_2
0 1 77.0 2002-03-10 99.0 101.0
1 2 88.0 2003-04-27 66.0 102.0
2 3 11.0 2004-06-06 NaN NaN
3 3 NaN 2004-05-05 33.0 103.0





share|improve this answer















I think merge on 'id' and then split the DataFrame as needed if the date doesn't fall within 30 days



import pandas as pd

# Rename so it's easier to split columns later
left = left.rename(columns={'date': 'date_l'})

m = left.merge(right, on='id', how='outer')
mask = m.date >= m.date_l - pd.Timedelta(days=30)

pd.concat([
m[mask].drop(columns='date_l'),
m.loc[~mask, left.columns].rename(columns={'date_l': 'date'}),
m.loc[~mask, right.columns]],
ignore_index=True, sort=False)


Output:



   id  val_3       date  val_1  val_2
0 1 77.0 2002-03-10 99.0 101.0
1 2 88.0 2003-04-27 66.0 102.0
2 3 11.0 2004-06-06 NaN NaN
3 3 NaN 2004-05-05 33.0 103.0






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 3 at 20:19

























answered Jan 3 at 19:52









ALollzALollz

16k31738




16k31738













  • Although I concluded that my use-case is a lot more complex, this answer achieves what I said i want so I will mark it as correct.

    – gorjan
    Jan 5 at 2:18



















  • Although I concluded that my use-case is a lot more complex, this answer achieves what I said i want so I will mark it as correct.

    – gorjan
    Jan 5 at 2:18

















Although I concluded that my use-case is a lot more complex, this answer achieves what I said i want so I will mark it as correct.

– gorjan
Jan 5 at 2:18





Although I concluded that my use-case is a lot more complex, this answer achieves what I said i want so I will mark it as correct.

– gorjan
Jan 5 at 2:18




















draft saved

draft discarded




















































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.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54028648%2fpandas-outer-join-with-a-specified-range-of-difference-between-the-keys%23new-answer', 'question_page');
}
);

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







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas