1

I'm using python 3.7 and pandas 1.0.1

I'm trying to fill a column in my dataframe following the results of two previous columns.

I have a date column, an In column (which registers when an activity is starting) and an Out column (which registers when an activity is finished).

I need a Res column, which will register the overall duration of the activity.

First I have this simple dataframe:

    data = {'date':['2020-01-01','2020-01-02','2020-01-03','2020-01-04','2020-01-05','2020-01-06','2020-01-07','2020-08-01','2020-01-09','2020-01-10'],
            'in':[0,0,1,0,0,0,0,1,0,0],
            'out':[0,0,0,0,0,1,0,0,1,0]}
    df = pd.DataFrame(data, columns=['date','in','out'])
    print(df)

The resulting dataframe is as follows:

         date  in  out
0  2020-01-01   0    0
1  2020-01-02   0    0
2  2020-01-03   1    0
3  2020-01-04   0    0
4  2020-01-05   0    0
5  2020-01-06   0    1
6  2020-01-07   0    0
7  2020-08-01   1    0
8  2020-01-09   0    1
9  2020-01-10   0    0

The result I'm trying to achieve is this:

         date  in  out  res
0  2020-01-01   0    0    0
1  2020-01-02   0    0    0
2  2020-01-03   1    0    1
3  2020-01-04   0    0    1
4  2020-01-05   0    0    1
5  2020-01-06   0    1    1
6  2020-01-07   0    0    0
7  2020-08-01   1    0    1
8  2020-01-09   0    1    1
9  2020-01-10   0    0    0

I was able to do it using iterrows:

    result = 0
    for index, row in df.iterrows():
        if (row['in']==1):
            result = 1
        elif (df['out'].shift(1)[index]==1):
            result = 0
        df.at[index,'res'] = result

But iterrows are not very time efficient when dealing with a very big dataframe.

How can I approach this problem in a better way?

2
  • Something like: df['res'] = np.where(df['in'].eq(1), 1, np.where(df['out'].shift(1).eq(1), 1, 0), 0?
    – jpp
    Jul 19, 2020 at 21:57
  • I'm sorry, but I couldn't make it work... But the function .eq is something I'll try to use more often as I didn't know about it... Thank you :)
    – Filipe
    Jul 20, 2020 at 14:28

1 Answer 1

0

Let's try some simple arithmetic here:

t = df['in'] + df['out']  
t.cumsum().where(t.eq(0), 1).eq(1).astype(int)

0    0
1    0
2    1
3    1
4    1
5    1
6    0
7    1
8    1
9    0
dtype: int64
1
  • Hey... That is pretty clever... I would never come up witha a solution like that... Thanks a lot for the help.. :)
    – Filipe
    Jul 20, 2020 at 14:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.