1

I'm studying Data Science with Python Pandas. But, I'm not good at handling data. So, I need some help.

df1

>>> df1
    stamp  id  col1  col2
0  100000   1   100    60
1  100000   2   100    30
2  100001   1    10    10
3  100001   1    20    30
4  100001   2    20    10
5  100001   2    20    90
6  100001   3    30    10
7  100002   1   300    30
8  100002   4    40    60

df2

>>> df2
    start     end  id  val
0  100000  100001   1    1
1  100002  100003   4    1

Using python3 pandas dataframe, How do I add a new column to the data that has the same 'id' value and 'stamp' values between 'start' and 'end' values?

@ Want to make result like this

>>> result
    stamp  id  col1  col2  val
0  100000   1   100    60    1
1  100000   2   100    30    0
2  100001   1    10    10    1
3  100001   1    20    30    1
4  100001   2    20    10    0
5  100001   2    20    90    0
6  100001   3    30    10    0
7  100002   1   300    30    0
8  100002   4    40    60    1

How can i make it?

2 Answers 2

2

Try

result = pd.DataFrame()

df2['stamp'] = df2['start']

result = pd.merge(df1,df2, on='stamp')
Sign up to request clarification or add additional context in comments.

1 Comment

pd.merge(df1,df2, on='stamp') | pd.merge(df1,df2, on=['stamp', 'id'], how='left') ==> Both ways are not correct.
0

melt the second dataframe(df2), so that start and end columns are 'melted' into one column; then proceed to merge the new dataframe with df1, with stamp and id as the merge columns, and fill the null values with 0

df2 = df2.melt(["id", "val"], value_name="stamp")

df1.merge(df2.drop("variable", axis=1), on=["stamp", "id"], how="left").fillna(0)


stamp   id  col1    col2    val
0   100000  1   100 60  1.0
1   100000  2   100 30  0.0
2   100001  1   10  10  1.0
3   100001  1   20  30  1.0
4   100001  2   20  10  0.0
5   100001  2   20  90  0.0
6   100001  3   30  10  0.0
7   100002  1   300 30  0.0
8   100002  4   40  60  1.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.